PackageManagerService.java revision 15bb16fb48f523b6b0d8c03cfe5988096341e29d
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.INSTALL_EXTERNAL;
29import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
30import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
32import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
36import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
37import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
38import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
39import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
40import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
43import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
44import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
45import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
46import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
47import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
48import static android.content.pm.PackageManager.INSTALL_INTERNAL;
49import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
52import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
53import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
54import static android.content.pm.PackageManager.MATCH_ALL;
55import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
56import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
57import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
58import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
59import static android.content.pm.PackageManager.PERMISSION_GRANTED;
60import static android.content.pm.PackageParser.isApkFile;
61import static android.os.Process.PACKAGE_INFO_GID;
62import static android.os.Process.SYSTEM_UID;
63import static android.system.OsConstants.O_CREAT;
64import static android.system.OsConstants.O_RDWR;
65import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
66import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
67import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
68import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
69import static com.android.internal.util.ArrayUtils.appendInt;
70import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
71import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
72import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
73import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
74import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
75
76import android.Manifest;
77import android.app.ActivityManager;
78import android.app.ActivityManagerNative;
79import android.app.AppGlobals;
80import android.app.IActivityManager;
81import android.app.admin.IDevicePolicyManager;
82import android.app.backup.IBackupManager;
83import android.app.usage.UsageStats;
84import android.app.usage.UsageStatsManager;
85import android.content.BroadcastReceiver;
86import android.content.ComponentName;
87import android.content.Context;
88import android.content.IIntentReceiver;
89import android.content.Intent;
90import android.content.IntentFilter;
91import android.content.IntentSender;
92import android.content.IntentSender.SendIntentException;
93import android.content.ServiceConnection;
94import android.content.pm.ActivityInfo;
95import android.content.pm.ApplicationInfo;
96import android.content.pm.FeatureInfo;
97import android.content.pm.IOnPermissionsChangeListener;
98import android.content.pm.IPackageDataObserver;
99import android.content.pm.IPackageDeleteObserver;
100import android.content.pm.IPackageDeleteObserver2;
101import android.content.pm.IPackageInstallObserver2;
102import android.content.pm.IPackageInstaller;
103import android.content.pm.IPackageManager;
104import android.content.pm.IPackageMoveObserver;
105import android.content.pm.IPackageStatsObserver;
106import android.content.pm.InstrumentationInfo;
107import android.content.pm.IntentFilterVerificationInfo;
108import android.content.pm.KeySet;
109import android.content.pm.ManifestDigest;
110import android.content.pm.PackageCleanItem;
111import android.content.pm.PackageInfo;
112import android.content.pm.PackageInfoLite;
113import android.content.pm.PackageInstaller;
114import android.content.pm.PackageManager;
115import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
116import android.content.pm.PackageManagerInternal;
117import android.content.pm.PackageParser;
118import android.content.pm.PackageParser.ActivityIntentInfo;
119import android.content.pm.PackageParser.PackageLite;
120import android.content.pm.PackageParser.PackageParserException;
121import android.content.pm.PackageStats;
122import android.content.pm.PackageUserState;
123import android.content.pm.ParceledListSlice;
124import android.content.pm.PermissionGroupInfo;
125import android.content.pm.PermissionInfo;
126import android.content.pm.ProviderInfo;
127import android.content.pm.ResolveInfo;
128import android.content.pm.ServiceInfo;
129import android.content.pm.Signature;
130import android.content.pm.UserInfo;
131import android.content.pm.VerificationParams;
132import android.content.pm.VerifierDeviceIdentity;
133import android.content.pm.VerifierInfo;
134import android.content.res.Resources;
135import android.hardware.display.DisplayManager;
136import android.net.Uri;
137import android.os.Binder;
138import android.os.Build;
139import android.os.Bundle;
140import android.os.Debug;
141import android.os.Environment;
142import android.os.Environment.UserEnvironment;
143import android.os.FileUtils;
144import android.os.Handler;
145import android.os.IBinder;
146import android.os.Looper;
147import android.os.Message;
148import android.os.Parcel;
149import android.os.ParcelFileDescriptor;
150import android.os.Process;
151import android.os.RemoteCallbackList;
152import android.os.RemoteException;
153import android.os.SELinux;
154import android.os.ServiceManager;
155import android.os.SystemClock;
156import android.os.SystemProperties;
157import android.os.UserHandle;
158import android.os.UserManager;
159import android.os.storage.IMountService;
160import android.os.storage.StorageEventListener;
161import android.os.storage.StorageManager;
162import android.os.storage.VolumeInfo;
163import android.os.storage.VolumeRecord;
164import android.security.KeyStore;
165import android.security.SystemKeyStore;
166import android.system.ErrnoException;
167import android.system.Os;
168import android.system.StructStat;
169import android.text.TextUtils;
170import android.text.format.DateUtils;
171import android.util.ArrayMap;
172import android.util.ArraySet;
173import android.util.AtomicFile;
174import android.util.DisplayMetrics;
175import android.util.EventLog;
176import android.util.ExceptionUtils;
177import android.util.Log;
178import android.util.LogPrinter;
179import android.util.MathUtils;
180import android.util.PrintStreamPrinter;
181import android.util.Slog;
182import android.util.SparseArray;
183import android.util.SparseBooleanArray;
184import android.util.SparseIntArray;
185import android.util.Xml;
186import android.view.Display;
187
188import dalvik.system.DexFile;
189import dalvik.system.VMRuntime;
190
191import libcore.io.IoUtils;
192import libcore.util.EmptyArray;
193
194import com.android.internal.R;
195import com.android.internal.annotations.GuardedBy;
196import com.android.internal.app.IMediaContainerService;
197import com.android.internal.app.ResolverActivity;
198import com.android.internal.content.NativeLibraryHelper;
199import com.android.internal.content.PackageHelper;
200import com.android.internal.os.IParcelFileDescriptorFactory;
201import com.android.internal.os.SomeArgs;
202import com.android.internal.os.Zygote;
203import com.android.internal.util.ArrayUtils;
204import com.android.internal.util.FastPrintWriter;
205import com.android.internal.util.FastXmlSerializer;
206import com.android.internal.util.IndentingPrintWriter;
207import com.android.internal.util.Preconditions;
208import com.android.server.EventLogTags;
209import com.android.server.FgThread;
210import com.android.server.IntentResolver;
211import com.android.server.LocalServices;
212import com.android.server.ServiceThread;
213import com.android.server.SystemConfig;
214import com.android.server.Watchdog;
215import com.android.server.pm.PermissionsState.PermissionState;
216import com.android.server.pm.Settings.DatabaseVersion;
217import com.android.server.storage.DeviceStorageMonitorInternal;
218
219import org.xmlpull.v1.XmlPullParser;
220import org.xmlpull.v1.XmlPullParserException;
221import org.xmlpull.v1.XmlSerializer;
222
223import java.io.BufferedInputStream;
224import java.io.BufferedOutputStream;
225import java.io.BufferedReader;
226import java.io.ByteArrayInputStream;
227import java.io.ByteArrayOutputStream;
228import java.io.File;
229import java.io.FileDescriptor;
230import java.io.FileNotFoundException;
231import java.io.FileOutputStream;
232import java.io.FileReader;
233import java.io.FilenameFilter;
234import java.io.IOException;
235import java.io.InputStream;
236import java.io.PrintWriter;
237import java.nio.charset.StandardCharsets;
238import java.security.NoSuchAlgorithmException;
239import java.security.PublicKey;
240import java.security.cert.CertificateEncodingException;
241import java.security.cert.CertificateException;
242import java.text.SimpleDateFormat;
243import java.util.ArrayList;
244import java.util.Arrays;
245import java.util.Collection;
246import java.util.Collections;
247import java.util.Comparator;
248import java.util.Date;
249import java.util.Iterator;
250import java.util.List;
251import java.util.Map;
252import java.util.Objects;
253import java.util.Set;
254import java.util.concurrent.CountDownLatch;
255import java.util.concurrent.TimeUnit;
256import java.util.concurrent.atomic.AtomicBoolean;
257import java.util.concurrent.atomic.AtomicInteger;
258import java.util.concurrent.atomic.AtomicLong;
259
260/**
261 * Keep track of all those .apks everywhere.
262 *
263 * This is very central to the platform's security; please run the unit
264 * tests whenever making modifications here:
265 *
266mmm frameworks/base/tests/AndroidTests
267adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
268adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
269 *
270 * {@hide}
271 */
272public class PackageManagerService extends IPackageManager.Stub {
273    static final String TAG = "PackageManager";
274    static final boolean DEBUG_SETTINGS = false;
275    static final boolean DEBUG_PREFERRED = false;
276    static final boolean DEBUG_UPGRADE = false;
277    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
278    private static final boolean DEBUG_BACKUP = true;
279    private static final boolean DEBUG_INSTALL = false;
280    private static final boolean DEBUG_REMOVE = false;
281    private static final boolean DEBUG_BROADCASTS = false;
282    private static final boolean DEBUG_SHOW_INFO = false;
283    private static final boolean DEBUG_PACKAGE_INFO = false;
284    private static final boolean DEBUG_INTENT_MATCHING = false;
285    private static final boolean DEBUG_PACKAGE_SCANNING = false;
286    private static final boolean DEBUG_VERIFY = false;
287    private static final boolean DEBUG_DEXOPT = false;
288    private static final boolean DEBUG_ABI_SELECTION = false;
289
290    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
291
292    private static final int RADIO_UID = Process.PHONE_UID;
293    private static final int LOG_UID = Process.LOG_UID;
294    private static final int NFC_UID = Process.NFC_UID;
295    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
296    private static final int SHELL_UID = Process.SHELL_UID;
297
298    // Cap the size of permission trees that 3rd party apps can define
299    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
300
301    // Suffix used during package installation when copying/moving
302    // package apks to install directory.
303    private static final String INSTALL_PACKAGE_SUFFIX = "-";
304
305    static final int SCAN_NO_DEX = 1<<1;
306    static final int SCAN_FORCE_DEX = 1<<2;
307    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
308    static final int SCAN_NEW_INSTALL = 1<<4;
309    static final int SCAN_NO_PATHS = 1<<5;
310    static final int SCAN_UPDATE_TIME = 1<<6;
311    static final int SCAN_DEFER_DEX = 1<<7;
312    static final int SCAN_BOOTING = 1<<8;
313    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
314    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
315    static final int SCAN_REQUIRE_KNOWN = 1<<12;
316    static final int SCAN_MOVE = 1<<13;
317    static final int SCAN_INITIAL = 1<<14;
318
319    static final int REMOVE_CHATTY = 1<<16;
320
321    private static final int[] EMPTY_INT_ARRAY = new int[0];
322
323    /**
324     * Timeout (in milliseconds) after which the watchdog should declare that
325     * our handler thread is wedged.  The usual default for such things is one
326     * minute but we sometimes do very lengthy I/O operations on this thread,
327     * such as installing multi-gigabyte applications, so ours needs to be longer.
328     */
329    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
330
331    /**
332     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
333     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
334     * settings entry if available, otherwise we use the hardcoded default.  If it's been
335     * more than this long since the last fstrim, we force one during the boot sequence.
336     *
337     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
338     * one gets run at the next available charging+idle time.  This final mandatory
339     * no-fstrim check kicks in only of the other scheduling criteria is never met.
340     */
341    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
342
343    /**
344     * Whether verification is enabled by default.
345     */
346    private static final boolean DEFAULT_VERIFY_ENABLE = true;
347
348    /**
349     * The default maximum time to wait for the verification agent to return in
350     * milliseconds.
351     */
352    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
353
354    /**
355     * The default response for package verification timeout.
356     *
357     * This can be either PackageManager.VERIFICATION_ALLOW or
358     * PackageManager.VERIFICATION_REJECT.
359     */
360    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
361
362    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
363
364    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
365            DEFAULT_CONTAINER_PACKAGE,
366            "com.android.defcontainer.DefaultContainerService");
367
368    private static final String KILL_APP_REASON_GIDS_CHANGED =
369            "permission grant or revoke changed gids";
370
371    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
372            "permissions revoked";
373
374    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
375
376    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
377
378    /** Permission grant: not grant the permission. */
379    private static final int GRANT_DENIED = 1;
380
381    /** Permission grant: grant the permission as an install permission. */
382    private static final int GRANT_INSTALL = 2;
383
384    /** Permission grant: grant the permission as an install permission for a legacy app. */
385    private static final int GRANT_INSTALL_LEGACY = 3;
386
387    /** Permission grant: grant the permission as a runtime one. */
388    private static final int GRANT_RUNTIME = 4;
389
390    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
391    private static final int GRANT_UPGRADE = 5;
392
393    /** Canonical intent used to identify what counts as a "web browser" app */
394    private static final Intent sBrowserIntent;
395    static {
396        sBrowserIntent = new Intent();
397        sBrowserIntent.setAction(Intent.ACTION_VIEW);
398        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
399        sBrowserIntent.setData(Uri.parse("http:"));
400    }
401
402    final ServiceThread mHandlerThread;
403
404    final PackageHandler mHandler;
405
406    /**
407     * Messages for {@link #mHandler} that need to wait for system ready before
408     * being dispatched.
409     */
410    private ArrayList<Message> mPostSystemReadyMessages;
411
412    final int mSdkVersion = Build.VERSION.SDK_INT;
413
414    final Context mContext;
415    final boolean mFactoryTest;
416    final boolean mOnlyCore;
417    final boolean mLazyDexOpt;
418    final long mDexOptLRUThresholdInMills;
419    final DisplayMetrics mMetrics;
420    final int mDefParseFlags;
421    final String[] mSeparateProcesses;
422    final boolean mIsUpgrade;
423
424    // This is where all application persistent data goes.
425    final File mAppDataDir;
426
427    // This is where all application persistent data goes for secondary users.
428    final File mUserAppDataDir;
429
430    /** The location for ASEC container files on internal storage. */
431    final String mAsecInternalPath;
432
433    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
434    // LOCK HELD.  Can be called with mInstallLock held.
435    @GuardedBy("mInstallLock")
436    final Installer mInstaller;
437
438    /** Directory where installed third-party apps stored */
439    final File mAppInstallDir;
440
441    /**
442     * Directory to which applications installed internally have their
443     * 32 bit native libraries copied.
444     */
445    private File mAppLib32InstallDir;
446
447    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
448    // apps.
449    final File mDrmAppPrivateInstallDir;
450
451    // ----------------------------------------------------------------
452
453    // Lock for state used when installing and doing other long running
454    // operations.  Methods that must be called with this lock held have
455    // the suffix "LI".
456    final Object mInstallLock = new Object();
457
458    // ----------------------------------------------------------------
459
460    // Keys are String (package name), values are Package.  This also serves
461    // as the lock for the global state.  Methods that must be called with
462    // this lock held have the prefix "LP".
463    @GuardedBy("mPackages")
464    final ArrayMap<String, PackageParser.Package> mPackages =
465            new ArrayMap<String, PackageParser.Package>();
466
467    // Tracks available target package names -> overlay package paths.
468    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
469        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
470
471    final Settings mSettings;
472    boolean mRestoredSettings;
473
474    // System configuration read by SystemConfig.
475    final int[] mGlobalGids;
476    final SparseArray<ArraySet<String>> mSystemPermissions;
477    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
478
479    // If mac_permissions.xml was found for seinfo labeling.
480    boolean mFoundPolicyFile;
481
482    // If a recursive restorecon of /data/data/<pkg> is needed.
483    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
484
485    public static final class SharedLibraryEntry {
486        public final String path;
487        public final String apk;
488
489        SharedLibraryEntry(String _path, String _apk) {
490            path = _path;
491            apk = _apk;
492        }
493    }
494
495    // Currently known shared libraries.
496    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
497            new ArrayMap<String, SharedLibraryEntry>();
498
499    // All available activities, for your resolving pleasure.
500    final ActivityIntentResolver mActivities =
501            new ActivityIntentResolver();
502
503    // All available receivers, for your resolving pleasure.
504    final ActivityIntentResolver mReceivers =
505            new ActivityIntentResolver();
506
507    // All available services, for your resolving pleasure.
508    final ServiceIntentResolver mServices = new ServiceIntentResolver();
509
510    // All available providers, for your resolving pleasure.
511    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
512
513    // Mapping from provider base names (first directory in content URI codePath)
514    // to the provider information.
515    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
516            new ArrayMap<String, PackageParser.Provider>();
517
518    // Mapping from instrumentation class names to info about them.
519    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
520            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
521
522    // Mapping from permission names to info about them.
523    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
524            new ArrayMap<String, PackageParser.PermissionGroup>();
525
526    // Packages whose data we have transfered into another package, thus
527    // should no longer exist.
528    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
529
530    // Broadcast actions that are only available to the system.
531    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
532
533    /** List of packages waiting for verification. */
534    final SparseArray<PackageVerificationState> mPendingVerification
535            = new SparseArray<PackageVerificationState>();
536
537    /** Set of packages associated with each app op permission. */
538    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
539
540    final PackageInstallerService mInstallerService;
541
542    private final PackageDexOptimizer mPackageDexOptimizer;
543
544    private AtomicInteger mNextMoveId = new AtomicInteger();
545    private final MoveCallbacks mMoveCallbacks;
546
547    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
548
549    // Cache of users who need badging.
550    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
551
552    /** Token for keys in mPendingVerification. */
553    private int mPendingVerificationToken = 0;
554
555    volatile boolean mSystemReady;
556    volatile boolean mSafeMode;
557    volatile boolean mHasSystemUidErrors;
558
559    ApplicationInfo mAndroidApplication;
560    final ActivityInfo mResolveActivity = new ActivityInfo();
561    final ResolveInfo mResolveInfo = new ResolveInfo();
562    ComponentName mResolveComponentName;
563    PackageParser.Package mPlatformPackage;
564    ComponentName mCustomResolverComponentName;
565
566    boolean mResolverReplaced = false;
567
568    private final ComponentName mIntentFilterVerifierComponent;
569    private int mIntentFilterVerificationToken = 0;
570
571    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
572            = new SparseArray<IntentFilterVerificationState>();
573
574    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
575            new DefaultPermissionGrantPolicy(this);
576
577    private static class IFVerificationParams {
578        PackageParser.Package pkg;
579        boolean replacing;
580        int userId;
581        int verifierUid;
582
583        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
584                int _userId, int _verifierUid) {
585            pkg = _pkg;
586            replacing = _replacing;
587            userId = _userId;
588            replacing = _replacing;
589            verifierUid = _verifierUid;
590        }
591    }
592
593    private interface IntentFilterVerifier<T extends IntentFilter> {
594        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
595                                               T filter, String packageName);
596        void startVerifications(int userId);
597        void receiveVerificationResponse(int verificationId);
598    }
599
600    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
601        private Context mContext;
602        private ComponentName mIntentFilterVerifierComponent;
603        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
604
605        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
606            mContext = context;
607            mIntentFilterVerifierComponent = verifierComponent;
608        }
609
610        private String getDefaultScheme() {
611            return IntentFilter.SCHEME_HTTPS;
612        }
613
614        @Override
615        public void startVerifications(int userId) {
616            // Launch verifications requests
617            int count = mCurrentIntentFilterVerifications.size();
618            for (int n=0; n<count; n++) {
619                int verificationId = mCurrentIntentFilterVerifications.get(n);
620                final IntentFilterVerificationState ivs =
621                        mIntentFilterVerificationStates.get(verificationId);
622
623                String packageName = ivs.getPackageName();
624
625                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
626                final int filterCount = filters.size();
627                ArraySet<String> domainsSet = new ArraySet<>();
628                for (int m=0; m<filterCount; m++) {
629                    PackageParser.ActivityIntentInfo filter = filters.get(m);
630                    domainsSet.addAll(filter.getHostsList());
631                }
632                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
633                synchronized (mPackages) {
634                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
635                            packageName, domainsList) != null) {
636                        scheduleWriteSettingsLocked();
637                    }
638                }
639                sendVerificationRequest(userId, verificationId, ivs);
640            }
641            mCurrentIntentFilterVerifications.clear();
642        }
643
644        private void sendVerificationRequest(int userId, int verificationId,
645                IntentFilterVerificationState ivs) {
646
647            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
648            verificationIntent.putExtra(
649                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
650                    verificationId);
651            verificationIntent.putExtra(
652                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
653                    getDefaultScheme());
654            verificationIntent.putExtra(
655                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
656                    ivs.getHostsString());
657            verificationIntent.putExtra(
658                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
659                    ivs.getPackageName());
660            verificationIntent.setComponent(mIntentFilterVerifierComponent);
661            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
662
663            UserHandle user = new UserHandle(userId);
664            mContext.sendBroadcastAsUser(verificationIntent, user);
665            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
666                    "Sending IntentFilter verification broadcast");
667        }
668
669        public void receiveVerificationResponse(int verificationId) {
670            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
671
672            final boolean verified = ivs.isVerified();
673
674            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
675            final int count = filters.size();
676            if (DEBUG_DOMAIN_VERIFICATION) {
677                Slog.i(TAG, "Received verification response " + verificationId
678                        + " for " + count + " filters, verified=" + verified);
679            }
680            for (int n=0; n<count; n++) {
681                PackageParser.ActivityIntentInfo filter = filters.get(n);
682                filter.setVerified(verified);
683
684                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
685                        + " verified with result:" + verified + " and hosts:"
686                        + ivs.getHostsString());
687            }
688
689            mIntentFilterVerificationStates.remove(verificationId);
690
691            final String packageName = ivs.getPackageName();
692            IntentFilterVerificationInfo ivi = null;
693
694            synchronized (mPackages) {
695                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
696            }
697            if (ivi == null) {
698                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
699                        + verificationId + " packageName:" + packageName);
700                return;
701            }
702            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
703                    "Updating IntentFilterVerificationInfo for verificationId:" + verificationId);
704
705            synchronized (mPackages) {
706                if (verified) {
707                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
708                } else {
709                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
710                }
711                scheduleWriteSettingsLocked();
712
713                final int userId = ivs.getUserId();
714                if (userId != UserHandle.USER_ALL) {
715                    final int userStatus =
716                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
717
718                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
719                    boolean needUpdate = false;
720
721                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
722                    // already been set by the User thru the Disambiguation dialog
723                    switch (userStatus) {
724                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
725                            if (verified) {
726                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
727                            } else {
728                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
729                            }
730                            needUpdate = true;
731                            break;
732
733                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
734                            if (verified) {
735                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
736                                needUpdate = true;
737                            }
738                            break;
739
740                        default:
741                            // Nothing to do
742                    }
743
744                    if (needUpdate) {
745                        mSettings.updateIntentFilterVerificationStatusLPw(
746                                packageName, updatedStatus, userId);
747                        scheduleWritePackageRestrictionsLocked(userId);
748                    }
749                }
750            }
751        }
752
753        @Override
754        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
755                    ActivityIntentInfo filter, String packageName) {
756            if (!hasValidDomains(filter)) {
757                return false;
758            }
759            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
760            if (ivs == null) {
761                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
762                        packageName);
763            }
764            if (DEBUG_DOMAIN_VERIFICATION) {
765                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
766            }
767            ivs.addFilter(filter);
768            return true;
769        }
770
771        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
772                int userId, int verificationId, String packageName) {
773            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
774                    verifierUid, userId, packageName);
775            ivs.setPendingState();
776            synchronized (mPackages) {
777                mIntentFilterVerificationStates.append(verificationId, ivs);
778                mCurrentIntentFilterVerifications.add(verificationId);
779            }
780            return ivs;
781        }
782    }
783
784    private static boolean hasValidDomains(ActivityIntentInfo filter) {
785        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
786                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
787        if (!hasHTTPorHTTPS) {
788            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
789                    "IntentFilter does not contain any HTTP or HTTPS data scheme");
790            return false;
791        }
792        return true;
793    }
794
795    private IntentFilterVerifier mIntentFilterVerifier;
796
797    // Set of pending broadcasts for aggregating enable/disable of components.
798    static class PendingPackageBroadcasts {
799        // for each user id, a map of <package name -> components within that package>
800        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
801
802        public PendingPackageBroadcasts() {
803            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
804        }
805
806        public ArrayList<String> get(int userId, String packageName) {
807            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
808            return packages.get(packageName);
809        }
810
811        public void put(int userId, String packageName, ArrayList<String> components) {
812            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
813            packages.put(packageName, components);
814        }
815
816        public void remove(int userId, String packageName) {
817            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
818            if (packages != null) {
819                packages.remove(packageName);
820            }
821        }
822
823        public void remove(int userId) {
824            mUidMap.remove(userId);
825        }
826
827        public int userIdCount() {
828            return mUidMap.size();
829        }
830
831        public int userIdAt(int n) {
832            return mUidMap.keyAt(n);
833        }
834
835        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
836            return mUidMap.get(userId);
837        }
838
839        public int size() {
840            // total number of pending broadcast entries across all userIds
841            int num = 0;
842            for (int i = 0; i< mUidMap.size(); i++) {
843                num += mUidMap.valueAt(i).size();
844            }
845            return num;
846        }
847
848        public void clear() {
849            mUidMap.clear();
850        }
851
852        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
853            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
854            if (map == null) {
855                map = new ArrayMap<String, ArrayList<String>>();
856                mUidMap.put(userId, map);
857            }
858            return map;
859        }
860    }
861    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
862
863    // Service Connection to remote media container service to copy
864    // package uri's from external media onto secure containers
865    // or internal storage.
866    private IMediaContainerService mContainerService = null;
867
868    static final int SEND_PENDING_BROADCAST = 1;
869    static final int MCS_BOUND = 3;
870    static final int END_COPY = 4;
871    static final int INIT_COPY = 5;
872    static final int MCS_UNBIND = 6;
873    static final int START_CLEANING_PACKAGE = 7;
874    static final int FIND_INSTALL_LOC = 8;
875    static final int POST_INSTALL = 9;
876    static final int MCS_RECONNECT = 10;
877    static final int MCS_GIVE_UP = 11;
878    static final int UPDATED_MEDIA_STATUS = 12;
879    static final int WRITE_SETTINGS = 13;
880    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
881    static final int PACKAGE_VERIFIED = 15;
882    static final int CHECK_PENDING_VERIFICATION = 16;
883    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
884    static final int INTENT_FILTER_VERIFIED = 18;
885
886    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
887
888    // Delay time in millisecs
889    static final int BROADCAST_DELAY = 10 * 1000;
890
891    static UserManagerService sUserManager;
892
893    // Stores a list of users whose package restrictions file needs to be updated
894    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
895
896    final private DefaultContainerConnection mDefContainerConn =
897            new DefaultContainerConnection();
898    class DefaultContainerConnection implements ServiceConnection {
899        public void onServiceConnected(ComponentName name, IBinder service) {
900            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
901            IMediaContainerService imcs =
902                IMediaContainerService.Stub.asInterface(service);
903            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
904        }
905
906        public void onServiceDisconnected(ComponentName name) {
907            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
908        }
909    }
910
911    // Recordkeeping of restore-after-install operations that are currently in flight
912    // between the Package Manager and the Backup Manager
913    class PostInstallData {
914        public InstallArgs args;
915        public PackageInstalledInfo res;
916
917        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
918            args = _a;
919            res = _r;
920        }
921    }
922
923    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
924    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
925
926    // XML tags for backup/restore of various bits of state
927    private static final String TAG_PREFERRED_BACKUP = "pa";
928    private static final String TAG_DEFAULT_APPS = "da";
929    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
930
931    private final String mRequiredVerifierPackage;
932
933    private final PackageUsage mPackageUsage = new PackageUsage();
934
935    private class PackageUsage {
936        private static final int WRITE_INTERVAL
937            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
938
939        private final Object mFileLock = new Object();
940        private final AtomicLong mLastWritten = new AtomicLong(0);
941        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
942
943        private boolean mIsHistoricalPackageUsageAvailable = true;
944
945        boolean isHistoricalPackageUsageAvailable() {
946            return mIsHistoricalPackageUsageAvailable;
947        }
948
949        void write(boolean force) {
950            if (force) {
951                writeInternal();
952                return;
953            }
954            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
955                && !DEBUG_DEXOPT) {
956                return;
957            }
958            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
959                new Thread("PackageUsage_DiskWriter") {
960                    @Override
961                    public void run() {
962                        try {
963                            writeInternal();
964                        } finally {
965                            mBackgroundWriteRunning.set(false);
966                        }
967                    }
968                }.start();
969            }
970        }
971
972        private void writeInternal() {
973            synchronized (mPackages) {
974                synchronized (mFileLock) {
975                    AtomicFile file = getFile();
976                    FileOutputStream f = null;
977                    try {
978                        f = file.startWrite();
979                        BufferedOutputStream out = new BufferedOutputStream(f);
980                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
981                        StringBuilder sb = new StringBuilder();
982                        for (PackageParser.Package pkg : mPackages.values()) {
983                            if (pkg.mLastPackageUsageTimeInMills == 0) {
984                                continue;
985                            }
986                            sb.setLength(0);
987                            sb.append(pkg.packageName);
988                            sb.append(' ');
989                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
990                            sb.append('\n');
991                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
992                        }
993                        out.flush();
994                        file.finishWrite(f);
995                    } catch (IOException e) {
996                        if (f != null) {
997                            file.failWrite(f);
998                        }
999                        Log.e(TAG, "Failed to write package usage times", e);
1000                    }
1001                }
1002            }
1003            mLastWritten.set(SystemClock.elapsedRealtime());
1004        }
1005
1006        void readLP() {
1007            synchronized (mFileLock) {
1008                AtomicFile file = getFile();
1009                BufferedInputStream in = null;
1010                try {
1011                    in = new BufferedInputStream(file.openRead());
1012                    StringBuffer sb = new StringBuffer();
1013                    while (true) {
1014                        String packageName = readToken(in, sb, ' ');
1015                        if (packageName == null) {
1016                            break;
1017                        }
1018                        String timeInMillisString = readToken(in, sb, '\n');
1019                        if (timeInMillisString == null) {
1020                            throw new IOException("Failed to find last usage time for package "
1021                                                  + packageName);
1022                        }
1023                        PackageParser.Package pkg = mPackages.get(packageName);
1024                        if (pkg == null) {
1025                            continue;
1026                        }
1027                        long timeInMillis;
1028                        try {
1029                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1030                        } catch (NumberFormatException e) {
1031                            throw new IOException("Failed to parse " + timeInMillisString
1032                                                  + " as a long.", e);
1033                        }
1034                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1035                    }
1036                } catch (FileNotFoundException expected) {
1037                    mIsHistoricalPackageUsageAvailable = false;
1038                } catch (IOException e) {
1039                    Log.w(TAG, "Failed to read package usage times", e);
1040                } finally {
1041                    IoUtils.closeQuietly(in);
1042                }
1043            }
1044            mLastWritten.set(SystemClock.elapsedRealtime());
1045        }
1046
1047        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1048                throws IOException {
1049            sb.setLength(0);
1050            while (true) {
1051                int ch = in.read();
1052                if (ch == -1) {
1053                    if (sb.length() == 0) {
1054                        return null;
1055                    }
1056                    throw new IOException("Unexpected EOF");
1057                }
1058                if (ch == endOfToken) {
1059                    return sb.toString();
1060                }
1061                sb.append((char)ch);
1062            }
1063        }
1064
1065        private AtomicFile getFile() {
1066            File dataDir = Environment.getDataDirectory();
1067            File systemDir = new File(dataDir, "system");
1068            File fname = new File(systemDir, "package-usage.list");
1069            return new AtomicFile(fname);
1070        }
1071    }
1072
1073    class PackageHandler extends Handler {
1074        private boolean mBound = false;
1075        final ArrayList<HandlerParams> mPendingInstalls =
1076            new ArrayList<HandlerParams>();
1077
1078        private boolean connectToService() {
1079            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1080                    " DefaultContainerService");
1081            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1082            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1083            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1084                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1085                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1086                mBound = true;
1087                return true;
1088            }
1089            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1090            return false;
1091        }
1092
1093        private void disconnectService() {
1094            mContainerService = null;
1095            mBound = false;
1096            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1097            mContext.unbindService(mDefContainerConn);
1098            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1099        }
1100
1101        PackageHandler(Looper looper) {
1102            super(looper);
1103        }
1104
1105        public void handleMessage(Message msg) {
1106            try {
1107                doHandleMessage(msg);
1108            } finally {
1109                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1110            }
1111        }
1112
1113        void doHandleMessage(Message msg) {
1114            switch (msg.what) {
1115                case INIT_COPY: {
1116                    HandlerParams params = (HandlerParams) msg.obj;
1117                    int idx = mPendingInstalls.size();
1118                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1119                    // If a bind was already initiated we dont really
1120                    // need to do anything. The pending install
1121                    // will be processed later on.
1122                    if (!mBound) {
1123                        // If this is the only one pending we might
1124                        // have to bind to the service again.
1125                        if (!connectToService()) {
1126                            Slog.e(TAG, "Failed to bind to media container service");
1127                            params.serviceError();
1128                            return;
1129                        } else {
1130                            // Once we bind to the service, the first
1131                            // pending request will be processed.
1132                            mPendingInstalls.add(idx, params);
1133                        }
1134                    } else {
1135                        mPendingInstalls.add(idx, params);
1136                        // Already bound to the service. Just make
1137                        // sure we trigger off processing the first request.
1138                        if (idx == 0) {
1139                            mHandler.sendEmptyMessage(MCS_BOUND);
1140                        }
1141                    }
1142                    break;
1143                }
1144                case MCS_BOUND: {
1145                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1146                    if (msg.obj != null) {
1147                        mContainerService = (IMediaContainerService) msg.obj;
1148                    }
1149                    if (mContainerService == null) {
1150                        if (!mBound) {
1151                            // Something seriously wrong since we are not bound and we are not
1152                            // waiting for connection. Bail out.
1153                            Slog.e(TAG, "Cannot bind to media container service");
1154                            for (HandlerParams params : mPendingInstalls) {
1155                                // Indicate service bind error
1156                                params.serviceError();
1157                            }
1158                            mPendingInstalls.clear();
1159                        } else {
1160                            Slog.w(TAG, "Waiting to connect to media container service");
1161                        }
1162                    } else if (mPendingInstalls.size() > 0) {
1163                        HandlerParams params = mPendingInstalls.get(0);
1164                        if (params != null) {
1165                            if (params.startCopy()) {
1166                                // We are done...  look for more work or to
1167                                // go idle.
1168                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1169                                        "Checking for more work or unbind...");
1170                                // Delete pending install
1171                                if (mPendingInstalls.size() > 0) {
1172                                    mPendingInstalls.remove(0);
1173                                }
1174                                if (mPendingInstalls.size() == 0) {
1175                                    if (mBound) {
1176                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1177                                                "Posting delayed MCS_UNBIND");
1178                                        removeMessages(MCS_UNBIND);
1179                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1180                                        // Unbind after a little delay, to avoid
1181                                        // continual thrashing.
1182                                        sendMessageDelayed(ubmsg, 10000);
1183                                    }
1184                                } else {
1185                                    // There are more pending requests in queue.
1186                                    // Just post MCS_BOUND message to trigger processing
1187                                    // of next pending install.
1188                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1189                                            "Posting MCS_BOUND for next work");
1190                                    mHandler.sendEmptyMessage(MCS_BOUND);
1191                                }
1192                            }
1193                        }
1194                    } else {
1195                        // Should never happen ideally.
1196                        Slog.w(TAG, "Empty queue");
1197                    }
1198                    break;
1199                }
1200                case MCS_RECONNECT: {
1201                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1202                    if (mPendingInstalls.size() > 0) {
1203                        if (mBound) {
1204                            disconnectService();
1205                        }
1206                        if (!connectToService()) {
1207                            Slog.e(TAG, "Failed to bind to media container service");
1208                            for (HandlerParams params : mPendingInstalls) {
1209                                // Indicate service bind error
1210                                params.serviceError();
1211                            }
1212                            mPendingInstalls.clear();
1213                        }
1214                    }
1215                    break;
1216                }
1217                case MCS_UNBIND: {
1218                    // If there is no actual work left, then time to unbind.
1219                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1220
1221                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1222                        if (mBound) {
1223                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1224
1225                            disconnectService();
1226                        }
1227                    } else if (mPendingInstalls.size() > 0) {
1228                        // There are more pending requests in queue.
1229                        // Just post MCS_BOUND message to trigger processing
1230                        // of next pending install.
1231                        mHandler.sendEmptyMessage(MCS_BOUND);
1232                    }
1233
1234                    break;
1235                }
1236                case MCS_GIVE_UP: {
1237                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1238                    mPendingInstalls.remove(0);
1239                    break;
1240                }
1241                case SEND_PENDING_BROADCAST: {
1242                    String packages[];
1243                    ArrayList<String> components[];
1244                    int size = 0;
1245                    int uids[];
1246                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1247                    synchronized (mPackages) {
1248                        if (mPendingBroadcasts == null) {
1249                            return;
1250                        }
1251                        size = mPendingBroadcasts.size();
1252                        if (size <= 0) {
1253                            // Nothing to be done. Just return
1254                            return;
1255                        }
1256                        packages = new String[size];
1257                        components = new ArrayList[size];
1258                        uids = new int[size];
1259                        int i = 0;  // filling out the above arrays
1260
1261                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1262                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1263                            Iterator<Map.Entry<String, ArrayList<String>>> it
1264                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1265                                            .entrySet().iterator();
1266                            while (it.hasNext() && i < size) {
1267                                Map.Entry<String, ArrayList<String>> ent = it.next();
1268                                packages[i] = ent.getKey();
1269                                components[i] = ent.getValue();
1270                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1271                                uids[i] = (ps != null)
1272                                        ? UserHandle.getUid(packageUserId, ps.appId)
1273                                        : -1;
1274                                i++;
1275                            }
1276                        }
1277                        size = i;
1278                        mPendingBroadcasts.clear();
1279                    }
1280                    // Send broadcasts
1281                    for (int i = 0; i < size; i++) {
1282                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1283                    }
1284                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1285                    break;
1286                }
1287                case START_CLEANING_PACKAGE: {
1288                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1289                    final String packageName = (String)msg.obj;
1290                    final int userId = msg.arg1;
1291                    final boolean andCode = msg.arg2 != 0;
1292                    synchronized (mPackages) {
1293                        if (userId == UserHandle.USER_ALL) {
1294                            int[] users = sUserManager.getUserIds();
1295                            for (int user : users) {
1296                                mSettings.addPackageToCleanLPw(
1297                                        new PackageCleanItem(user, packageName, andCode));
1298                            }
1299                        } else {
1300                            mSettings.addPackageToCleanLPw(
1301                                    new PackageCleanItem(userId, packageName, andCode));
1302                        }
1303                    }
1304                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1305                    startCleaningPackages();
1306                } break;
1307                case POST_INSTALL: {
1308                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1309                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1310                    mRunningInstalls.delete(msg.arg1);
1311                    boolean deleteOld = false;
1312
1313                    if (data != null) {
1314                        InstallArgs args = data.args;
1315                        PackageInstalledInfo res = data.res;
1316
1317                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1318                            final String packageName = res.pkg.applicationInfo.packageName;
1319                            res.removedInfo.sendBroadcast(false, true, false);
1320                            Bundle extras = new Bundle(1);
1321                            extras.putInt(Intent.EXTRA_UID, res.uid);
1322
1323                            // Now that we successfully installed the package, grant runtime
1324                            // permissions if requested before broadcasting the install.
1325                            if ((args.installFlags
1326                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1327                                grantRequestedRuntimePermissions(res.pkg,
1328                                        args.user.getIdentifier());
1329                            }
1330
1331                            // Determine the set of users who are adding this
1332                            // package for the first time vs. those who are seeing
1333                            // an update.
1334                            int[] firstUsers;
1335                            int[] updateUsers = new int[0];
1336                            if (res.origUsers == null || res.origUsers.length == 0) {
1337                                firstUsers = res.newUsers;
1338                            } else {
1339                                firstUsers = new int[0];
1340                                for (int i=0; i<res.newUsers.length; i++) {
1341                                    int user = res.newUsers[i];
1342                                    boolean isNew = true;
1343                                    for (int j=0; j<res.origUsers.length; j++) {
1344                                        if (res.origUsers[j] == user) {
1345                                            isNew = false;
1346                                            break;
1347                                        }
1348                                    }
1349                                    if (isNew) {
1350                                        int[] newFirst = new int[firstUsers.length+1];
1351                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1352                                                firstUsers.length);
1353                                        newFirst[firstUsers.length] = user;
1354                                        firstUsers = newFirst;
1355                                    } else {
1356                                        int[] newUpdate = new int[updateUsers.length+1];
1357                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1358                                                updateUsers.length);
1359                                        newUpdate[updateUsers.length] = user;
1360                                        updateUsers = newUpdate;
1361                                    }
1362                                }
1363                            }
1364                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1365                                    packageName, extras, null, null, firstUsers);
1366                            final boolean update = res.removedInfo.removedPackage != null;
1367                            if (update) {
1368                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1369                            }
1370                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1371                                    packageName, extras, null, null, updateUsers);
1372                            if (update) {
1373                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1374                                        packageName, extras, null, null, updateUsers);
1375                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1376                                        null, null, packageName, null, updateUsers);
1377
1378                                // treat asec-hosted packages like removable media on upgrade
1379                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1380                                    if (DEBUG_INSTALL) {
1381                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1382                                                + " is ASEC-hosted -> AVAILABLE");
1383                                    }
1384                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1385                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1386                                    pkgList.add(packageName);
1387                                    sendResourcesChangedBroadcast(true, true,
1388                                            pkgList,uidArray, null);
1389                                }
1390                            }
1391                            if (res.removedInfo.args != null) {
1392                                // Remove the replaced package's older resources safely now
1393                                deleteOld = true;
1394                            }
1395
1396                            // If this app is a browser and it's newly-installed for some
1397                            // users, clear any default-browser state in those users
1398                            if (firstUsers.length > 0) {
1399                                // the app's nature doesn't depend on the user, so we can just
1400                                // check its browser nature in any user and generalize.
1401                                if (packageIsBrowser(packageName, firstUsers[0])) {
1402                                    synchronized (mPackages) {
1403                                        for (int userId : firstUsers) {
1404                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1405                                        }
1406                                    }
1407                                }
1408                            }
1409                            // Log current value of "unknown sources" setting
1410                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1411                                getUnknownSourcesSettings());
1412                        }
1413                        // Force a gc to clear up things
1414                        Runtime.getRuntime().gc();
1415                        // We delete after a gc for applications  on sdcard.
1416                        if (deleteOld) {
1417                            synchronized (mInstallLock) {
1418                                res.removedInfo.args.doPostDeleteLI(true);
1419                            }
1420                        }
1421                        if (args.observer != null) {
1422                            try {
1423                                Bundle extras = extrasForInstallResult(res);
1424                                args.observer.onPackageInstalled(res.name, res.returnCode,
1425                                        res.returnMsg, extras);
1426                            } catch (RemoteException e) {
1427                                Slog.i(TAG, "Observer no longer exists.");
1428                            }
1429                        }
1430                    } else {
1431                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1432                    }
1433                } break;
1434                case UPDATED_MEDIA_STATUS: {
1435                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1436                    boolean reportStatus = msg.arg1 == 1;
1437                    boolean doGc = msg.arg2 == 1;
1438                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1439                    if (doGc) {
1440                        // Force a gc to clear up stale containers.
1441                        Runtime.getRuntime().gc();
1442                    }
1443                    if (msg.obj != null) {
1444                        @SuppressWarnings("unchecked")
1445                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1446                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1447                        // Unload containers
1448                        unloadAllContainers(args);
1449                    }
1450                    if (reportStatus) {
1451                        try {
1452                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1453                            PackageHelper.getMountService().finishMediaUpdate();
1454                        } catch (RemoteException e) {
1455                            Log.e(TAG, "MountService not running?");
1456                        }
1457                    }
1458                } break;
1459                case WRITE_SETTINGS: {
1460                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1461                    synchronized (mPackages) {
1462                        removeMessages(WRITE_SETTINGS);
1463                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1464                        mSettings.writeLPr();
1465                        mDirtyUsers.clear();
1466                    }
1467                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1468                } break;
1469                case WRITE_PACKAGE_RESTRICTIONS: {
1470                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1471                    synchronized (mPackages) {
1472                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1473                        for (int userId : mDirtyUsers) {
1474                            mSettings.writePackageRestrictionsLPr(userId);
1475                        }
1476                        mDirtyUsers.clear();
1477                    }
1478                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1479                } break;
1480                case CHECK_PENDING_VERIFICATION: {
1481                    final int verificationId = msg.arg1;
1482                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1483
1484                    if ((state != null) && !state.timeoutExtended()) {
1485                        final InstallArgs args = state.getInstallArgs();
1486                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1487
1488                        Slog.i(TAG, "Verification timed out for " + originUri);
1489                        mPendingVerification.remove(verificationId);
1490
1491                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1492
1493                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1494                            Slog.i(TAG, "Continuing with installation of " + originUri);
1495                            state.setVerifierResponse(Binder.getCallingUid(),
1496                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1497                            broadcastPackageVerified(verificationId, originUri,
1498                                    PackageManager.VERIFICATION_ALLOW,
1499                                    state.getInstallArgs().getUser());
1500                            try {
1501                                ret = args.copyApk(mContainerService, true);
1502                            } catch (RemoteException e) {
1503                                Slog.e(TAG, "Could not contact the ContainerService");
1504                            }
1505                        } else {
1506                            broadcastPackageVerified(verificationId, originUri,
1507                                    PackageManager.VERIFICATION_REJECT,
1508                                    state.getInstallArgs().getUser());
1509                        }
1510
1511                        processPendingInstall(args, ret);
1512                        mHandler.sendEmptyMessage(MCS_UNBIND);
1513                    }
1514                    break;
1515                }
1516                case PACKAGE_VERIFIED: {
1517                    final int verificationId = msg.arg1;
1518
1519                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1520                    if (state == null) {
1521                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1522                        break;
1523                    }
1524
1525                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1526
1527                    state.setVerifierResponse(response.callerUid, response.code);
1528
1529                    if (state.isVerificationComplete()) {
1530                        mPendingVerification.remove(verificationId);
1531
1532                        final InstallArgs args = state.getInstallArgs();
1533                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1534
1535                        int ret;
1536                        if (state.isInstallAllowed()) {
1537                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1538                            broadcastPackageVerified(verificationId, originUri,
1539                                    response.code, state.getInstallArgs().getUser());
1540                            try {
1541                                ret = args.copyApk(mContainerService, true);
1542                            } catch (RemoteException e) {
1543                                Slog.e(TAG, "Could not contact the ContainerService");
1544                            }
1545                        } else {
1546                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1547                        }
1548
1549                        processPendingInstall(args, ret);
1550
1551                        mHandler.sendEmptyMessage(MCS_UNBIND);
1552                    }
1553
1554                    break;
1555                }
1556                case START_INTENT_FILTER_VERIFICATIONS: {
1557                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1558                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1559                            params.replacing, params.pkg);
1560                    break;
1561                }
1562                case INTENT_FILTER_VERIFIED: {
1563                    final int verificationId = msg.arg1;
1564
1565                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1566                            verificationId);
1567                    if (state == null) {
1568                        Slog.w(TAG, "Invalid IntentFilter verification token "
1569                                + verificationId + " received");
1570                        break;
1571                    }
1572
1573                    final int userId = state.getUserId();
1574
1575                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1576                            "Processing IntentFilter verification with token:"
1577                            + verificationId + " and userId:" + userId);
1578
1579                    final IntentFilterVerificationResponse response =
1580                            (IntentFilterVerificationResponse) msg.obj;
1581
1582                    state.setVerifierResponse(response.callerUid, response.code);
1583
1584                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1585                            "IntentFilter verification with token:" + verificationId
1586                            + " and userId:" + userId
1587                            + " is settings verifier response with response code:"
1588                            + response.code);
1589
1590                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1591                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1592                                + response.getFailedDomainsString());
1593                    }
1594
1595                    if (state.isVerificationComplete()) {
1596                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1597                    } else {
1598                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1599                                "IntentFilter verification with token:" + verificationId
1600                                + " was not said to be complete");
1601                    }
1602
1603                    break;
1604                }
1605            }
1606        }
1607    }
1608
1609    private StorageEventListener mStorageListener = new StorageEventListener() {
1610        @Override
1611        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1612            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1613                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1614                    final String volumeUuid = vol.getFsUuid();
1615
1616                    // Clean up any users or apps that were removed or recreated
1617                    // while this volume was missing
1618                    reconcileUsers(volumeUuid);
1619                    reconcileApps(volumeUuid);
1620
1621                    // Clean up any install sessions that expired or were
1622                    // cancelled while this volume was missing
1623                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1624
1625                    loadPrivatePackages(vol);
1626
1627                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1628                    unloadPrivatePackages(vol);
1629                }
1630            }
1631
1632            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1633                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1634                    updateExternalMediaStatus(true, false);
1635                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1636                    updateExternalMediaStatus(false, false);
1637                }
1638            }
1639        }
1640
1641        @Override
1642        public void onVolumeForgotten(String fsUuid) {
1643            // Remove any apps installed on the forgotten volume
1644            synchronized (mPackages) {
1645                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1646                for (PackageSetting ps : packages) {
1647                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1648                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1649                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1650                }
1651
1652                mSettings.writeLPr();
1653            }
1654        }
1655    };
1656
1657    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1658        if (userId >= UserHandle.USER_OWNER) {
1659            grantRequestedRuntimePermissionsForUser(pkg, userId);
1660        } else if (userId == UserHandle.USER_ALL) {
1661            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1662                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1663            }
1664        }
1665
1666        // We could have touched GID membership, so flush out packages.list
1667        synchronized (mPackages) {
1668            mSettings.writePackageListLPr();
1669        }
1670    }
1671
1672    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1673        SettingBase sb = (SettingBase) pkg.mExtras;
1674        if (sb == null) {
1675            return;
1676        }
1677
1678        PermissionsState permissionsState = sb.getPermissionsState();
1679
1680        for (String permission : pkg.requestedPermissions) {
1681            BasePermission bp = mSettings.mPermissions.get(permission);
1682            if (bp != null && bp.isRuntime()) {
1683                permissionsState.grantRuntimePermission(bp, userId);
1684            }
1685        }
1686    }
1687
1688    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1689        Bundle extras = null;
1690        switch (res.returnCode) {
1691            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1692                extras = new Bundle();
1693                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1694                        res.origPermission);
1695                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1696                        res.origPackage);
1697                break;
1698            }
1699            case PackageManager.INSTALL_SUCCEEDED: {
1700                extras = new Bundle();
1701                extras.putBoolean(Intent.EXTRA_REPLACING,
1702                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1703                break;
1704            }
1705        }
1706        return extras;
1707    }
1708
1709    void scheduleWriteSettingsLocked() {
1710        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1711            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1712        }
1713    }
1714
1715    void scheduleWritePackageRestrictionsLocked(int userId) {
1716        if (!sUserManager.exists(userId)) return;
1717        mDirtyUsers.add(userId);
1718        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1719            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1720        }
1721    }
1722
1723    public static PackageManagerService main(Context context, Installer installer,
1724            boolean factoryTest, boolean onlyCore) {
1725        PackageManagerService m = new PackageManagerService(context, installer,
1726                factoryTest, onlyCore);
1727        ServiceManager.addService("package", m);
1728        return m;
1729    }
1730
1731    static String[] splitString(String str, char sep) {
1732        int count = 1;
1733        int i = 0;
1734        while ((i=str.indexOf(sep, i)) >= 0) {
1735            count++;
1736            i++;
1737        }
1738
1739        String[] res = new String[count];
1740        i=0;
1741        count = 0;
1742        int lastI=0;
1743        while ((i=str.indexOf(sep, i)) >= 0) {
1744            res[count] = str.substring(lastI, i);
1745            count++;
1746            i++;
1747            lastI = i;
1748        }
1749        res[count] = str.substring(lastI, str.length());
1750        return res;
1751    }
1752
1753    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1754        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1755                Context.DISPLAY_SERVICE);
1756        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1757    }
1758
1759    public PackageManagerService(Context context, Installer installer,
1760            boolean factoryTest, boolean onlyCore) {
1761        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1762                SystemClock.uptimeMillis());
1763
1764        if (mSdkVersion <= 0) {
1765            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1766        }
1767
1768        mContext = context;
1769        mFactoryTest = factoryTest;
1770        mOnlyCore = onlyCore;
1771        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1772        mMetrics = new DisplayMetrics();
1773        mSettings = new Settings(mPackages);
1774        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1775                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1776        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1777                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1778        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1779                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1780        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1781                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1782        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1783                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1784        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1785                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1786
1787        // TODO: add a property to control this?
1788        long dexOptLRUThresholdInMinutes;
1789        if (mLazyDexOpt) {
1790            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1791        } else {
1792            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1793        }
1794        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1795
1796        String separateProcesses = SystemProperties.get("debug.separate_processes");
1797        if (separateProcesses != null && separateProcesses.length() > 0) {
1798            if ("*".equals(separateProcesses)) {
1799                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1800                mSeparateProcesses = null;
1801                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1802            } else {
1803                mDefParseFlags = 0;
1804                mSeparateProcesses = separateProcesses.split(",");
1805                Slog.w(TAG, "Running with debug.separate_processes: "
1806                        + separateProcesses);
1807            }
1808        } else {
1809            mDefParseFlags = 0;
1810            mSeparateProcesses = null;
1811        }
1812
1813        mInstaller = installer;
1814        mPackageDexOptimizer = new PackageDexOptimizer(this);
1815        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1816
1817        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1818                FgThread.get().getLooper());
1819
1820        getDefaultDisplayMetrics(context, mMetrics);
1821
1822        SystemConfig systemConfig = SystemConfig.getInstance();
1823        mGlobalGids = systemConfig.getGlobalGids();
1824        mSystemPermissions = systemConfig.getSystemPermissions();
1825        mAvailableFeatures = systemConfig.getAvailableFeatures();
1826
1827        synchronized (mInstallLock) {
1828        // writer
1829        synchronized (mPackages) {
1830            mHandlerThread = new ServiceThread(TAG,
1831                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1832            mHandlerThread.start();
1833            mHandler = new PackageHandler(mHandlerThread.getLooper());
1834            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1835
1836            File dataDir = Environment.getDataDirectory();
1837            mAppDataDir = new File(dataDir, "data");
1838            mAppInstallDir = new File(dataDir, "app");
1839            mAppLib32InstallDir = new File(dataDir, "app-lib");
1840            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1841            mUserAppDataDir = new File(dataDir, "user");
1842            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1843
1844            sUserManager = new UserManagerService(context, this,
1845                    mInstallLock, mPackages);
1846
1847            // Propagate permission configuration in to package manager.
1848            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1849                    = systemConfig.getPermissions();
1850            for (int i=0; i<permConfig.size(); i++) {
1851                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1852                BasePermission bp = mSettings.mPermissions.get(perm.name);
1853                if (bp == null) {
1854                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1855                    mSettings.mPermissions.put(perm.name, bp);
1856                }
1857                if (perm.gids != null) {
1858                    bp.setGids(perm.gids, perm.perUser);
1859                }
1860            }
1861
1862            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1863            for (int i=0; i<libConfig.size(); i++) {
1864                mSharedLibraries.put(libConfig.keyAt(i),
1865                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1866            }
1867
1868            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1869
1870            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1871                    mSdkVersion, mOnlyCore);
1872
1873            String customResolverActivity = Resources.getSystem().getString(
1874                    R.string.config_customResolverActivity);
1875            if (TextUtils.isEmpty(customResolverActivity)) {
1876                customResolverActivity = null;
1877            } else {
1878                mCustomResolverComponentName = ComponentName.unflattenFromString(
1879                        customResolverActivity);
1880            }
1881
1882            long startTime = SystemClock.uptimeMillis();
1883
1884            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1885                    startTime);
1886
1887            // Set flag to monitor and not change apk file paths when
1888            // scanning install directories.
1889            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1890
1891            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1892
1893            /**
1894             * Add everything in the in the boot class path to the
1895             * list of process files because dexopt will have been run
1896             * if necessary during zygote startup.
1897             */
1898            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1899            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1900
1901            if (bootClassPath != null) {
1902                String[] bootClassPathElements = splitString(bootClassPath, ':');
1903                for (String element : bootClassPathElements) {
1904                    alreadyDexOpted.add(element);
1905                }
1906            } else {
1907                Slog.w(TAG, "No BOOTCLASSPATH found!");
1908            }
1909
1910            if (systemServerClassPath != null) {
1911                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1912                for (String element : systemServerClassPathElements) {
1913                    alreadyDexOpted.add(element);
1914                }
1915            } else {
1916                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1917            }
1918
1919            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1920            final String[] dexCodeInstructionSets =
1921                    getDexCodeInstructionSets(
1922                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1923
1924            /**
1925             * Ensure all external libraries have had dexopt run on them.
1926             */
1927            if (mSharedLibraries.size() > 0) {
1928                // NOTE: For now, we're compiling these system "shared libraries"
1929                // (and framework jars) into all available architectures. It's possible
1930                // to compile them only when we come across an app that uses them (there's
1931                // already logic for that in scanPackageLI) but that adds some complexity.
1932                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1933                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1934                        final String lib = libEntry.path;
1935                        if (lib == null) {
1936                            continue;
1937                        }
1938
1939                        try {
1940                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1941                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1942                                alreadyDexOpted.add(lib);
1943                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1944                            }
1945                        } catch (FileNotFoundException e) {
1946                            Slog.w(TAG, "Library not found: " + lib);
1947                        } catch (IOException e) {
1948                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1949                                    + e.getMessage());
1950                        }
1951                    }
1952                }
1953            }
1954
1955            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1956
1957            // Gross hack for now: we know this file doesn't contain any
1958            // code, so don't dexopt it to avoid the resulting log spew.
1959            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1960
1961            // Gross hack for now: we know this file is only part of
1962            // the boot class path for art, so don't dexopt it to
1963            // avoid the resulting log spew.
1964            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1965
1966            /**
1967             * There are a number of commands implemented in Java, which
1968             * we currently need to do the dexopt on so that they can be
1969             * run from a non-root shell.
1970             */
1971            String[] frameworkFiles = frameworkDir.list();
1972            if (frameworkFiles != null) {
1973                // TODO: We could compile these only for the most preferred ABI. We should
1974                // first double check that the dex files for these commands are not referenced
1975                // by other system apps.
1976                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1977                    for (int i=0; i<frameworkFiles.length; i++) {
1978                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1979                        String path = libPath.getPath();
1980                        // Skip the file if we already did it.
1981                        if (alreadyDexOpted.contains(path)) {
1982                            continue;
1983                        }
1984                        // Skip the file if it is not a type we want to dexopt.
1985                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1986                            continue;
1987                        }
1988                        try {
1989                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1990                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1991                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1992                            }
1993                        } catch (FileNotFoundException e) {
1994                            Slog.w(TAG, "Jar not found: " + path);
1995                        } catch (IOException e) {
1996                            Slog.w(TAG, "Exception reading jar: " + path, e);
1997                        }
1998                    }
1999                }
2000            }
2001
2002            // Collect vendor overlay packages.
2003            // (Do this before scanning any apps.)
2004            // For security and version matching reason, only consider
2005            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2006            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2007            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2008                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2009
2010            // Find base frameworks (resource packages without code).
2011            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2012                    | PackageParser.PARSE_IS_SYSTEM_DIR
2013                    | PackageParser.PARSE_IS_PRIVILEGED,
2014                    scanFlags | SCAN_NO_DEX, 0);
2015
2016            // Collected privileged system packages.
2017            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2018            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2019                    | PackageParser.PARSE_IS_SYSTEM_DIR
2020                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2021
2022            // Collect ordinary system packages.
2023            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2024            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2025                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2026
2027            // Collect all vendor packages.
2028            File vendorAppDir = new File("/vendor/app");
2029            try {
2030                vendorAppDir = vendorAppDir.getCanonicalFile();
2031            } catch (IOException e) {
2032                // failed to look up canonical path, continue with original one
2033            }
2034            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2035                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2036
2037            // Collect all OEM packages.
2038            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2039            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2040                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2041
2042            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2043            mInstaller.moveFiles();
2044
2045            // Prune any system packages that no longer exist.
2046            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2047            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
2048            if (!mOnlyCore) {
2049                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2050                while (psit.hasNext()) {
2051                    PackageSetting ps = psit.next();
2052
2053                    /*
2054                     * If this is not a system app, it can't be a
2055                     * disable system app.
2056                     */
2057                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2058                        continue;
2059                    }
2060
2061                    /*
2062                     * If the package is scanned, it's not erased.
2063                     */
2064                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2065                    if (scannedPkg != null) {
2066                        /*
2067                         * If the system app is both scanned and in the
2068                         * disabled packages list, then it must have been
2069                         * added via OTA. Remove it from the currently
2070                         * scanned package so the previously user-installed
2071                         * application can be scanned.
2072                         */
2073                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2074                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2075                                    + ps.name + "; removing system app.  Last known codePath="
2076                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2077                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2078                                    + scannedPkg.mVersionCode);
2079                            removePackageLI(ps, true);
2080                            expectingBetter.put(ps.name, ps.codePath);
2081                        }
2082
2083                        continue;
2084                    }
2085
2086                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2087                        psit.remove();
2088                        logCriticalInfo(Log.WARN, "System package " + ps.name
2089                                + " no longer exists; wiping its data");
2090                        removeDataDirsLI(null, ps.name);
2091                    } else {
2092                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2093                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2094                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2095                        }
2096                    }
2097                }
2098            }
2099
2100            //look for any incomplete package installations
2101            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2102            //clean up list
2103            for(int i = 0; i < deletePkgsList.size(); i++) {
2104                //clean up here
2105                cleanupInstallFailedPackage(deletePkgsList.get(i));
2106            }
2107            //delete tmp files
2108            deleteTempPackageFiles();
2109
2110            // Remove any shared userIDs that have no associated packages
2111            mSettings.pruneSharedUsersLPw();
2112
2113            if (!mOnlyCore) {
2114                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2115                        SystemClock.uptimeMillis());
2116                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2117
2118                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2119                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2120
2121                /**
2122                 * Remove disable package settings for any updated system
2123                 * apps that were removed via an OTA. If they're not a
2124                 * previously-updated app, remove them completely.
2125                 * Otherwise, just revoke their system-level permissions.
2126                 */
2127                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2128                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2129                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2130
2131                    String msg;
2132                    if (deletedPkg == null) {
2133                        msg = "Updated system package " + deletedAppName
2134                                + " no longer exists; wiping its data";
2135                        removeDataDirsLI(null, deletedAppName);
2136                    } else {
2137                        msg = "Updated system app + " + deletedAppName
2138                                + " no longer present; removing system privileges for "
2139                                + deletedAppName;
2140
2141                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2142
2143                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2144                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2145                    }
2146                    logCriticalInfo(Log.WARN, msg);
2147                }
2148
2149                /**
2150                 * Make sure all system apps that we expected to appear on
2151                 * the userdata partition actually showed up. If they never
2152                 * appeared, crawl back and revive the system version.
2153                 */
2154                for (int i = 0; i < expectingBetter.size(); i++) {
2155                    final String packageName = expectingBetter.keyAt(i);
2156                    if (!mPackages.containsKey(packageName)) {
2157                        final File scanFile = expectingBetter.valueAt(i);
2158
2159                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2160                                + " but never showed up; reverting to system");
2161
2162                        final int reparseFlags;
2163                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2164                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2165                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2166                                    | PackageParser.PARSE_IS_PRIVILEGED;
2167                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2168                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2169                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2170                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2171                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2172                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2173                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2174                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2175                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2176                        } else {
2177                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2178                            continue;
2179                        }
2180
2181                        mSettings.enableSystemPackageLPw(packageName);
2182
2183                        try {
2184                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2185                        } catch (PackageManagerException e) {
2186                            Slog.e(TAG, "Failed to parse original system package: "
2187                                    + e.getMessage());
2188                        }
2189                    }
2190                }
2191            }
2192
2193            // Now that we know all of the shared libraries, update all clients to have
2194            // the correct library paths.
2195            updateAllSharedLibrariesLPw();
2196
2197            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2198                // NOTE: We ignore potential failures here during a system scan (like
2199                // the rest of the commands above) because there's precious little we
2200                // can do about it. A settings error is reported, though.
2201                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2202                        false /* force dexopt */, false /* defer dexopt */);
2203            }
2204
2205            // Now that we know all the packages we are keeping,
2206            // read and update their last usage times.
2207            mPackageUsage.readLP();
2208
2209            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2210                    SystemClock.uptimeMillis());
2211            Slog.i(TAG, "Time to scan packages: "
2212                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2213                    + " seconds");
2214
2215            // If the platform SDK has changed since the last time we booted,
2216            // we need to re-grant app permission to catch any new ones that
2217            // appear.  This is really a hack, and means that apps can in some
2218            // cases get permissions that the user didn't initially explicitly
2219            // allow...  it would be nice to have some better way to handle
2220            // this situation.
2221            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2222                    != mSdkVersion;
2223            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2224                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2225                    + "; regranting permissions for internal storage");
2226            mSettings.mInternalSdkPlatform = mSdkVersion;
2227
2228            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2229                    | (regrantPermissions
2230                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2231                            : 0));
2232
2233            // If this is the first boot, and it is a normal boot, then
2234            // we need to initialize the default preferred apps.
2235            if (!mRestoredSettings && !onlyCore) {
2236                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2237                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2238            }
2239
2240            // If this is first boot after an OTA, and a normal boot, then
2241            // we need to clear code cache directories.
2242            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2243            if (mIsUpgrade && !onlyCore) {
2244                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2245                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2246                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2247                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2248                }
2249                mSettings.mFingerprint = Build.FINGERPRINT;
2250            }
2251
2252            primeDomainVerificationsLPw();
2253            checkDefaultBrowser();
2254
2255            // All the changes are done during package scanning.
2256            mSettings.updateInternalDatabaseVersion();
2257
2258            // can downgrade to reader
2259            mSettings.writeLPr();
2260
2261            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2262                    SystemClock.uptimeMillis());
2263
2264            mRequiredVerifierPackage = getRequiredVerifierLPr();
2265
2266            mInstallerService = new PackageInstallerService(context, this);
2267
2268            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2269            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2270                    mIntentFilterVerifierComponent);
2271
2272        } // synchronized (mPackages)
2273        } // synchronized (mInstallLock)
2274
2275        // Now after opening every single application zip, make sure they
2276        // are all flushed.  Not really needed, but keeps things nice and
2277        // tidy.
2278        Runtime.getRuntime().gc();
2279
2280        // Expose private service for system components to use.
2281        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2282    }
2283
2284    @Override
2285    public boolean isFirstBoot() {
2286        return !mRestoredSettings;
2287    }
2288
2289    @Override
2290    public boolean isOnlyCoreApps() {
2291        return mOnlyCore;
2292    }
2293
2294    @Override
2295    public boolean isUpgrade() {
2296        return mIsUpgrade;
2297    }
2298
2299    private String getRequiredVerifierLPr() {
2300        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2301        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2302                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2303
2304        String requiredVerifier = null;
2305
2306        final int N = receivers.size();
2307        for (int i = 0; i < N; i++) {
2308            final ResolveInfo info = receivers.get(i);
2309
2310            if (info.activityInfo == null) {
2311                continue;
2312            }
2313
2314            final String packageName = info.activityInfo.packageName;
2315
2316            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2317                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2318                continue;
2319            }
2320
2321            if (requiredVerifier != null) {
2322                throw new RuntimeException("There can be only one required verifier");
2323            }
2324
2325            requiredVerifier = packageName;
2326        }
2327
2328        return requiredVerifier;
2329    }
2330
2331    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2332        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2333        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2334                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2335
2336        ComponentName verifierComponentName = null;
2337
2338        int priority = -1000;
2339        final int N = receivers.size();
2340        for (int i = 0; i < N; i++) {
2341            final ResolveInfo info = receivers.get(i);
2342
2343            if (info.activityInfo == null) {
2344                continue;
2345            }
2346
2347            final String packageName = info.activityInfo.packageName;
2348
2349            final PackageSetting ps = mSettings.mPackages.get(packageName);
2350            if (ps == null) {
2351                continue;
2352            }
2353
2354            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2355                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2356                continue;
2357            }
2358
2359            // Select the IntentFilterVerifier with the highest priority
2360            if (priority < info.priority) {
2361                priority = info.priority;
2362                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2363                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2364                        + verifierComponentName + " with priority: " + info.priority);
2365            }
2366        }
2367
2368        return verifierComponentName;
2369    }
2370
2371    private void primeDomainVerificationsLPw() {
2372        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2373        boolean updated = false;
2374        ArraySet<String> allHostsSet = new ArraySet<>();
2375        for (PackageParser.Package pkg : mPackages.values()) {
2376            final String packageName = pkg.packageName;
2377            if (!hasDomainURLs(pkg)) {
2378                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2379                            "package with no domain URLs: " + packageName);
2380                continue;
2381            }
2382            if (!pkg.isSystemApp()) {
2383                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2384                        "No priming domain verifications for a non system package : " +
2385                                packageName);
2386                continue;
2387            }
2388            for (PackageParser.Activity a : pkg.activities) {
2389                for (ActivityIntentInfo filter : a.intents) {
2390                    if (hasValidDomains(filter)) {
2391                        allHostsSet.addAll(filter.getHostsList());
2392                    }
2393                }
2394            }
2395            if (allHostsSet.size() == 0) {
2396                allHostsSet.add("*");
2397            }
2398            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2399            IntentFilterVerificationInfo ivi =
2400                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2401            if (ivi != null) {
2402                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2403                        "Priming domain verifications for package: " + packageName +
2404                        " with hosts:" + ivi.getDomainsString());
2405                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2406                updated = true;
2407            }
2408            else {
2409                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2410                        "No priming domain verifications for package: " + packageName);
2411            }
2412            allHostsSet.clear();
2413        }
2414        if (updated) {
2415            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2416                    "Will need to write primed domain verifications");
2417        }
2418        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2419    }
2420
2421    private void applyFactoryDefaultBrowserLPw(int userId) {
2422        // The default browser app's package name is stored in a string resource,
2423        // with a product-specific overlay used for vendor customization.
2424        String browserPkg = mContext.getResources().getString(
2425                com.android.internal.R.string.default_browser);
2426        if (browserPkg != null) {
2427            // non-empty string => required to be a known package
2428            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2429            if (ps == null) {
2430                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2431                browserPkg = null;
2432            } else {
2433                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2434            }
2435        }
2436
2437        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2438        // default.  If there's more than one, just leave everything alone.
2439        if (browserPkg == null) {
2440            calculateDefaultBrowserLPw(userId);
2441        }
2442    }
2443
2444    private void calculateDefaultBrowserLPw(int userId) {
2445        List<String> allBrowsers = resolveAllBrowserApps(userId);
2446        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2447        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2448    }
2449
2450    private List<String> resolveAllBrowserApps(int userId) {
2451        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2452        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2453                PackageManager.MATCH_ALL, userId);
2454
2455        final int count = list.size();
2456        List<String> result = new ArrayList<String>(count);
2457        for (int i=0; i<count; i++) {
2458            ResolveInfo info = list.get(i);
2459            if (info.activityInfo == null
2460                    || !info.handleAllWebDataURI
2461                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2462                    || result.contains(info.activityInfo.packageName)) {
2463                continue;
2464            }
2465            result.add(info.activityInfo.packageName);
2466        }
2467
2468        return result;
2469    }
2470
2471    private boolean packageIsBrowser(String packageName, int userId) {
2472        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2473                PackageManager.MATCH_ALL, userId);
2474        final int N = list.size();
2475        for (int i = 0; i < N; i++) {
2476            ResolveInfo info = list.get(i);
2477            if (packageName.equals(info.activityInfo.packageName)) {
2478                return true;
2479            }
2480        }
2481        return false;
2482    }
2483
2484    private void checkDefaultBrowser() {
2485        final int myUserId = UserHandle.myUserId();
2486        final String packageName = getDefaultBrowserPackageName(myUserId);
2487        if (packageName != null) {
2488            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2489            if (info == null) {
2490                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2491                synchronized (mPackages) {
2492                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2493                }
2494            }
2495        }
2496    }
2497
2498    @Override
2499    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2500            throws RemoteException {
2501        try {
2502            return super.onTransact(code, data, reply, flags);
2503        } catch (RuntimeException e) {
2504            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2505                Slog.wtf(TAG, "Package Manager Crash", e);
2506            }
2507            throw e;
2508        }
2509    }
2510
2511    void cleanupInstallFailedPackage(PackageSetting ps) {
2512        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2513
2514        removeDataDirsLI(ps.volumeUuid, ps.name);
2515        if (ps.codePath != null) {
2516            if (ps.codePath.isDirectory()) {
2517                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2518            } else {
2519                ps.codePath.delete();
2520            }
2521        }
2522        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2523            if (ps.resourcePath.isDirectory()) {
2524                FileUtils.deleteContents(ps.resourcePath);
2525            }
2526            ps.resourcePath.delete();
2527        }
2528        mSettings.removePackageLPw(ps.name);
2529    }
2530
2531    static int[] appendInts(int[] cur, int[] add) {
2532        if (add == null) return cur;
2533        if (cur == null) return add;
2534        final int N = add.length;
2535        for (int i=0; i<N; i++) {
2536            cur = appendInt(cur, add[i]);
2537        }
2538        return cur;
2539    }
2540
2541    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2542        if (!sUserManager.exists(userId)) return null;
2543        final PackageSetting ps = (PackageSetting) p.mExtras;
2544        if (ps == null) {
2545            return null;
2546        }
2547
2548        final PermissionsState permissionsState = ps.getPermissionsState();
2549
2550        final int[] gids = permissionsState.computeGids(userId);
2551        final Set<String> permissions = permissionsState.getPermissions(userId);
2552        final PackageUserState state = ps.readUserState(userId);
2553
2554        return PackageParser.generatePackageInfo(p, gids, flags,
2555                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2556    }
2557
2558    @Override
2559    public boolean isPackageFrozen(String packageName) {
2560        synchronized (mPackages) {
2561            final PackageSetting ps = mSettings.mPackages.get(packageName);
2562            if (ps != null) {
2563                return ps.frozen;
2564            }
2565        }
2566        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2567        return true;
2568    }
2569
2570    @Override
2571    public boolean isPackageAvailable(String packageName, int userId) {
2572        if (!sUserManager.exists(userId)) return false;
2573        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2574        synchronized (mPackages) {
2575            PackageParser.Package p = mPackages.get(packageName);
2576            if (p != null) {
2577                final PackageSetting ps = (PackageSetting) p.mExtras;
2578                if (ps != null) {
2579                    final PackageUserState state = ps.readUserState(userId);
2580                    if (state != null) {
2581                        return PackageParser.isAvailable(state);
2582                    }
2583                }
2584            }
2585        }
2586        return false;
2587    }
2588
2589    @Override
2590    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2591        if (!sUserManager.exists(userId)) return null;
2592        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2593        // reader
2594        synchronized (mPackages) {
2595            PackageParser.Package p = mPackages.get(packageName);
2596            if (DEBUG_PACKAGE_INFO)
2597                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2598            if (p != null) {
2599                return generatePackageInfo(p, flags, userId);
2600            }
2601            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2602                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2603            }
2604        }
2605        return null;
2606    }
2607
2608    @Override
2609    public String[] currentToCanonicalPackageNames(String[] names) {
2610        String[] out = new String[names.length];
2611        // reader
2612        synchronized (mPackages) {
2613            for (int i=names.length-1; i>=0; i--) {
2614                PackageSetting ps = mSettings.mPackages.get(names[i]);
2615                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2616            }
2617        }
2618        return out;
2619    }
2620
2621    @Override
2622    public String[] canonicalToCurrentPackageNames(String[] names) {
2623        String[] out = new String[names.length];
2624        // reader
2625        synchronized (mPackages) {
2626            for (int i=names.length-1; i>=0; i--) {
2627                String cur = mSettings.mRenamedPackages.get(names[i]);
2628                out[i] = cur != null ? cur : names[i];
2629            }
2630        }
2631        return out;
2632    }
2633
2634    @Override
2635    public int getPackageUid(String packageName, int userId) {
2636        if (!sUserManager.exists(userId)) return -1;
2637        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2638
2639        // reader
2640        synchronized (mPackages) {
2641            PackageParser.Package p = mPackages.get(packageName);
2642            if(p != null) {
2643                return UserHandle.getUid(userId, p.applicationInfo.uid);
2644            }
2645            PackageSetting ps = mSettings.mPackages.get(packageName);
2646            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2647                return -1;
2648            }
2649            p = ps.pkg;
2650            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2651        }
2652    }
2653
2654    @Override
2655    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2656        if (!sUserManager.exists(userId)) {
2657            return null;
2658        }
2659
2660        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2661                "getPackageGids");
2662
2663        // reader
2664        synchronized (mPackages) {
2665            PackageParser.Package p = mPackages.get(packageName);
2666            if (DEBUG_PACKAGE_INFO) {
2667                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2668            }
2669            if (p != null) {
2670                PackageSetting ps = (PackageSetting) p.mExtras;
2671                return ps.getPermissionsState().computeGids(userId);
2672            }
2673        }
2674
2675        return null;
2676    }
2677
2678    @Override
2679    public int getMountExternalMode(int uid) {
2680        if (Process.isIsolated(uid)) {
2681            return Zygote.MOUNT_EXTERNAL_NONE;
2682        } else {
2683            if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
2684                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2685            } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2686                return Zygote.MOUNT_EXTERNAL_WRITE;
2687            } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2688                return Zygote.MOUNT_EXTERNAL_READ;
2689            } else {
2690                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2691            }
2692        }
2693    }
2694
2695    static PermissionInfo generatePermissionInfo(
2696            BasePermission bp, int flags) {
2697        if (bp.perm != null) {
2698            return PackageParser.generatePermissionInfo(bp.perm, flags);
2699        }
2700        PermissionInfo pi = new PermissionInfo();
2701        pi.name = bp.name;
2702        pi.packageName = bp.sourcePackage;
2703        pi.nonLocalizedLabel = bp.name;
2704        pi.protectionLevel = bp.protectionLevel;
2705        return pi;
2706    }
2707
2708    @Override
2709    public PermissionInfo getPermissionInfo(String name, int flags) {
2710        // reader
2711        synchronized (mPackages) {
2712            final BasePermission p = mSettings.mPermissions.get(name);
2713            if (p != null) {
2714                return generatePermissionInfo(p, flags);
2715            }
2716            return null;
2717        }
2718    }
2719
2720    @Override
2721    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2722        // reader
2723        synchronized (mPackages) {
2724            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2725            for (BasePermission p : mSettings.mPermissions.values()) {
2726                if (group == null) {
2727                    if (p.perm == null || p.perm.info.group == null) {
2728                        out.add(generatePermissionInfo(p, flags));
2729                    }
2730                } else {
2731                    if (p.perm != null && group.equals(p.perm.info.group)) {
2732                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2733                    }
2734                }
2735            }
2736
2737            if (out.size() > 0) {
2738                return out;
2739            }
2740            return mPermissionGroups.containsKey(group) ? out : null;
2741        }
2742    }
2743
2744    @Override
2745    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2746        // reader
2747        synchronized (mPackages) {
2748            return PackageParser.generatePermissionGroupInfo(
2749                    mPermissionGroups.get(name), flags);
2750        }
2751    }
2752
2753    @Override
2754    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2755        // reader
2756        synchronized (mPackages) {
2757            final int N = mPermissionGroups.size();
2758            ArrayList<PermissionGroupInfo> out
2759                    = new ArrayList<PermissionGroupInfo>(N);
2760            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2761                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2762            }
2763            return out;
2764        }
2765    }
2766
2767    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2768            int userId) {
2769        if (!sUserManager.exists(userId)) return null;
2770        PackageSetting ps = mSettings.mPackages.get(packageName);
2771        if (ps != null) {
2772            if (ps.pkg == null) {
2773                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2774                        flags, userId);
2775                if (pInfo != null) {
2776                    return pInfo.applicationInfo;
2777                }
2778                return null;
2779            }
2780            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2781                    ps.readUserState(userId), userId);
2782        }
2783        return null;
2784    }
2785
2786    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2787            int userId) {
2788        if (!sUserManager.exists(userId)) return null;
2789        PackageSetting ps = mSettings.mPackages.get(packageName);
2790        if (ps != null) {
2791            PackageParser.Package pkg = ps.pkg;
2792            if (pkg == null) {
2793                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2794                    return null;
2795                }
2796                // Only data remains, so we aren't worried about code paths
2797                pkg = new PackageParser.Package(packageName);
2798                pkg.applicationInfo.packageName = packageName;
2799                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2800                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2801                pkg.applicationInfo.dataDir = Environment
2802                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2803                        .getAbsolutePath();
2804                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2805                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2806            }
2807            return generatePackageInfo(pkg, flags, userId);
2808        }
2809        return null;
2810    }
2811
2812    @Override
2813    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2814        if (!sUserManager.exists(userId)) return null;
2815        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2816        // writer
2817        synchronized (mPackages) {
2818            PackageParser.Package p = mPackages.get(packageName);
2819            if (DEBUG_PACKAGE_INFO) Log.v(
2820                    TAG, "getApplicationInfo " + packageName
2821                    + ": " + p);
2822            if (p != null) {
2823                PackageSetting ps = mSettings.mPackages.get(packageName);
2824                if (ps == null) return null;
2825                // Note: isEnabledLP() does not apply here - always return info
2826                return PackageParser.generateApplicationInfo(
2827                        p, flags, ps.readUserState(userId), userId);
2828            }
2829            if ("android".equals(packageName)||"system".equals(packageName)) {
2830                return mAndroidApplication;
2831            }
2832            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2833                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2834            }
2835        }
2836        return null;
2837    }
2838
2839    @Override
2840    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2841            final IPackageDataObserver observer) {
2842        mContext.enforceCallingOrSelfPermission(
2843                android.Manifest.permission.CLEAR_APP_CACHE, null);
2844        // Queue up an async operation since clearing cache may take a little while.
2845        mHandler.post(new Runnable() {
2846            public void run() {
2847                mHandler.removeCallbacks(this);
2848                int retCode = -1;
2849                synchronized (mInstallLock) {
2850                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2851                    if (retCode < 0) {
2852                        Slog.w(TAG, "Couldn't clear application caches");
2853                    }
2854                }
2855                if (observer != null) {
2856                    try {
2857                        observer.onRemoveCompleted(null, (retCode >= 0));
2858                    } catch (RemoteException e) {
2859                        Slog.w(TAG, "RemoveException when invoking call back");
2860                    }
2861                }
2862            }
2863        });
2864    }
2865
2866    @Override
2867    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2868            final IntentSender pi) {
2869        mContext.enforceCallingOrSelfPermission(
2870                android.Manifest.permission.CLEAR_APP_CACHE, null);
2871        // Queue up an async operation since clearing cache may take a little while.
2872        mHandler.post(new Runnable() {
2873            public void run() {
2874                mHandler.removeCallbacks(this);
2875                int retCode = -1;
2876                synchronized (mInstallLock) {
2877                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2878                    if (retCode < 0) {
2879                        Slog.w(TAG, "Couldn't clear application caches");
2880                    }
2881                }
2882                if(pi != null) {
2883                    try {
2884                        // Callback via pending intent
2885                        int code = (retCode >= 0) ? 1 : 0;
2886                        pi.sendIntent(null, code, null,
2887                                null, null);
2888                    } catch (SendIntentException e1) {
2889                        Slog.i(TAG, "Failed to send pending intent");
2890                    }
2891                }
2892            }
2893        });
2894    }
2895
2896    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2897        synchronized (mInstallLock) {
2898            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2899                throw new IOException("Failed to free enough space");
2900            }
2901        }
2902    }
2903
2904    @Override
2905    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2906        if (!sUserManager.exists(userId)) return null;
2907        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2908        synchronized (mPackages) {
2909            PackageParser.Activity a = mActivities.mActivities.get(component);
2910
2911            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2912            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2913                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2914                if (ps == null) return null;
2915                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2916                        userId);
2917            }
2918            if (mResolveComponentName.equals(component)) {
2919                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2920                        new PackageUserState(), userId);
2921            }
2922        }
2923        return null;
2924    }
2925
2926    @Override
2927    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2928            String resolvedType) {
2929        synchronized (mPackages) {
2930            PackageParser.Activity a = mActivities.mActivities.get(component);
2931            if (a == null) {
2932                return false;
2933            }
2934            for (int i=0; i<a.intents.size(); i++) {
2935                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2936                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2937                    return true;
2938                }
2939            }
2940            return false;
2941        }
2942    }
2943
2944    @Override
2945    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2946        if (!sUserManager.exists(userId)) return null;
2947        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2948        synchronized (mPackages) {
2949            PackageParser.Activity a = mReceivers.mActivities.get(component);
2950            if (DEBUG_PACKAGE_INFO) Log.v(
2951                TAG, "getReceiverInfo " + component + ": " + a);
2952            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2953                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2954                if (ps == null) return null;
2955                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2956                        userId);
2957            }
2958        }
2959        return null;
2960    }
2961
2962    @Override
2963    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2964        if (!sUserManager.exists(userId)) return null;
2965        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2966        synchronized (mPackages) {
2967            PackageParser.Service s = mServices.mServices.get(component);
2968            if (DEBUG_PACKAGE_INFO) Log.v(
2969                TAG, "getServiceInfo " + component + ": " + s);
2970            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2971                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2972                if (ps == null) return null;
2973                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2974                        userId);
2975            }
2976        }
2977        return null;
2978    }
2979
2980    @Override
2981    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2982        if (!sUserManager.exists(userId)) return null;
2983        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2984        synchronized (mPackages) {
2985            PackageParser.Provider p = mProviders.mProviders.get(component);
2986            if (DEBUG_PACKAGE_INFO) Log.v(
2987                TAG, "getProviderInfo " + component + ": " + p);
2988            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2989                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2990                if (ps == null) return null;
2991                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2992                        userId);
2993            }
2994        }
2995        return null;
2996    }
2997
2998    @Override
2999    public String[] getSystemSharedLibraryNames() {
3000        Set<String> libSet;
3001        synchronized (mPackages) {
3002            libSet = mSharedLibraries.keySet();
3003            int size = libSet.size();
3004            if (size > 0) {
3005                String[] libs = new String[size];
3006                libSet.toArray(libs);
3007                return libs;
3008            }
3009        }
3010        return null;
3011    }
3012
3013    /**
3014     * @hide
3015     */
3016    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3017        synchronized (mPackages) {
3018            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3019            if (lib != null && lib.apk != null) {
3020                return mPackages.get(lib.apk);
3021            }
3022        }
3023        return null;
3024    }
3025
3026    @Override
3027    public FeatureInfo[] getSystemAvailableFeatures() {
3028        Collection<FeatureInfo> featSet;
3029        synchronized (mPackages) {
3030            featSet = mAvailableFeatures.values();
3031            int size = featSet.size();
3032            if (size > 0) {
3033                FeatureInfo[] features = new FeatureInfo[size+1];
3034                featSet.toArray(features);
3035                FeatureInfo fi = new FeatureInfo();
3036                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3037                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3038                features[size] = fi;
3039                return features;
3040            }
3041        }
3042        return null;
3043    }
3044
3045    @Override
3046    public boolean hasSystemFeature(String name) {
3047        synchronized (mPackages) {
3048            return mAvailableFeatures.containsKey(name);
3049        }
3050    }
3051
3052    private void checkValidCaller(int uid, int userId) {
3053        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3054            return;
3055
3056        throw new SecurityException("Caller uid=" + uid
3057                + " is not privileged to communicate with user=" + userId);
3058    }
3059
3060    @Override
3061    public int checkPermission(String permName, String pkgName, int userId) {
3062        if (!sUserManager.exists(userId)) {
3063            return PackageManager.PERMISSION_DENIED;
3064        }
3065
3066        synchronized (mPackages) {
3067            final PackageParser.Package p = mPackages.get(pkgName);
3068            if (p != null && p.mExtras != null) {
3069                final PackageSetting ps = (PackageSetting) p.mExtras;
3070                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3071                    return PackageManager.PERMISSION_GRANTED;
3072                }
3073            }
3074        }
3075
3076        return PackageManager.PERMISSION_DENIED;
3077    }
3078
3079    @Override
3080    public int checkUidPermission(String permName, int uid) {
3081        final int userId = UserHandle.getUserId(uid);
3082
3083        if (!sUserManager.exists(userId)) {
3084            return PackageManager.PERMISSION_DENIED;
3085        }
3086
3087        synchronized (mPackages) {
3088            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3089            if (obj != null) {
3090                final SettingBase ps = (SettingBase) obj;
3091                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3092                    return PackageManager.PERMISSION_GRANTED;
3093                }
3094            } else {
3095                ArraySet<String> perms = mSystemPermissions.get(uid);
3096                if (perms != null && perms.contains(permName)) {
3097                    return PackageManager.PERMISSION_GRANTED;
3098                }
3099            }
3100        }
3101
3102        return PackageManager.PERMISSION_DENIED;
3103    }
3104
3105    /**
3106     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3107     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3108     * @param checkShell TODO(yamasani):
3109     * @param message the message to log on security exception
3110     */
3111    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3112            boolean checkShell, String message) {
3113        if (userId < 0) {
3114            throw new IllegalArgumentException("Invalid userId " + userId);
3115        }
3116        if (checkShell) {
3117            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3118        }
3119        if (userId == UserHandle.getUserId(callingUid)) return;
3120        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3121            if (requireFullPermission) {
3122                mContext.enforceCallingOrSelfPermission(
3123                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3124            } else {
3125                try {
3126                    mContext.enforceCallingOrSelfPermission(
3127                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3128                } catch (SecurityException se) {
3129                    mContext.enforceCallingOrSelfPermission(
3130                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3131                }
3132            }
3133        }
3134    }
3135
3136    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3137        if (callingUid == Process.SHELL_UID) {
3138            if (userHandle >= 0
3139                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3140                throw new SecurityException("Shell does not have permission to access user "
3141                        + userHandle);
3142            } else if (userHandle < 0) {
3143                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3144                        + Debug.getCallers(3));
3145            }
3146        }
3147    }
3148
3149    private BasePermission findPermissionTreeLP(String permName) {
3150        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3151            if (permName.startsWith(bp.name) &&
3152                    permName.length() > bp.name.length() &&
3153                    permName.charAt(bp.name.length()) == '.') {
3154                return bp;
3155            }
3156        }
3157        return null;
3158    }
3159
3160    private BasePermission checkPermissionTreeLP(String permName) {
3161        if (permName != null) {
3162            BasePermission bp = findPermissionTreeLP(permName);
3163            if (bp != null) {
3164                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3165                    return bp;
3166                }
3167                throw new SecurityException("Calling uid "
3168                        + Binder.getCallingUid()
3169                        + " is not allowed to add to permission tree "
3170                        + bp.name + " owned by uid " + bp.uid);
3171            }
3172        }
3173        throw new SecurityException("No permission tree found for " + permName);
3174    }
3175
3176    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3177        if (s1 == null) {
3178            return s2 == null;
3179        }
3180        if (s2 == null) {
3181            return false;
3182        }
3183        if (s1.getClass() != s2.getClass()) {
3184            return false;
3185        }
3186        return s1.equals(s2);
3187    }
3188
3189    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3190        if (pi1.icon != pi2.icon) return false;
3191        if (pi1.logo != pi2.logo) return false;
3192        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3193        if (!compareStrings(pi1.name, pi2.name)) return false;
3194        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3195        // We'll take care of setting this one.
3196        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3197        // These are not currently stored in settings.
3198        //if (!compareStrings(pi1.group, pi2.group)) return false;
3199        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3200        //if (pi1.labelRes != pi2.labelRes) return false;
3201        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3202        return true;
3203    }
3204
3205    int permissionInfoFootprint(PermissionInfo info) {
3206        int size = info.name.length();
3207        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3208        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3209        return size;
3210    }
3211
3212    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3213        int size = 0;
3214        for (BasePermission perm : mSettings.mPermissions.values()) {
3215            if (perm.uid == tree.uid) {
3216                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3217            }
3218        }
3219        return size;
3220    }
3221
3222    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3223        // We calculate the max size of permissions defined by this uid and throw
3224        // if that plus the size of 'info' would exceed our stated maximum.
3225        if (tree.uid != Process.SYSTEM_UID) {
3226            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3227            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3228                throw new SecurityException("Permission tree size cap exceeded");
3229            }
3230        }
3231    }
3232
3233    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3234        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3235            throw new SecurityException("Label must be specified in permission");
3236        }
3237        BasePermission tree = checkPermissionTreeLP(info.name);
3238        BasePermission bp = mSettings.mPermissions.get(info.name);
3239        boolean added = bp == null;
3240        boolean changed = true;
3241        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3242        if (added) {
3243            enforcePermissionCapLocked(info, tree);
3244            bp = new BasePermission(info.name, tree.sourcePackage,
3245                    BasePermission.TYPE_DYNAMIC);
3246        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3247            throw new SecurityException(
3248                    "Not allowed to modify non-dynamic permission "
3249                    + info.name);
3250        } else {
3251            if (bp.protectionLevel == fixedLevel
3252                    && bp.perm.owner.equals(tree.perm.owner)
3253                    && bp.uid == tree.uid
3254                    && comparePermissionInfos(bp.perm.info, info)) {
3255                changed = false;
3256            }
3257        }
3258        bp.protectionLevel = fixedLevel;
3259        info = new PermissionInfo(info);
3260        info.protectionLevel = fixedLevel;
3261        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3262        bp.perm.info.packageName = tree.perm.info.packageName;
3263        bp.uid = tree.uid;
3264        if (added) {
3265            mSettings.mPermissions.put(info.name, bp);
3266        }
3267        if (changed) {
3268            if (!async) {
3269                mSettings.writeLPr();
3270            } else {
3271                scheduleWriteSettingsLocked();
3272            }
3273        }
3274        return added;
3275    }
3276
3277    @Override
3278    public boolean addPermission(PermissionInfo info) {
3279        synchronized (mPackages) {
3280            return addPermissionLocked(info, false);
3281        }
3282    }
3283
3284    @Override
3285    public boolean addPermissionAsync(PermissionInfo info) {
3286        synchronized (mPackages) {
3287            return addPermissionLocked(info, true);
3288        }
3289    }
3290
3291    @Override
3292    public void removePermission(String name) {
3293        synchronized (mPackages) {
3294            checkPermissionTreeLP(name);
3295            BasePermission bp = mSettings.mPermissions.get(name);
3296            if (bp != null) {
3297                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3298                    throw new SecurityException(
3299                            "Not allowed to modify non-dynamic permission "
3300                            + name);
3301                }
3302                mSettings.mPermissions.remove(name);
3303                mSettings.writeLPr();
3304            }
3305        }
3306    }
3307
3308    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3309            BasePermission bp) {
3310        int index = pkg.requestedPermissions.indexOf(bp.name);
3311        if (index == -1) {
3312            throw new SecurityException("Package " + pkg.packageName
3313                    + " has not requested permission " + bp.name);
3314        }
3315        if (!bp.isRuntime()) {
3316            throw new SecurityException("Permission " + bp.name
3317                    + " is not a changeable permission type");
3318        }
3319    }
3320
3321    @Override
3322    public void grantRuntimePermission(String packageName, String name, final int userId) {
3323        if (!sUserManager.exists(userId)) {
3324            Log.e(TAG, "No such user:" + userId);
3325            return;
3326        }
3327
3328        mContext.enforceCallingOrSelfPermission(
3329                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3330                "grantRuntimePermission");
3331
3332        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3333                "grantRuntimePermission");
3334
3335        final int uid;
3336        final SettingBase sb;
3337
3338        synchronized (mPackages) {
3339            final PackageParser.Package pkg = mPackages.get(packageName);
3340            if (pkg == null) {
3341                throw new IllegalArgumentException("Unknown package: " + packageName);
3342            }
3343
3344            final BasePermission bp = mSettings.mPermissions.get(name);
3345            if (bp == null) {
3346                throw new IllegalArgumentException("Unknown permission: " + name);
3347            }
3348
3349            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3350
3351            uid = pkg.applicationInfo.uid;
3352            sb = (SettingBase) pkg.mExtras;
3353            if (sb == null) {
3354                throw new IllegalArgumentException("Unknown package: " + packageName);
3355            }
3356
3357            final PermissionsState permissionsState = sb.getPermissionsState();
3358
3359            final int flags = permissionsState.getPermissionFlags(name, userId);
3360            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3361                throw new SecurityException("Cannot grant system fixed permission: "
3362                        + name + " for package: " + packageName);
3363            }
3364
3365            final int result = permissionsState.grantRuntimePermission(bp, userId);
3366            switch (result) {
3367                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3368                    return;
3369                }
3370
3371                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3372                    mHandler.post(new Runnable() {
3373                        @Override
3374                        public void run() {
3375                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3376                        }
3377                    });
3378                } break;
3379            }
3380
3381            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3382
3383            // Not critical if that is lost - app has to request again.
3384            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3385        }
3386
3387        if (READ_EXTERNAL_STORAGE.equals(name)
3388                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3389            final long token = Binder.clearCallingIdentity();
3390            try {
3391                final StorageManager storage = mContext.getSystemService(StorageManager.class);
3392                storage.remountUid(uid);
3393            } finally {
3394                Binder.restoreCallingIdentity(token);
3395            }
3396        }
3397    }
3398
3399    @Override
3400    public void revokeRuntimePermission(String packageName, String name, int userId) {
3401        if (!sUserManager.exists(userId)) {
3402            Log.e(TAG, "No such user:" + userId);
3403            return;
3404        }
3405
3406        mContext.enforceCallingOrSelfPermission(
3407                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3408                "revokeRuntimePermission");
3409
3410        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3411                "revokeRuntimePermission");
3412
3413        final SettingBase sb;
3414
3415        synchronized (mPackages) {
3416            final PackageParser.Package pkg = mPackages.get(packageName);
3417            if (pkg == null) {
3418                throw new IllegalArgumentException("Unknown package: " + packageName);
3419            }
3420
3421            final BasePermission bp = mSettings.mPermissions.get(name);
3422            if (bp == null) {
3423                throw new IllegalArgumentException("Unknown permission: " + name);
3424            }
3425
3426            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3427
3428            sb = (SettingBase) pkg.mExtras;
3429            if (sb == null) {
3430                throw new IllegalArgumentException("Unknown package: " + packageName);
3431            }
3432
3433            final PermissionsState permissionsState = sb.getPermissionsState();
3434
3435            final int flags = permissionsState.getPermissionFlags(name, userId);
3436            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3437                throw new SecurityException("Cannot revoke system fixed permission: "
3438                        + name + " for package: " + packageName);
3439            }
3440
3441            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3442                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3443                return;
3444            }
3445
3446            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3447
3448            // Critical, after this call app should never have the permission.
3449            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3450        }
3451
3452        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3453    }
3454
3455    @Override
3456    public void resetRuntimePermissions() {
3457        mContext.enforceCallingOrSelfPermission(
3458                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3459                "revokeRuntimePermission");
3460
3461        int callingUid = Binder.getCallingUid();
3462        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3463            mContext.enforceCallingOrSelfPermission(
3464                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3465                    "resetRuntimePermissions");
3466        }
3467
3468        final int[] userIds;
3469
3470        synchronized (mPackages) {
3471            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3472            final int userCount = UserManagerService.getInstance().getUserIds().length;
3473            userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount);
3474        }
3475
3476        for (int userId : userIds) {
3477            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
3478        }
3479    }
3480
3481    @Override
3482    public int getPermissionFlags(String name, String packageName, int userId) {
3483        if (!sUserManager.exists(userId)) {
3484            return 0;
3485        }
3486
3487        mContext.enforceCallingOrSelfPermission(
3488                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3489                "getPermissionFlags");
3490
3491        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3492                "getPermissionFlags");
3493
3494        synchronized (mPackages) {
3495            final PackageParser.Package pkg = mPackages.get(packageName);
3496            if (pkg == null) {
3497                throw new IllegalArgumentException("Unknown package: " + packageName);
3498            }
3499
3500            final BasePermission bp = mSettings.mPermissions.get(name);
3501            if (bp == null) {
3502                throw new IllegalArgumentException("Unknown permission: " + name);
3503            }
3504
3505            SettingBase sb = (SettingBase) pkg.mExtras;
3506            if (sb == null) {
3507                throw new IllegalArgumentException("Unknown package: " + packageName);
3508            }
3509
3510            PermissionsState permissionsState = sb.getPermissionsState();
3511            return permissionsState.getPermissionFlags(name, userId);
3512        }
3513    }
3514
3515    @Override
3516    public void updatePermissionFlags(String name, String packageName, int flagMask,
3517            int flagValues, int userId) {
3518        if (!sUserManager.exists(userId)) {
3519            return;
3520        }
3521
3522        mContext.enforceCallingOrSelfPermission(
3523                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3524                "updatePermissionFlags");
3525
3526        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3527                "updatePermissionFlags");
3528
3529        // Only the system can change system fixed flags.
3530        if (getCallingUid() != Process.SYSTEM_UID) {
3531            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3532            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3533        }
3534
3535        synchronized (mPackages) {
3536            final PackageParser.Package pkg = mPackages.get(packageName);
3537            if (pkg == null) {
3538                throw new IllegalArgumentException("Unknown package: " + packageName);
3539            }
3540
3541            final BasePermission bp = mSettings.mPermissions.get(name);
3542            if (bp == null) {
3543                throw new IllegalArgumentException("Unknown permission: " + name);
3544            }
3545
3546            SettingBase sb = (SettingBase) pkg.mExtras;
3547            if (sb == null) {
3548                throw new IllegalArgumentException("Unknown package: " + packageName);
3549            }
3550
3551            PermissionsState permissionsState = sb.getPermissionsState();
3552
3553            // Only the package manager can change flags for system component permissions.
3554            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3555            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3556                return;
3557            }
3558
3559            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3560
3561            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3562                // Install and runtime permissions are stored in different places,
3563                // so figure out what permission changed and persist the change.
3564                if (permissionsState.getInstallPermissionState(name) != null) {
3565                    scheduleWriteSettingsLocked();
3566                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3567                        || hadState) {
3568                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3569                }
3570            }
3571        }
3572    }
3573
3574    /**
3575     * Update the permission flags for all packages and runtime permissions of a user in order
3576     * to allow device or profile owner to remove POLICY_FIXED.
3577     */
3578    @Override
3579    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3580        if (!sUserManager.exists(userId)) {
3581            return;
3582        }
3583
3584        mContext.enforceCallingOrSelfPermission(
3585                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3586                "updatePermissionFlagsForAllApps");
3587
3588        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3589                "updatePermissionFlagsForAllApps");
3590
3591        // Only the system can change system fixed flags.
3592        if (getCallingUid() != Process.SYSTEM_UID) {
3593            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3594            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3595        }
3596
3597        synchronized (mPackages) {
3598            boolean changed = false;
3599            final int packageCount = mPackages.size();
3600            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3601                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3602                SettingBase sb = (SettingBase) pkg.mExtras;
3603                if (sb == null) {
3604                    continue;
3605                }
3606                PermissionsState permissionsState = sb.getPermissionsState();
3607                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3608                        userId, flagMask, flagValues);
3609            }
3610            if (changed) {
3611                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3612            }
3613        }
3614    }
3615
3616    @Override
3617    public boolean shouldShowRequestPermissionRationale(String permissionName,
3618            String packageName, int userId) {
3619        if (UserHandle.getCallingUserId() != userId) {
3620            mContext.enforceCallingPermission(
3621                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3622                    "canShowRequestPermissionRationale for user " + userId);
3623        }
3624
3625        final int uid = getPackageUid(packageName, userId);
3626        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3627            return false;
3628        }
3629
3630        if (checkPermission(permissionName, packageName, userId)
3631                == PackageManager.PERMISSION_GRANTED) {
3632            return false;
3633        }
3634
3635        final int flags;
3636
3637        final long identity = Binder.clearCallingIdentity();
3638        try {
3639            flags = getPermissionFlags(permissionName,
3640                    packageName, userId);
3641        } finally {
3642            Binder.restoreCallingIdentity(identity);
3643        }
3644
3645        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3646                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3647                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3648
3649        if ((flags & fixedFlags) != 0) {
3650            return false;
3651        }
3652
3653        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3654    }
3655
3656    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3657        BasePermission bp = mSettings.mPermissions.get(permission);
3658        if (bp == null) {
3659            throw new SecurityException("Missing " + permission + " permission");
3660        }
3661
3662        SettingBase sb = (SettingBase) pkg.mExtras;
3663        PermissionsState permissionsState = sb.getPermissionsState();
3664
3665        if (permissionsState.grantInstallPermission(bp) !=
3666                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3667            scheduleWriteSettingsLocked();
3668        }
3669    }
3670
3671    @Override
3672    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3673        mContext.enforceCallingOrSelfPermission(
3674                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3675                "addOnPermissionsChangeListener");
3676
3677        synchronized (mPackages) {
3678            mOnPermissionChangeListeners.addListenerLocked(listener);
3679        }
3680    }
3681
3682    @Override
3683    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3684        synchronized (mPackages) {
3685            mOnPermissionChangeListeners.removeListenerLocked(listener);
3686        }
3687    }
3688
3689    @Override
3690    public boolean isProtectedBroadcast(String actionName) {
3691        synchronized (mPackages) {
3692            return mProtectedBroadcasts.contains(actionName);
3693        }
3694    }
3695
3696    @Override
3697    public int checkSignatures(String pkg1, String pkg2) {
3698        synchronized (mPackages) {
3699            final PackageParser.Package p1 = mPackages.get(pkg1);
3700            final PackageParser.Package p2 = mPackages.get(pkg2);
3701            if (p1 == null || p1.mExtras == null
3702                    || p2 == null || p2.mExtras == null) {
3703                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3704            }
3705            return compareSignatures(p1.mSignatures, p2.mSignatures);
3706        }
3707    }
3708
3709    @Override
3710    public int checkUidSignatures(int uid1, int uid2) {
3711        // Map to base uids.
3712        uid1 = UserHandle.getAppId(uid1);
3713        uid2 = UserHandle.getAppId(uid2);
3714        // reader
3715        synchronized (mPackages) {
3716            Signature[] s1;
3717            Signature[] s2;
3718            Object obj = mSettings.getUserIdLPr(uid1);
3719            if (obj != null) {
3720                if (obj instanceof SharedUserSetting) {
3721                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3722                } else if (obj instanceof PackageSetting) {
3723                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3724                } else {
3725                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3726                }
3727            } else {
3728                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3729            }
3730            obj = mSettings.getUserIdLPr(uid2);
3731            if (obj != null) {
3732                if (obj instanceof SharedUserSetting) {
3733                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3734                } else if (obj instanceof PackageSetting) {
3735                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3736                } else {
3737                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3738                }
3739            } else {
3740                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3741            }
3742            return compareSignatures(s1, s2);
3743        }
3744    }
3745
3746    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3747        final long identity = Binder.clearCallingIdentity();
3748        try {
3749            if (sb instanceof SharedUserSetting) {
3750                SharedUserSetting sus = (SharedUserSetting) sb;
3751                final int packageCount = sus.packages.size();
3752                for (int i = 0; i < packageCount; i++) {
3753                    PackageSetting susPs = sus.packages.valueAt(i);
3754                    if (userId == UserHandle.USER_ALL) {
3755                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3756                    } else {
3757                        final int uid = UserHandle.getUid(userId, susPs.appId);
3758                        killUid(uid, reason);
3759                    }
3760                }
3761            } else if (sb instanceof PackageSetting) {
3762                PackageSetting ps = (PackageSetting) sb;
3763                if (userId == UserHandle.USER_ALL) {
3764                    killApplication(ps.pkg.packageName, ps.appId, reason);
3765                } else {
3766                    final int uid = UserHandle.getUid(userId, ps.appId);
3767                    killUid(uid, reason);
3768                }
3769            }
3770        } finally {
3771            Binder.restoreCallingIdentity(identity);
3772        }
3773    }
3774
3775    private static void killUid(int uid, String reason) {
3776        IActivityManager am = ActivityManagerNative.getDefault();
3777        if (am != null) {
3778            try {
3779                am.killUid(uid, reason);
3780            } catch (RemoteException e) {
3781                /* ignore - same process */
3782            }
3783        }
3784    }
3785
3786    /**
3787     * Compares two sets of signatures. Returns:
3788     * <br />
3789     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3790     * <br />
3791     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3792     * <br />
3793     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3794     * <br />
3795     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3796     * <br />
3797     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3798     */
3799    static int compareSignatures(Signature[] s1, Signature[] s2) {
3800        if (s1 == null) {
3801            return s2 == null
3802                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3803                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3804        }
3805
3806        if (s2 == null) {
3807            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3808        }
3809
3810        if (s1.length != s2.length) {
3811            return PackageManager.SIGNATURE_NO_MATCH;
3812        }
3813
3814        // Since both signature sets are of size 1, we can compare without HashSets.
3815        if (s1.length == 1) {
3816            return s1[0].equals(s2[0]) ?
3817                    PackageManager.SIGNATURE_MATCH :
3818                    PackageManager.SIGNATURE_NO_MATCH;
3819        }
3820
3821        ArraySet<Signature> set1 = new ArraySet<Signature>();
3822        for (Signature sig : s1) {
3823            set1.add(sig);
3824        }
3825        ArraySet<Signature> set2 = new ArraySet<Signature>();
3826        for (Signature sig : s2) {
3827            set2.add(sig);
3828        }
3829        // Make sure s2 contains all signatures in s1.
3830        if (set1.equals(set2)) {
3831            return PackageManager.SIGNATURE_MATCH;
3832        }
3833        return PackageManager.SIGNATURE_NO_MATCH;
3834    }
3835
3836    /**
3837     * If the database version for this type of package (internal storage or
3838     * external storage) is less than the version where package signatures
3839     * were updated, return true.
3840     */
3841    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3842        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3843                DatabaseVersion.SIGNATURE_END_ENTITY))
3844                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3845                        DatabaseVersion.SIGNATURE_END_ENTITY));
3846    }
3847
3848    /**
3849     * Used for backward compatibility to make sure any packages with
3850     * certificate chains get upgraded to the new style. {@code existingSigs}
3851     * will be in the old format (since they were stored on disk from before the
3852     * system upgrade) and {@code scannedSigs} will be in the newer format.
3853     */
3854    private int compareSignaturesCompat(PackageSignatures existingSigs,
3855            PackageParser.Package scannedPkg) {
3856        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3857            return PackageManager.SIGNATURE_NO_MATCH;
3858        }
3859
3860        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3861        for (Signature sig : existingSigs.mSignatures) {
3862            existingSet.add(sig);
3863        }
3864        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3865        for (Signature sig : scannedPkg.mSignatures) {
3866            try {
3867                Signature[] chainSignatures = sig.getChainSignatures();
3868                for (Signature chainSig : chainSignatures) {
3869                    scannedCompatSet.add(chainSig);
3870                }
3871            } catch (CertificateEncodingException e) {
3872                scannedCompatSet.add(sig);
3873            }
3874        }
3875        /*
3876         * Make sure the expanded scanned set contains all signatures in the
3877         * existing one.
3878         */
3879        if (scannedCompatSet.equals(existingSet)) {
3880            // Migrate the old signatures to the new scheme.
3881            existingSigs.assignSignatures(scannedPkg.mSignatures);
3882            // The new KeySets will be re-added later in the scanning process.
3883            synchronized (mPackages) {
3884                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3885            }
3886            return PackageManager.SIGNATURE_MATCH;
3887        }
3888        return PackageManager.SIGNATURE_NO_MATCH;
3889    }
3890
3891    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3892        if (isExternal(scannedPkg)) {
3893            return mSettings.isExternalDatabaseVersionOlderThan(
3894                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3895        } else {
3896            return mSettings.isInternalDatabaseVersionOlderThan(
3897                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3898        }
3899    }
3900
3901    private int compareSignaturesRecover(PackageSignatures existingSigs,
3902            PackageParser.Package scannedPkg) {
3903        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3904            return PackageManager.SIGNATURE_NO_MATCH;
3905        }
3906
3907        String msg = null;
3908        try {
3909            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3910                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3911                        + scannedPkg.packageName);
3912                return PackageManager.SIGNATURE_MATCH;
3913            }
3914        } catch (CertificateException e) {
3915            msg = e.getMessage();
3916        }
3917
3918        logCriticalInfo(Log.INFO,
3919                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3920        return PackageManager.SIGNATURE_NO_MATCH;
3921    }
3922
3923    @Override
3924    public String[] getPackagesForUid(int uid) {
3925        uid = UserHandle.getAppId(uid);
3926        // reader
3927        synchronized (mPackages) {
3928            Object obj = mSettings.getUserIdLPr(uid);
3929            if (obj instanceof SharedUserSetting) {
3930                final SharedUserSetting sus = (SharedUserSetting) obj;
3931                final int N = sus.packages.size();
3932                final String[] res = new String[N];
3933                final Iterator<PackageSetting> it = sus.packages.iterator();
3934                int i = 0;
3935                while (it.hasNext()) {
3936                    res[i++] = it.next().name;
3937                }
3938                return res;
3939            } else if (obj instanceof PackageSetting) {
3940                final PackageSetting ps = (PackageSetting) obj;
3941                return new String[] { ps.name };
3942            }
3943        }
3944        return null;
3945    }
3946
3947    @Override
3948    public String getNameForUid(int uid) {
3949        // reader
3950        synchronized (mPackages) {
3951            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3952            if (obj instanceof SharedUserSetting) {
3953                final SharedUserSetting sus = (SharedUserSetting) obj;
3954                return sus.name + ":" + sus.userId;
3955            } else if (obj instanceof PackageSetting) {
3956                final PackageSetting ps = (PackageSetting) obj;
3957                return ps.name;
3958            }
3959        }
3960        return null;
3961    }
3962
3963    @Override
3964    public int getUidForSharedUser(String sharedUserName) {
3965        if(sharedUserName == null) {
3966            return -1;
3967        }
3968        // reader
3969        synchronized (mPackages) {
3970            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3971            if (suid == null) {
3972                return -1;
3973            }
3974            return suid.userId;
3975        }
3976    }
3977
3978    @Override
3979    public int getFlagsForUid(int uid) {
3980        synchronized (mPackages) {
3981            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3982            if (obj instanceof SharedUserSetting) {
3983                final SharedUserSetting sus = (SharedUserSetting) obj;
3984                return sus.pkgFlags;
3985            } else if (obj instanceof PackageSetting) {
3986                final PackageSetting ps = (PackageSetting) obj;
3987                return ps.pkgFlags;
3988            }
3989        }
3990        return 0;
3991    }
3992
3993    @Override
3994    public int getPrivateFlagsForUid(int uid) {
3995        synchronized (mPackages) {
3996            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3997            if (obj instanceof SharedUserSetting) {
3998                final SharedUserSetting sus = (SharedUserSetting) obj;
3999                return sus.pkgPrivateFlags;
4000            } else if (obj instanceof PackageSetting) {
4001                final PackageSetting ps = (PackageSetting) obj;
4002                return ps.pkgPrivateFlags;
4003            }
4004        }
4005        return 0;
4006    }
4007
4008    @Override
4009    public boolean isUidPrivileged(int uid) {
4010        uid = UserHandle.getAppId(uid);
4011        // reader
4012        synchronized (mPackages) {
4013            Object obj = mSettings.getUserIdLPr(uid);
4014            if (obj instanceof SharedUserSetting) {
4015                final SharedUserSetting sus = (SharedUserSetting) obj;
4016                final Iterator<PackageSetting> it = sus.packages.iterator();
4017                while (it.hasNext()) {
4018                    if (it.next().isPrivileged()) {
4019                        return true;
4020                    }
4021                }
4022            } else if (obj instanceof PackageSetting) {
4023                final PackageSetting ps = (PackageSetting) obj;
4024                return ps.isPrivileged();
4025            }
4026        }
4027        return false;
4028    }
4029
4030    @Override
4031    public String[] getAppOpPermissionPackages(String permissionName) {
4032        synchronized (mPackages) {
4033            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4034            if (pkgs == null) {
4035                return null;
4036            }
4037            return pkgs.toArray(new String[pkgs.size()]);
4038        }
4039    }
4040
4041    @Override
4042    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4043            int flags, int userId) {
4044        if (!sUserManager.exists(userId)) return null;
4045        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4046        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4047        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4048    }
4049
4050    @Override
4051    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4052            IntentFilter filter, int match, ComponentName activity) {
4053        final int userId = UserHandle.getCallingUserId();
4054        if (DEBUG_PREFERRED) {
4055            Log.v(TAG, "setLastChosenActivity intent=" + intent
4056                + " resolvedType=" + resolvedType
4057                + " flags=" + flags
4058                + " filter=" + filter
4059                + " match=" + match
4060                + " activity=" + activity);
4061            filter.dump(new PrintStreamPrinter(System.out), "    ");
4062        }
4063        intent.setComponent(null);
4064        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4065        // Find any earlier preferred or last chosen entries and nuke them
4066        findPreferredActivity(intent, resolvedType,
4067                flags, query, 0, false, true, false, userId);
4068        // Add the new activity as the last chosen for this filter
4069        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4070                "Setting last chosen");
4071    }
4072
4073    @Override
4074    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4075        final int userId = UserHandle.getCallingUserId();
4076        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4077        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4078        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4079                false, false, false, userId);
4080    }
4081
4082    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4083            int flags, List<ResolveInfo> query, int userId) {
4084        if (query != null) {
4085            final int N = query.size();
4086            if (N == 1) {
4087                return query.get(0);
4088            } else if (N > 1) {
4089                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4090                // If there is more than one activity with the same priority,
4091                // then let the user decide between them.
4092                ResolveInfo r0 = query.get(0);
4093                ResolveInfo r1 = query.get(1);
4094                if (DEBUG_INTENT_MATCHING || debug) {
4095                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4096                            + r1.activityInfo.name + "=" + r1.priority);
4097                }
4098                // If the first activity has a higher priority, or a different
4099                // default, then it is always desireable to pick it.
4100                if (r0.priority != r1.priority
4101                        || r0.preferredOrder != r1.preferredOrder
4102                        || r0.isDefault != r1.isDefault) {
4103                    return query.get(0);
4104                }
4105                // If we have saved a preference for a preferred activity for
4106                // this Intent, use that.
4107                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4108                        flags, query, r0.priority, true, false, debug, userId);
4109                if (ri != null) {
4110                    return ri;
4111                }
4112                if (userId != 0) {
4113                    ri = new ResolveInfo(mResolveInfo);
4114                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4115                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4116                            ri.activityInfo.applicationInfo);
4117                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4118                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4119                    return ri;
4120                }
4121                return mResolveInfo;
4122            }
4123        }
4124        return null;
4125    }
4126
4127    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4128            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4129        final int N = query.size();
4130        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4131                .get(userId);
4132        // Get the list of persistent preferred activities that handle the intent
4133        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4134        List<PersistentPreferredActivity> pprefs = ppir != null
4135                ? ppir.queryIntent(intent, resolvedType,
4136                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4137                : null;
4138        if (pprefs != null && pprefs.size() > 0) {
4139            final int M = pprefs.size();
4140            for (int i=0; i<M; i++) {
4141                final PersistentPreferredActivity ppa = pprefs.get(i);
4142                if (DEBUG_PREFERRED || debug) {
4143                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4144                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4145                            + "\n  component=" + ppa.mComponent);
4146                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4147                }
4148                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4149                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4150                if (DEBUG_PREFERRED || debug) {
4151                    Slog.v(TAG, "Found persistent preferred activity:");
4152                    if (ai != null) {
4153                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4154                    } else {
4155                        Slog.v(TAG, "  null");
4156                    }
4157                }
4158                if (ai == null) {
4159                    // This previously registered persistent preferred activity
4160                    // component is no longer known. Ignore it and do NOT remove it.
4161                    continue;
4162                }
4163                for (int j=0; j<N; j++) {
4164                    final ResolveInfo ri = query.get(j);
4165                    if (!ri.activityInfo.applicationInfo.packageName
4166                            .equals(ai.applicationInfo.packageName)) {
4167                        continue;
4168                    }
4169                    if (!ri.activityInfo.name.equals(ai.name)) {
4170                        continue;
4171                    }
4172                    //  Found a persistent preference that can handle the intent.
4173                    if (DEBUG_PREFERRED || debug) {
4174                        Slog.v(TAG, "Returning persistent preferred activity: " +
4175                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4176                    }
4177                    return ri;
4178                }
4179            }
4180        }
4181        return null;
4182    }
4183
4184    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4185            List<ResolveInfo> query, int priority, boolean always,
4186            boolean removeMatches, boolean debug, int userId) {
4187        if (!sUserManager.exists(userId)) return null;
4188        // writer
4189        synchronized (mPackages) {
4190            if (intent.getSelector() != null) {
4191                intent = intent.getSelector();
4192            }
4193            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4194
4195            // Try to find a matching persistent preferred activity.
4196            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4197                    debug, userId);
4198
4199            // If a persistent preferred activity matched, use it.
4200            if (pri != null) {
4201                return pri;
4202            }
4203
4204            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4205            // Get the list of preferred activities that handle the intent
4206            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4207            List<PreferredActivity> prefs = pir != null
4208                    ? pir.queryIntent(intent, resolvedType,
4209                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4210                    : null;
4211            if (prefs != null && prefs.size() > 0) {
4212                boolean changed = false;
4213                try {
4214                    // First figure out how good the original match set is.
4215                    // We will only allow preferred activities that came
4216                    // from the same match quality.
4217                    int match = 0;
4218
4219                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4220
4221                    final int N = query.size();
4222                    for (int j=0; j<N; j++) {
4223                        final ResolveInfo ri = query.get(j);
4224                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4225                                + ": 0x" + Integer.toHexString(match));
4226                        if (ri.match > match) {
4227                            match = ri.match;
4228                        }
4229                    }
4230
4231                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4232                            + Integer.toHexString(match));
4233
4234                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4235                    final int M = prefs.size();
4236                    for (int i=0; i<M; i++) {
4237                        final PreferredActivity pa = prefs.get(i);
4238                        if (DEBUG_PREFERRED || debug) {
4239                            Slog.v(TAG, "Checking PreferredActivity ds="
4240                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4241                                    + "\n  component=" + pa.mPref.mComponent);
4242                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4243                        }
4244                        if (pa.mPref.mMatch != match) {
4245                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4246                                    + Integer.toHexString(pa.mPref.mMatch));
4247                            continue;
4248                        }
4249                        // If it's not an "always" type preferred activity and that's what we're
4250                        // looking for, skip it.
4251                        if (always && !pa.mPref.mAlways) {
4252                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4253                            continue;
4254                        }
4255                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4256                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4257                        if (DEBUG_PREFERRED || debug) {
4258                            Slog.v(TAG, "Found preferred activity:");
4259                            if (ai != null) {
4260                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4261                            } else {
4262                                Slog.v(TAG, "  null");
4263                            }
4264                        }
4265                        if (ai == null) {
4266                            // This previously registered preferred activity
4267                            // component is no longer known.  Most likely an update
4268                            // to the app was installed and in the new version this
4269                            // component no longer exists.  Clean it up by removing
4270                            // it from the preferred activities list, and skip it.
4271                            Slog.w(TAG, "Removing dangling preferred activity: "
4272                                    + pa.mPref.mComponent);
4273                            pir.removeFilter(pa);
4274                            changed = true;
4275                            continue;
4276                        }
4277                        for (int j=0; j<N; j++) {
4278                            final ResolveInfo ri = query.get(j);
4279                            if (!ri.activityInfo.applicationInfo.packageName
4280                                    .equals(ai.applicationInfo.packageName)) {
4281                                continue;
4282                            }
4283                            if (!ri.activityInfo.name.equals(ai.name)) {
4284                                continue;
4285                            }
4286
4287                            if (removeMatches) {
4288                                pir.removeFilter(pa);
4289                                changed = true;
4290                                if (DEBUG_PREFERRED) {
4291                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4292                                }
4293                                break;
4294                            }
4295
4296                            // Okay we found a previously set preferred or last chosen app.
4297                            // If the result set is different from when this
4298                            // was created, we need to clear it and re-ask the
4299                            // user their preference, if we're looking for an "always" type entry.
4300                            if (always && !pa.mPref.sameSet(query)) {
4301                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4302                                        + intent + " type " + resolvedType);
4303                                if (DEBUG_PREFERRED) {
4304                                    Slog.v(TAG, "Removing preferred activity since set changed "
4305                                            + pa.mPref.mComponent);
4306                                }
4307                                pir.removeFilter(pa);
4308                                // Re-add the filter as a "last chosen" entry (!always)
4309                                PreferredActivity lastChosen = new PreferredActivity(
4310                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4311                                pir.addFilter(lastChosen);
4312                                changed = true;
4313                                return null;
4314                            }
4315
4316                            // Yay! Either the set matched or we're looking for the last chosen
4317                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4318                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4319                            return ri;
4320                        }
4321                    }
4322                } finally {
4323                    if (changed) {
4324                        if (DEBUG_PREFERRED) {
4325                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4326                        }
4327                        scheduleWritePackageRestrictionsLocked(userId);
4328                    }
4329                }
4330            }
4331        }
4332        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4333        return null;
4334    }
4335
4336    /*
4337     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4338     */
4339    @Override
4340    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4341            int targetUserId) {
4342        mContext.enforceCallingOrSelfPermission(
4343                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4344        List<CrossProfileIntentFilter> matches =
4345                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4346        if (matches != null) {
4347            int size = matches.size();
4348            for (int i = 0; i < size; i++) {
4349                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4350            }
4351        }
4352        if (hasWebURI(intent)) {
4353            // cross-profile app linking works only towards the parent.
4354            final UserInfo parent = getProfileParent(sourceUserId);
4355            synchronized(mPackages) {
4356                return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId,
4357                        parent.id) != null;
4358            }
4359        }
4360        return false;
4361    }
4362
4363    private UserInfo getProfileParent(int userId) {
4364        final long identity = Binder.clearCallingIdentity();
4365        try {
4366            return sUserManager.getProfileParent(userId);
4367        } finally {
4368            Binder.restoreCallingIdentity(identity);
4369        }
4370    }
4371
4372    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4373            String resolvedType, int userId) {
4374        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4375        if (resolver != null) {
4376            return resolver.queryIntent(intent, resolvedType, false, userId);
4377        }
4378        return null;
4379    }
4380
4381    @Override
4382    public List<ResolveInfo> queryIntentActivities(Intent intent,
4383            String resolvedType, int flags, int userId) {
4384        if (!sUserManager.exists(userId)) return Collections.emptyList();
4385        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4386        ComponentName comp = intent.getComponent();
4387        if (comp == null) {
4388            if (intent.getSelector() != null) {
4389                intent = intent.getSelector();
4390                comp = intent.getComponent();
4391            }
4392        }
4393
4394        if (comp != null) {
4395            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4396            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4397            if (ai != null) {
4398                final ResolveInfo ri = new ResolveInfo();
4399                ri.activityInfo = ai;
4400                list.add(ri);
4401            }
4402            return list;
4403        }
4404
4405        // reader
4406        synchronized (mPackages) {
4407            final String pkgName = intent.getPackage();
4408            if (pkgName == null) {
4409                List<CrossProfileIntentFilter> matchingFilters =
4410                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4411                // Check for results that need to skip the current profile.
4412                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4413                        resolvedType, flags, userId);
4414                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4415                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4416                    result.add(xpResolveInfo);
4417                    return filterIfNotPrimaryUser(result, userId);
4418                }
4419
4420                // Check for results in the current profile.
4421                List<ResolveInfo> result = mActivities.queryIntent(
4422                        intent, resolvedType, flags, userId);
4423
4424                // Check for cross profile results.
4425                xpResolveInfo = queryCrossProfileIntents(
4426                        matchingFilters, intent, resolvedType, flags, userId);
4427                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4428                    result.add(xpResolveInfo);
4429                    Collections.sort(result, mResolvePrioritySorter);
4430                }
4431                result = filterIfNotPrimaryUser(result, userId);
4432                if (hasWebURI(intent)) {
4433                    CrossProfileDomainInfo xpDomainInfo = null;
4434                    final UserInfo parent = getProfileParent(userId);
4435                    if (parent != null) {
4436                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4437                                flags, userId, parent.id);
4438                    }
4439                    if (xpDomainInfo != null) {
4440                        if (xpResolveInfo != null) {
4441                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4442                            // in the result.
4443                            result.remove(xpResolveInfo);
4444                        }
4445                        if (result.size() == 0) {
4446                            result.add(xpDomainInfo.resolveInfo);
4447                            return result;
4448                        }
4449                    } else if (result.size() <= 1) {
4450                        return result;
4451                    }
4452                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4453                            xpDomainInfo);
4454                    Collections.sort(result, mResolvePrioritySorter);
4455                }
4456                return result;
4457            }
4458            final PackageParser.Package pkg = mPackages.get(pkgName);
4459            if (pkg != null) {
4460                return filterIfNotPrimaryUser(
4461                        mActivities.queryIntentForPackage(
4462                                intent, resolvedType, flags, pkg.activities, userId),
4463                        userId);
4464            }
4465            return new ArrayList<ResolveInfo>();
4466        }
4467    }
4468
4469    private static class CrossProfileDomainInfo {
4470        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4471        ResolveInfo resolveInfo;
4472        /* Best domain verification status of the activities found in the other profile */
4473        int bestDomainVerificationStatus;
4474    }
4475
4476    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4477            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4478        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4479                sourceUserId)) {
4480            return null;
4481        }
4482        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4483                resolvedType, flags, parentUserId);
4484
4485        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4486            return null;
4487        }
4488        CrossProfileDomainInfo result = null;
4489        int size = resultTargetUser.size();
4490        for (int i = 0; i < size; i++) {
4491            ResolveInfo riTargetUser = resultTargetUser.get(i);
4492            // Intent filter verification is only for filters that specify a host. So don't return
4493            // those that handle all web uris.
4494            if (riTargetUser.handleAllWebDataURI) {
4495                continue;
4496            }
4497            String packageName = riTargetUser.activityInfo.packageName;
4498            PackageSetting ps = mSettings.mPackages.get(packageName);
4499            if (ps == null) {
4500                continue;
4501            }
4502            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4503            if (result == null) {
4504                result = new CrossProfileDomainInfo();
4505                result.resolveInfo =
4506                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4507                result.bestDomainVerificationStatus = status;
4508            } else {
4509                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4510                        result.bestDomainVerificationStatus);
4511            }
4512        }
4513        return result;
4514    }
4515
4516    /**
4517     * Verification statuses are ordered from the worse to the best, except for
4518     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4519     */
4520    private int bestDomainVerificationStatus(int status1, int status2) {
4521        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4522            return status2;
4523        }
4524        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4525            return status1;
4526        }
4527        return (int) MathUtils.max(status1, status2);
4528    }
4529
4530    private boolean isUserEnabled(int userId) {
4531        long callingId = Binder.clearCallingIdentity();
4532        try {
4533            UserInfo userInfo = sUserManager.getUserInfo(userId);
4534            return userInfo != null && userInfo.isEnabled();
4535        } finally {
4536            Binder.restoreCallingIdentity(callingId);
4537        }
4538    }
4539
4540    /**
4541     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4542     *
4543     * @return filtered list
4544     */
4545    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4546        if (userId == UserHandle.USER_OWNER) {
4547            return resolveInfos;
4548        }
4549        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4550            ResolveInfo info = resolveInfos.get(i);
4551            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4552                resolveInfos.remove(i);
4553            }
4554        }
4555        return resolveInfos;
4556    }
4557
4558    private static boolean hasWebURI(Intent intent) {
4559        if (intent.getData() == null) {
4560            return false;
4561        }
4562        final String scheme = intent.getScheme();
4563        if (TextUtils.isEmpty(scheme)) {
4564            return false;
4565        }
4566        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4567    }
4568
4569    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4570            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4571        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4572            Slog.v("TAG", "Filtering results with preferred activities. Candidates count: " +
4573                    candidates.size());
4574        }
4575
4576        final int userId = UserHandle.getCallingUserId();
4577        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4578        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4579        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4580        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4581        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4582
4583        synchronized (mPackages) {
4584            final int count = candidates.size();
4585            // First, try to use linked apps. Partition the candidates into four lists:
4586            // one for the final results, one for the "do not use ever", one for "undefined status"
4587            // and finally one for "browser app type".
4588            for (int n=0; n<count; n++) {
4589                ResolveInfo info = candidates.get(n);
4590                String packageName = info.activityInfo.packageName;
4591                PackageSetting ps = mSettings.mPackages.get(packageName);
4592                if (ps != null) {
4593                    // Add to the special match all list (Browser use case)
4594                    if (info.handleAllWebDataURI) {
4595                        matchAllList.add(info);
4596                        continue;
4597                    }
4598                    // Try to get the status from User settings first
4599                    int status = getDomainVerificationStatusLPr(ps, userId);
4600                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4601                        if (DEBUG_DOMAIN_VERIFICATION) {
4602                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName);
4603                        }
4604                        alwaysList.add(info);
4605                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4606                        if (DEBUG_DOMAIN_VERIFICATION) {
4607                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4608                        }
4609                        neverList.add(info);
4610                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4611                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4612                        if (DEBUG_DOMAIN_VERIFICATION) {
4613                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4614                        }
4615                        undefinedList.add(info);
4616                    }
4617                }
4618            }
4619            // First try to add the "always" resolution for the current user if there is any
4620            if (alwaysList.size() > 0) {
4621                result.addAll(alwaysList);
4622            // if there is an "always" for the parent user, add it.
4623            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4624                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4625                result.add(xpDomainInfo.resolveInfo);
4626            } else {
4627                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4628                result.addAll(undefinedList);
4629                if (xpDomainInfo != null && (
4630                        xpDomainInfo.bestDomainVerificationStatus
4631                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4632                        || xpDomainInfo.bestDomainVerificationStatus
4633                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4634                    result.add(xpDomainInfo.resolveInfo);
4635                }
4636                // Also add Browsers (all of them or only the default one)
4637                if ((flags & MATCH_ALL) != 0) {
4638                    result.addAll(matchAllList);
4639                } else {
4640                    // Try to add the Default Browser if we can
4641                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4642                            UserHandle.myUserId());
4643                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4644                        boolean defaultBrowserFound = false;
4645                        final int browserCount = matchAllList.size();
4646                        for (int n=0; n<browserCount; n++) {
4647                            ResolveInfo browser = matchAllList.get(n);
4648                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4649                                result.add(browser);
4650                                defaultBrowserFound = true;
4651                                break;
4652                            }
4653                        }
4654                        if (!defaultBrowserFound) {
4655                            result.addAll(matchAllList);
4656                        }
4657                    } else {
4658                        result.addAll(matchAllList);
4659                    }
4660                }
4661
4662                // If there is nothing selected, add all candidates and remove the ones that the user
4663                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4664                if (result.size() == 0) {
4665                    result.addAll(candidates);
4666                    result.removeAll(neverList);
4667                }
4668            }
4669        }
4670        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4671            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4672                    result.size());
4673            for (ResolveInfo info : result) {
4674                Slog.v(TAG, "  + " + info.activityInfo);
4675            }
4676        }
4677        return result;
4678    }
4679
4680    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4681        int status = ps.getDomainVerificationStatusForUser(userId);
4682        // if none available, get the master status
4683        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4684            if (ps.getIntentFilterVerificationInfo() != null) {
4685                status = ps.getIntentFilterVerificationInfo().getStatus();
4686            }
4687        }
4688        return status;
4689    }
4690
4691    private ResolveInfo querySkipCurrentProfileIntents(
4692            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4693            int flags, int sourceUserId) {
4694        if (matchingFilters != null) {
4695            int size = matchingFilters.size();
4696            for (int i = 0; i < size; i ++) {
4697                CrossProfileIntentFilter filter = matchingFilters.get(i);
4698                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4699                    // Checking if there are activities in the target user that can handle the
4700                    // intent.
4701                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4702                            flags, sourceUserId);
4703                    if (resolveInfo != null) {
4704                        return resolveInfo;
4705                    }
4706                }
4707            }
4708        }
4709        return null;
4710    }
4711
4712    // Return matching ResolveInfo if any for skip current profile intent filters.
4713    private ResolveInfo queryCrossProfileIntents(
4714            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4715            int flags, int sourceUserId) {
4716        if (matchingFilters != null) {
4717            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4718            // match the same intent. For performance reasons, it is better not to
4719            // run queryIntent twice for the same userId
4720            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4721            int size = matchingFilters.size();
4722            for (int i = 0; i < size; i++) {
4723                CrossProfileIntentFilter filter = matchingFilters.get(i);
4724                int targetUserId = filter.getTargetUserId();
4725                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4726                        && !alreadyTriedUserIds.get(targetUserId)) {
4727                    // Checking if there are activities in the target user that can handle the
4728                    // intent.
4729                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4730                            flags, sourceUserId);
4731                    if (resolveInfo != null) return resolveInfo;
4732                    alreadyTriedUserIds.put(targetUserId, true);
4733                }
4734            }
4735        }
4736        return null;
4737    }
4738
4739    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4740            String resolvedType, int flags, int sourceUserId) {
4741        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4742                resolvedType, flags, filter.getTargetUserId());
4743        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4744            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4745        }
4746        return null;
4747    }
4748
4749    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4750            int sourceUserId, int targetUserId) {
4751        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4752        String className;
4753        if (targetUserId == UserHandle.USER_OWNER) {
4754            className = FORWARD_INTENT_TO_USER_OWNER;
4755        } else {
4756            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4757        }
4758        ComponentName forwardingActivityComponentName = new ComponentName(
4759                mAndroidApplication.packageName, className);
4760        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4761                sourceUserId);
4762        if (targetUserId == UserHandle.USER_OWNER) {
4763            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4764            forwardingResolveInfo.noResourceId = true;
4765        }
4766        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4767        forwardingResolveInfo.priority = 0;
4768        forwardingResolveInfo.preferredOrder = 0;
4769        forwardingResolveInfo.match = 0;
4770        forwardingResolveInfo.isDefault = true;
4771        forwardingResolveInfo.filter = filter;
4772        forwardingResolveInfo.targetUserId = targetUserId;
4773        return forwardingResolveInfo;
4774    }
4775
4776    @Override
4777    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4778            Intent[] specifics, String[] specificTypes, Intent intent,
4779            String resolvedType, int flags, int userId) {
4780        if (!sUserManager.exists(userId)) return Collections.emptyList();
4781        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4782                false, "query intent activity options");
4783        final String resultsAction = intent.getAction();
4784
4785        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4786                | PackageManager.GET_RESOLVED_FILTER, userId);
4787
4788        if (DEBUG_INTENT_MATCHING) {
4789            Log.v(TAG, "Query " + intent + ": " + results);
4790        }
4791
4792        int specificsPos = 0;
4793        int N;
4794
4795        // todo: note that the algorithm used here is O(N^2).  This
4796        // isn't a problem in our current environment, but if we start running
4797        // into situations where we have more than 5 or 10 matches then this
4798        // should probably be changed to something smarter...
4799
4800        // First we go through and resolve each of the specific items
4801        // that were supplied, taking care of removing any corresponding
4802        // duplicate items in the generic resolve list.
4803        if (specifics != null) {
4804            for (int i=0; i<specifics.length; i++) {
4805                final Intent sintent = specifics[i];
4806                if (sintent == null) {
4807                    continue;
4808                }
4809
4810                if (DEBUG_INTENT_MATCHING) {
4811                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4812                }
4813
4814                String action = sintent.getAction();
4815                if (resultsAction != null && resultsAction.equals(action)) {
4816                    // If this action was explicitly requested, then don't
4817                    // remove things that have it.
4818                    action = null;
4819                }
4820
4821                ResolveInfo ri = null;
4822                ActivityInfo ai = null;
4823
4824                ComponentName comp = sintent.getComponent();
4825                if (comp == null) {
4826                    ri = resolveIntent(
4827                        sintent,
4828                        specificTypes != null ? specificTypes[i] : null,
4829                            flags, userId);
4830                    if (ri == null) {
4831                        continue;
4832                    }
4833                    if (ri == mResolveInfo) {
4834                        // ACK!  Must do something better with this.
4835                    }
4836                    ai = ri.activityInfo;
4837                    comp = new ComponentName(ai.applicationInfo.packageName,
4838                            ai.name);
4839                } else {
4840                    ai = getActivityInfo(comp, flags, userId);
4841                    if (ai == null) {
4842                        continue;
4843                    }
4844                }
4845
4846                // Look for any generic query activities that are duplicates
4847                // of this specific one, and remove them from the results.
4848                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4849                N = results.size();
4850                int j;
4851                for (j=specificsPos; j<N; j++) {
4852                    ResolveInfo sri = results.get(j);
4853                    if ((sri.activityInfo.name.equals(comp.getClassName())
4854                            && sri.activityInfo.applicationInfo.packageName.equals(
4855                                    comp.getPackageName()))
4856                        || (action != null && sri.filter.matchAction(action))) {
4857                        results.remove(j);
4858                        if (DEBUG_INTENT_MATCHING) Log.v(
4859                            TAG, "Removing duplicate item from " + j
4860                            + " due to specific " + specificsPos);
4861                        if (ri == null) {
4862                            ri = sri;
4863                        }
4864                        j--;
4865                        N--;
4866                    }
4867                }
4868
4869                // Add this specific item to its proper place.
4870                if (ri == null) {
4871                    ri = new ResolveInfo();
4872                    ri.activityInfo = ai;
4873                }
4874                results.add(specificsPos, ri);
4875                ri.specificIndex = i;
4876                specificsPos++;
4877            }
4878        }
4879
4880        // Now we go through the remaining generic results and remove any
4881        // duplicate actions that are found here.
4882        N = results.size();
4883        for (int i=specificsPos; i<N-1; i++) {
4884            final ResolveInfo rii = results.get(i);
4885            if (rii.filter == null) {
4886                continue;
4887            }
4888
4889            // Iterate over all of the actions of this result's intent
4890            // filter...  typically this should be just one.
4891            final Iterator<String> it = rii.filter.actionsIterator();
4892            if (it == null) {
4893                continue;
4894            }
4895            while (it.hasNext()) {
4896                final String action = it.next();
4897                if (resultsAction != null && resultsAction.equals(action)) {
4898                    // If this action was explicitly requested, then don't
4899                    // remove things that have it.
4900                    continue;
4901                }
4902                for (int j=i+1; j<N; j++) {
4903                    final ResolveInfo rij = results.get(j);
4904                    if (rij.filter != null && rij.filter.hasAction(action)) {
4905                        results.remove(j);
4906                        if (DEBUG_INTENT_MATCHING) Log.v(
4907                            TAG, "Removing duplicate item from " + j
4908                            + " due to action " + action + " at " + i);
4909                        j--;
4910                        N--;
4911                    }
4912                }
4913            }
4914
4915            // If the caller didn't request filter information, drop it now
4916            // so we don't have to marshall/unmarshall it.
4917            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4918                rii.filter = null;
4919            }
4920        }
4921
4922        // Filter out the caller activity if so requested.
4923        if (caller != null) {
4924            N = results.size();
4925            for (int i=0; i<N; i++) {
4926                ActivityInfo ainfo = results.get(i).activityInfo;
4927                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4928                        && caller.getClassName().equals(ainfo.name)) {
4929                    results.remove(i);
4930                    break;
4931                }
4932            }
4933        }
4934
4935        // If the caller didn't request filter information,
4936        // drop them now so we don't have to
4937        // marshall/unmarshall it.
4938        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4939            N = results.size();
4940            for (int i=0; i<N; i++) {
4941                results.get(i).filter = null;
4942            }
4943        }
4944
4945        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4946        return results;
4947    }
4948
4949    @Override
4950    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4951            int userId) {
4952        if (!sUserManager.exists(userId)) return Collections.emptyList();
4953        ComponentName comp = intent.getComponent();
4954        if (comp == null) {
4955            if (intent.getSelector() != null) {
4956                intent = intent.getSelector();
4957                comp = intent.getComponent();
4958            }
4959        }
4960        if (comp != null) {
4961            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4962            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4963            if (ai != null) {
4964                ResolveInfo ri = new ResolveInfo();
4965                ri.activityInfo = ai;
4966                list.add(ri);
4967            }
4968            return list;
4969        }
4970
4971        // reader
4972        synchronized (mPackages) {
4973            String pkgName = intent.getPackage();
4974            if (pkgName == null) {
4975                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4976            }
4977            final PackageParser.Package pkg = mPackages.get(pkgName);
4978            if (pkg != null) {
4979                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4980                        userId);
4981            }
4982            return null;
4983        }
4984    }
4985
4986    @Override
4987    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4988        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4989        if (!sUserManager.exists(userId)) return null;
4990        if (query != null) {
4991            if (query.size() >= 1) {
4992                // If there is more than one service with the same priority,
4993                // just arbitrarily pick the first one.
4994                return query.get(0);
4995            }
4996        }
4997        return null;
4998    }
4999
5000    @Override
5001    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5002            int userId) {
5003        if (!sUserManager.exists(userId)) return Collections.emptyList();
5004        ComponentName comp = intent.getComponent();
5005        if (comp == null) {
5006            if (intent.getSelector() != null) {
5007                intent = intent.getSelector();
5008                comp = intent.getComponent();
5009            }
5010        }
5011        if (comp != null) {
5012            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5013            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5014            if (si != null) {
5015                final ResolveInfo ri = new ResolveInfo();
5016                ri.serviceInfo = si;
5017                list.add(ri);
5018            }
5019            return list;
5020        }
5021
5022        // reader
5023        synchronized (mPackages) {
5024            String pkgName = intent.getPackage();
5025            if (pkgName == null) {
5026                return mServices.queryIntent(intent, resolvedType, flags, userId);
5027            }
5028            final PackageParser.Package pkg = mPackages.get(pkgName);
5029            if (pkg != null) {
5030                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5031                        userId);
5032            }
5033            return null;
5034        }
5035    }
5036
5037    @Override
5038    public List<ResolveInfo> queryIntentContentProviders(
5039            Intent intent, String resolvedType, int flags, int userId) {
5040        if (!sUserManager.exists(userId)) return Collections.emptyList();
5041        ComponentName comp = intent.getComponent();
5042        if (comp == null) {
5043            if (intent.getSelector() != null) {
5044                intent = intent.getSelector();
5045                comp = intent.getComponent();
5046            }
5047        }
5048        if (comp != null) {
5049            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5050            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5051            if (pi != null) {
5052                final ResolveInfo ri = new ResolveInfo();
5053                ri.providerInfo = pi;
5054                list.add(ri);
5055            }
5056            return list;
5057        }
5058
5059        // reader
5060        synchronized (mPackages) {
5061            String pkgName = intent.getPackage();
5062            if (pkgName == null) {
5063                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5064            }
5065            final PackageParser.Package pkg = mPackages.get(pkgName);
5066            if (pkg != null) {
5067                return mProviders.queryIntentForPackage(
5068                        intent, resolvedType, flags, pkg.providers, userId);
5069            }
5070            return null;
5071        }
5072    }
5073
5074    @Override
5075    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5076        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5077
5078        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5079
5080        // writer
5081        synchronized (mPackages) {
5082            ArrayList<PackageInfo> list;
5083            if (listUninstalled) {
5084                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5085                for (PackageSetting ps : mSettings.mPackages.values()) {
5086                    PackageInfo pi;
5087                    if (ps.pkg != null) {
5088                        pi = generatePackageInfo(ps.pkg, flags, userId);
5089                    } else {
5090                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5091                    }
5092                    if (pi != null) {
5093                        list.add(pi);
5094                    }
5095                }
5096            } else {
5097                list = new ArrayList<PackageInfo>(mPackages.size());
5098                for (PackageParser.Package p : mPackages.values()) {
5099                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5100                    if (pi != null) {
5101                        list.add(pi);
5102                    }
5103                }
5104            }
5105
5106            return new ParceledListSlice<PackageInfo>(list);
5107        }
5108    }
5109
5110    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5111            String[] permissions, boolean[] tmp, int flags, int userId) {
5112        int numMatch = 0;
5113        final PermissionsState permissionsState = ps.getPermissionsState();
5114        for (int i=0; i<permissions.length; i++) {
5115            final String permission = permissions[i];
5116            if (permissionsState.hasPermission(permission, userId)) {
5117                tmp[i] = true;
5118                numMatch++;
5119            } else {
5120                tmp[i] = false;
5121            }
5122        }
5123        if (numMatch == 0) {
5124            return;
5125        }
5126        PackageInfo pi;
5127        if (ps.pkg != null) {
5128            pi = generatePackageInfo(ps.pkg, flags, userId);
5129        } else {
5130            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5131        }
5132        // The above might return null in cases of uninstalled apps or install-state
5133        // skew across users/profiles.
5134        if (pi != null) {
5135            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5136                if (numMatch == permissions.length) {
5137                    pi.requestedPermissions = permissions;
5138                } else {
5139                    pi.requestedPermissions = new String[numMatch];
5140                    numMatch = 0;
5141                    for (int i=0; i<permissions.length; i++) {
5142                        if (tmp[i]) {
5143                            pi.requestedPermissions[numMatch] = permissions[i];
5144                            numMatch++;
5145                        }
5146                    }
5147                }
5148            }
5149            list.add(pi);
5150        }
5151    }
5152
5153    @Override
5154    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5155            String[] permissions, int flags, int userId) {
5156        if (!sUserManager.exists(userId)) return null;
5157        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5158
5159        // writer
5160        synchronized (mPackages) {
5161            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5162            boolean[] tmpBools = new boolean[permissions.length];
5163            if (listUninstalled) {
5164                for (PackageSetting ps : mSettings.mPackages.values()) {
5165                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5166                }
5167            } else {
5168                for (PackageParser.Package pkg : mPackages.values()) {
5169                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5170                    if (ps != null) {
5171                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5172                                userId);
5173                    }
5174                }
5175            }
5176
5177            return new ParceledListSlice<PackageInfo>(list);
5178        }
5179    }
5180
5181    @Override
5182    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5183        if (!sUserManager.exists(userId)) return null;
5184        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5185
5186        // writer
5187        synchronized (mPackages) {
5188            ArrayList<ApplicationInfo> list;
5189            if (listUninstalled) {
5190                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5191                for (PackageSetting ps : mSettings.mPackages.values()) {
5192                    ApplicationInfo ai;
5193                    if (ps.pkg != null) {
5194                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5195                                ps.readUserState(userId), userId);
5196                    } else {
5197                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5198                    }
5199                    if (ai != null) {
5200                        list.add(ai);
5201                    }
5202                }
5203            } else {
5204                list = new ArrayList<ApplicationInfo>(mPackages.size());
5205                for (PackageParser.Package p : mPackages.values()) {
5206                    if (p.mExtras != null) {
5207                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5208                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5209                        if (ai != null) {
5210                            list.add(ai);
5211                        }
5212                    }
5213                }
5214            }
5215
5216            return new ParceledListSlice<ApplicationInfo>(list);
5217        }
5218    }
5219
5220    public List<ApplicationInfo> getPersistentApplications(int flags) {
5221        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5222
5223        // reader
5224        synchronized (mPackages) {
5225            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5226            final int userId = UserHandle.getCallingUserId();
5227            while (i.hasNext()) {
5228                final PackageParser.Package p = i.next();
5229                if (p.applicationInfo != null
5230                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5231                        && (!mSafeMode || isSystemApp(p))) {
5232                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5233                    if (ps != null) {
5234                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5235                                ps.readUserState(userId), userId);
5236                        if (ai != null) {
5237                            finalList.add(ai);
5238                        }
5239                    }
5240                }
5241            }
5242        }
5243
5244        return finalList;
5245    }
5246
5247    @Override
5248    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5249        if (!sUserManager.exists(userId)) return null;
5250        // reader
5251        synchronized (mPackages) {
5252            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5253            PackageSetting ps = provider != null
5254                    ? mSettings.mPackages.get(provider.owner.packageName)
5255                    : null;
5256            return ps != null
5257                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5258                    && (!mSafeMode || (provider.info.applicationInfo.flags
5259                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5260                    ? PackageParser.generateProviderInfo(provider, flags,
5261                            ps.readUserState(userId), userId)
5262                    : null;
5263        }
5264    }
5265
5266    /**
5267     * @deprecated
5268     */
5269    @Deprecated
5270    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5271        // reader
5272        synchronized (mPackages) {
5273            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5274                    .entrySet().iterator();
5275            final int userId = UserHandle.getCallingUserId();
5276            while (i.hasNext()) {
5277                Map.Entry<String, PackageParser.Provider> entry = i.next();
5278                PackageParser.Provider p = entry.getValue();
5279                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5280
5281                if (ps != null && p.syncable
5282                        && (!mSafeMode || (p.info.applicationInfo.flags
5283                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5284                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5285                            ps.readUserState(userId), userId);
5286                    if (info != null) {
5287                        outNames.add(entry.getKey());
5288                        outInfo.add(info);
5289                    }
5290                }
5291            }
5292        }
5293    }
5294
5295    @Override
5296    public List<ProviderInfo> queryContentProviders(String processName,
5297            int uid, int flags) {
5298        ArrayList<ProviderInfo> finalList = null;
5299        // reader
5300        synchronized (mPackages) {
5301            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5302            final int userId = processName != null ?
5303                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5304            while (i.hasNext()) {
5305                final PackageParser.Provider p = i.next();
5306                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5307                if (ps != null && p.info.authority != null
5308                        && (processName == null
5309                                || (p.info.processName.equals(processName)
5310                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5311                        && mSettings.isEnabledLPr(p.info, flags, userId)
5312                        && (!mSafeMode
5313                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5314                    if (finalList == null) {
5315                        finalList = new ArrayList<ProviderInfo>(3);
5316                    }
5317                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5318                            ps.readUserState(userId), userId);
5319                    if (info != null) {
5320                        finalList.add(info);
5321                    }
5322                }
5323            }
5324        }
5325
5326        if (finalList != null) {
5327            Collections.sort(finalList, mProviderInitOrderSorter);
5328        }
5329
5330        return finalList;
5331    }
5332
5333    @Override
5334    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5335            int flags) {
5336        // reader
5337        synchronized (mPackages) {
5338            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5339            return PackageParser.generateInstrumentationInfo(i, flags);
5340        }
5341    }
5342
5343    @Override
5344    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5345            int flags) {
5346        ArrayList<InstrumentationInfo> finalList =
5347            new ArrayList<InstrumentationInfo>();
5348
5349        // reader
5350        synchronized (mPackages) {
5351            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5352            while (i.hasNext()) {
5353                final PackageParser.Instrumentation p = i.next();
5354                if (targetPackage == null
5355                        || targetPackage.equals(p.info.targetPackage)) {
5356                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5357                            flags);
5358                    if (ii != null) {
5359                        finalList.add(ii);
5360                    }
5361                }
5362            }
5363        }
5364
5365        return finalList;
5366    }
5367
5368    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5369        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5370        if (overlays == null) {
5371            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5372            return;
5373        }
5374        for (PackageParser.Package opkg : overlays.values()) {
5375            // Not much to do if idmap fails: we already logged the error
5376            // and we certainly don't want to abort installation of pkg simply
5377            // because an overlay didn't fit properly. For these reasons,
5378            // ignore the return value of createIdmapForPackagePairLI.
5379            createIdmapForPackagePairLI(pkg, opkg);
5380        }
5381    }
5382
5383    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5384            PackageParser.Package opkg) {
5385        if (!opkg.mTrustedOverlay) {
5386            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5387                    opkg.baseCodePath + ": overlay not trusted");
5388            return false;
5389        }
5390        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5391        if (overlaySet == null) {
5392            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5393                    opkg.baseCodePath + " but target package has no known overlays");
5394            return false;
5395        }
5396        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5397        // TODO: generate idmap for split APKs
5398        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5399            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5400                    + opkg.baseCodePath);
5401            return false;
5402        }
5403        PackageParser.Package[] overlayArray =
5404            overlaySet.values().toArray(new PackageParser.Package[0]);
5405        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5406            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5407                return p1.mOverlayPriority - p2.mOverlayPriority;
5408            }
5409        };
5410        Arrays.sort(overlayArray, cmp);
5411
5412        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5413        int i = 0;
5414        for (PackageParser.Package p : overlayArray) {
5415            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5416        }
5417        return true;
5418    }
5419
5420    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5421        final File[] files = dir.listFiles();
5422        if (ArrayUtils.isEmpty(files)) {
5423            Log.d(TAG, "No files in app dir " + dir);
5424            return;
5425        }
5426
5427        if (DEBUG_PACKAGE_SCANNING) {
5428            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5429                    + " flags=0x" + Integer.toHexString(parseFlags));
5430        }
5431
5432        for (File file : files) {
5433            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5434                    && !PackageInstallerService.isStageName(file.getName());
5435            if (!isPackage) {
5436                // Ignore entries which are not packages
5437                continue;
5438            }
5439            try {
5440                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5441                        scanFlags, currentTime, null);
5442            } catch (PackageManagerException e) {
5443                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5444
5445                // Delete invalid userdata apps
5446                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5447                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5448                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5449                    if (file.isDirectory()) {
5450                        mInstaller.rmPackageDir(file.getAbsolutePath());
5451                    } else {
5452                        file.delete();
5453                    }
5454                }
5455            }
5456        }
5457    }
5458
5459    private static File getSettingsProblemFile() {
5460        File dataDir = Environment.getDataDirectory();
5461        File systemDir = new File(dataDir, "system");
5462        File fname = new File(systemDir, "uiderrors.txt");
5463        return fname;
5464    }
5465
5466    static void reportSettingsProblem(int priority, String msg) {
5467        logCriticalInfo(priority, msg);
5468    }
5469
5470    static void logCriticalInfo(int priority, String msg) {
5471        Slog.println(priority, TAG, msg);
5472        EventLogTags.writePmCriticalInfo(msg);
5473        try {
5474            File fname = getSettingsProblemFile();
5475            FileOutputStream out = new FileOutputStream(fname, true);
5476            PrintWriter pw = new FastPrintWriter(out);
5477            SimpleDateFormat formatter = new SimpleDateFormat();
5478            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5479            pw.println(dateString + ": " + msg);
5480            pw.close();
5481            FileUtils.setPermissions(
5482                    fname.toString(),
5483                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5484                    -1, -1);
5485        } catch (java.io.IOException e) {
5486        }
5487    }
5488
5489    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5490            PackageParser.Package pkg, File srcFile, int parseFlags)
5491            throws PackageManagerException {
5492        if (ps != null
5493                && ps.codePath.equals(srcFile)
5494                && ps.timeStamp == srcFile.lastModified()
5495                && !isCompatSignatureUpdateNeeded(pkg)
5496                && !isRecoverSignatureUpdateNeeded(pkg)) {
5497            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5498            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5499            ArraySet<PublicKey> signingKs;
5500            synchronized (mPackages) {
5501                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5502            }
5503            if (ps.signatures.mSignatures != null
5504                    && ps.signatures.mSignatures.length != 0
5505                    && signingKs != null) {
5506                // Optimization: reuse the existing cached certificates
5507                // if the package appears to be unchanged.
5508                pkg.mSignatures = ps.signatures.mSignatures;
5509                pkg.mSigningKeys = signingKs;
5510                return;
5511            }
5512
5513            Slog.w(TAG, "PackageSetting for " + ps.name
5514                    + " is missing signatures.  Collecting certs again to recover them.");
5515        } else {
5516            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5517        }
5518
5519        try {
5520            pp.collectCertificates(pkg, parseFlags);
5521            pp.collectManifestDigest(pkg);
5522        } catch (PackageParserException e) {
5523            throw PackageManagerException.from(e);
5524        }
5525    }
5526
5527    /*
5528     *  Scan a package and return the newly parsed package.
5529     *  Returns null in case of errors and the error code is stored in mLastScanError
5530     */
5531    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5532            long currentTime, UserHandle user) throws PackageManagerException {
5533        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5534        parseFlags |= mDefParseFlags;
5535        PackageParser pp = new PackageParser();
5536        pp.setSeparateProcesses(mSeparateProcesses);
5537        pp.setOnlyCoreApps(mOnlyCore);
5538        pp.setDisplayMetrics(mMetrics);
5539
5540        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5541            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5542        }
5543
5544        final PackageParser.Package pkg;
5545        try {
5546            pkg = pp.parsePackage(scanFile, parseFlags);
5547        } catch (PackageParserException e) {
5548            throw PackageManagerException.from(e);
5549        }
5550
5551        PackageSetting ps = null;
5552        PackageSetting updatedPkg;
5553        // reader
5554        synchronized (mPackages) {
5555            // Look to see if we already know about this package.
5556            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5557            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5558                // This package has been renamed to its original name.  Let's
5559                // use that.
5560                ps = mSettings.peekPackageLPr(oldName);
5561            }
5562            // If there was no original package, see one for the real package name.
5563            if (ps == null) {
5564                ps = mSettings.peekPackageLPr(pkg.packageName);
5565            }
5566            // Check to see if this package could be hiding/updating a system
5567            // package.  Must look for it either under the original or real
5568            // package name depending on our state.
5569            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5570            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5571        }
5572        boolean updatedPkgBetter = false;
5573        // First check if this is a system package that may involve an update
5574        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5575            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5576            // it needs to drop FLAG_PRIVILEGED.
5577            if (locationIsPrivileged(scanFile)) {
5578                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5579            } else {
5580                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5581            }
5582
5583            if (ps != null && !ps.codePath.equals(scanFile)) {
5584                // The path has changed from what was last scanned...  check the
5585                // version of the new path against what we have stored to determine
5586                // what to do.
5587                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5588                if (pkg.mVersionCode <= ps.versionCode) {
5589                    // The system package has been updated and the code path does not match
5590                    // Ignore entry. Skip it.
5591                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5592                            + " ignored: updated version " + ps.versionCode
5593                            + " better than this " + pkg.mVersionCode);
5594                    if (!updatedPkg.codePath.equals(scanFile)) {
5595                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5596                                + ps.name + " changing from " + updatedPkg.codePathString
5597                                + " to " + scanFile);
5598                        updatedPkg.codePath = scanFile;
5599                        updatedPkg.codePathString = scanFile.toString();
5600                        updatedPkg.resourcePath = scanFile;
5601                        updatedPkg.resourcePathString = scanFile.toString();
5602                    }
5603                    updatedPkg.pkg = pkg;
5604                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5605                } else {
5606                    // The current app on the system partition is better than
5607                    // what we have updated to on the data partition; switch
5608                    // back to the system partition version.
5609                    // At this point, its safely assumed that package installation for
5610                    // apps in system partition will go through. If not there won't be a working
5611                    // version of the app
5612                    // writer
5613                    synchronized (mPackages) {
5614                        // Just remove the loaded entries from package lists.
5615                        mPackages.remove(ps.name);
5616                    }
5617
5618                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5619                            + " reverting from " + ps.codePathString
5620                            + ": new version " + pkg.mVersionCode
5621                            + " better than installed " + ps.versionCode);
5622
5623                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5624                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5625                    synchronized (mInstallLock) {
5626                        args.cleanUpResourcesLI();
5627                    }
5628                    synchronized (mPackages) {
5629                        mSettings.enableSystemPackageLPw(ps.name);
5630                    }
5631                    updatedPkgBetter = true;
5632                }
5633            }
5634        }
5635
5636        if (updatedPkg != null) {
5637            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5638            // initially
5639            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5640
5641            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5642            // flag set initially
5643            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5644                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5645            }
5646        }
5647
5648        // Verify certificates against what was last scanned
5649        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5650
5651        /*
5652         * A new system app appeared, but we already had a non-system one of the
5653         * same name installed earlier.
5654         */
5655        boolean shouldHideSystemApp = false;
5656        if (updatedPkg == null && ps != null
5657                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5658            /*
5659             * Check to make sure the signatures match first. If they don't,
5660             * wipe the installed application and its data.
5661             */
5662            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5663                    != PackageManager.SIGNATURE_MATCH) {
5664                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5665                        + " signatures don't match existing userdata copy; removing");
5666                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5667                ps = null;
5668            } else {
5669                /*
5670                 * If the newly-added system app is an older version than the
5671                 * already installed version, hide it. It will be scanned later
5672                 * and re-added like an update.
5673                 */
5674                if (pkg.mVersionCode <= ps.versionCode) {
5675                    shouldHideSystemApp = true;
5676                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5677                            + " but new version " + pkg.mVersionCode + " better than installed "
5678                            + ps.versionCode + "; hiding system");
5679                } else {
5680                    /*
5681                     * The newly found system app is a newer version that the
5682                     * one previously installed. Simply remove the
5683                     * already-installed application and replace it with our own
5684                     * while keeping the application data.
5685                     */
5686                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5687                            + " reverting from " + ps.codePathString + ": new version "
5688                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5689                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5690                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5691                    synchronized (mInstallLock) {
5692                        args.cleanUpResourcesLI();
5693                    }
5694                }
5695            }
5696        }
5697
5698        // The apk is forward locked (not public) if its code and resources
5699        // are kept in different files. (except for app in either system or
5700        // vendor path).
5701        // TODO grab this value from PackageSettings
5702        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5703            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5704                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5705            }
5706        }
5707
5708        // TODO: extend to support forward-locked splits
5709        String resourcePath = null;
5710        String baseResourcePath = null;
5711        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5712            if (ps != null && ps.resourcePathString != null) {
5713                resourcePath = ps.resourcePathString;
5714                baseResourcePath = ps.resourcePathString;
5715            } else {
5716                // Should not happen at all. Just log an error.
5717                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5718            }
5719        } else {
5720            resourcePath = pkg.codePath;
5721            baseResourcePath = pkg.baseCodePath;
5722        }
5723
5724        // Set application objects path explicitly.
5725        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5726        pkg.applicationInfo.setCodePath(pkg.codePath);
5727        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5728        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5729        pkg.applicationInfo.setResourcePath(resourcePath);
5730        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5731        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5732
5733        // Note that we invoke the following method only if we are about to unpack an application
5734        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5735                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5736
5737        /*
5738         * If the system app should be overridden by a previously installed
5739         * data, hide the system app now and let the /data/app scan pick it up
5740         * again.
5741         */
5742        if (shouldHideSystemApp) {
5743            synchronized (mPackages) {
5744                /*
5745                 * We have to grant systems permissions before we hide, because
5746                 * grantPermissions will assume the package update is trying to
5747                 * expand its permissions.
5748                 */
5749                grantPermissionsLPw(pkg, true, pkg.packageName);
5750                mSettings.disableSystemPackageLPw(pkg.packageName);
5751            }
5752        }
5753
5754        return scannedPkg;
5755    }
5756
5757    private static String fixProcessName(String defProcessName,
5758            String processName, int uid) {
5759        if (processName == null) {
5760            return defProcessName;
5761        }
5762        return processName;
5763    }
5764
5765    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5766            throws PackageManagerException {
5767        if (pkgSetting.signatures.mSignatures != null) {
5768            // Already existing package. Make sure signatures match
5769            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5770                    == PackageManager.SIGNATURE_MATCH;
5771            if (!match) {
5772                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5773                        == PackageManager.SIGNATURE_MATCH;
5774            }
5775            if (!match) {
5776                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5777                        == PackageManager.SIGNATURE_MATCH;
5778            }
5779            if (!match) {
5780                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5781                        + pkg.packageName + " signatures do not match the "
5782                        + "previously installed version; ignoring!");
5783            }
5784        }
5785
5786        // Check for shared user signatures
5787        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5788            // Already existing package. Make sure signatures match
5789            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5790                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5791            if (!match) {
5792                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5793                        == PackageManager.SIGNATURE_MATCH;
5794            }
5795            if (!match) {
5796                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5797                        == PackageManager.SIGNATURE_MATCH;
5798            }
5799            if (!match) {
5800                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5801                        "Package " + pkg.packageName
5802                        + " has no signatures that match those in shared user "
5803                        + pkgSetting.sharedUser.name + "; ignoring!");
5804            }
5805        }
5806    }
5807
5808    /**
5809     * Enforces that only the system UID or root's UID can call a method exposed
5810     * via Binder.
5811     *
5812     * @param message used as message if SecurityException is thrown
5813     * @throws SecurityException if the caller is not system or root
5814     */
5815    private static final void enforceSystemOrRoot(String message) {
5816        final int uid = Binder.getCallingUid();
5817        if (uid != Process.SYSTEM_UID && uid != 0) {
5818            throw new SecurityException(message);
5819        }
5820    }
5821
5822    @Override
5823    public void performBootDexOpt() {
5824        enforceSystemOrRoot("Only the system can request dexopt be performed");
5825
5826        // Before everything else, see whether we need to fstrim.
5827        try {
5828            IMountService ms = PackageHelper.getMountService();
5829            if (ms != null) {
5830                final boolean isUpgrade = isUpgrade();
5831                boolean doTrim = isUpgrade;
5832                if (doTrim) {
5833                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5834                } else {
5835                    final long interval = android.provider.Settings.Global.getLong(
5836                            mContext.getContentResolver(),
5837                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5838                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5839                    if (interval > 0) {
5840                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5841                        if (timeSinceLast > interval) {
5842                            doTrim = true;
5843                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5844                                    + "; running immediately");
5845                        }
5846                    }
5847                }
5848                if (doTrim) {
5849                    if (!isFirstBoot()) {
5850                        try {
5851                            ActivityManagerNative.getDefault().showBootMessage(
5852                                    mContext.getResources().getString(
5853                                            R.string.android_upgrading_fstrim), true);
5854                        } catch (RemoteException e) {
5855                        }
5856                    }
5857                    ms.runMaintenance();
5858                }
5859            } else {
5860                Slog.e(TAG, "Mount service unavailable!");
5861            }
5862        } catch (RemoteException e) {
5863            // Can't happen; MountService is local
5864        }
5865
5866        final ArraySet<PackageParser.Package> pkgs;
5867        synchronized (mPackages) {
5868            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5869        }
5870
5871        if (pkgs != null) {
5872            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5873            // in case the device runs out of space.
5874            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5875            // Give priority to core apps.
5876            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5877                PackageParser.Package pkg = it.next();
5878                if (pkg.coreApp) {
5879                    if (DEBUG_DEXOPT) {
5880                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5881                    }
5882                    sortedPkgs.add(pkg);
5883                    it.remove();
5884                }
5885            }
5886            // Give priority to system apps that listen for pre boot complete.
5887            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5888            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5889            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5890                PackageParser.Package pkg = it.next();
5891                if (pkgNames.contains(pkg.packageName)) {
5892                    if (DEBUG_DEXOPT) {
5893                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5894                    }
5895                    sortedPkgs.add(pkg);
5896                    it.remove();
5897                }
5898            }
5899            // Give priority to system apps.
5900            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5901                PackageParser.Package pkg = it.next();
5902                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5903                    if (DEBUG_DEXOPT) {
5904                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5905                    }
5906                    sortedPkgs.add(pkg);
5907                    it.remove();
5908                }
5909            }
5910            // Give priority to updated system apps.
5911            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5912                PackageParser.Package pkg = it.next();
5913                if (pkg.isUpdatedSystemApp()) {
5914                    if (DEBUG_DEXOPT) {
5915                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5916                    }
5917                    sortedPkgs.add(pkg);
5918                    it.remove();
5919                }
5920            }
5921            // Give priority to apps that listen for boot complete.
5922            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5923            pkgNames = getPackageNamesForIntent(intent);
5924            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5925                PackageParser.Package pkg = it.next();
5926                if (pkgNames.contains(pkg.packageName)) {
5927                    if (DEBUG_DEXOPT) {
5928                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5929                    }
5930                    sortedPkgs.add(pkg);
5931                    it.remove();
5932                }
5933            }
5934            // Filter out packages that aren't recently used.
5935            filterRecentlyUsedApps(pkgs);
5936            // Add all remaining apps.
5937            for (PackageParser.Package pkg : pkgs) {
5938                if (DEBUG_DEXOPT) {
5939                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5940                }
5941                sortedPkgs.add(pkg);
5942            }
5943
5944            // If we want to be lazy, filter everything that wasn't recently used.
5945            if (mLazyDexOpt) {
5946                filterRecentlyUsedApps(sortedPkgs);
5947            }
5948
5949            int i = 0;
5950            int total = sortedPkgs.size();
5951            File dataDir = Environment.getDataDirectory();
5952            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5953            if (lowThreshold == 0) {
5954                throw new IllegalStateException("Invalid low memory threshold");
5955            }
5956            for (PackageParser.Package pkg : sortedPkgs) {
5957                long usableSpace = dataDir.getUsableSpace();
5958                if (usableSpace < lowThreshold) {
5959                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5960                    break;
5961                }
5962                performBootDexOpt(pkg, ++i, total);
5963            }
5964        }
5965    }
5966
5967    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5968        // Filter out packages that aren't recently used.
5969        //
5970        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5971        // should do a full dexopt.
5972        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5973            int total = pkgs.size();
5974            int skipped = 0;
5975            long now = System.currentTimeMillis();
5976            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5977                PackageParser.Package pkg = i.next();
5978                long then = pkg.mLastPackageUsageTimeInMills;
5979                if (then + mDexOptLRUThresholdInMills < now) {
5980                    if (DEBUG_DEXOPT) {
5981                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5982                              ((then == 0) ? "never" : new Date(then)));
5983                    }
5984                    i.remove();
5985                    skipped++;
5986                }
5987            }
5988            if (DEBUG_DEXOPT) {
5989                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5990            }
5991        }
5992    }
5993
5994    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5995        List<ResolveInfo> ris = null;
5996        try {
5997            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5998                    intent, null, 0, UserHandle.USER_OWNER);
5999        } catch (RemoteException e) {
6000        }
6001        ArraySet<String> pkgNames = new ArraySet<String>();
6002        if (ris != null) {
6003            for (ResolveInfo ri : ris) {
6004                pkgNames.add(ri.activityInfo.packageName);
6005            }
6006        }
6007        return pkgNames;
6008    }
6009
6010    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6011        if (DEBUG_DEXOPT) {
6012            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6013        }
6014        if (!isFirstBoot()) {
6015            try {
6016                ActivityManagerNative.getDefault().showBootMessage(
6017                        mContext.getResources().getString(R.string.android_upgrading_apk,
6018                                curr, total), true);
6019            } catch (RemoteException e) {
6020            }
6021        }
6022        PackageParser.Package p = pkg;
6023        synchronized (mInstallLock) {
6024            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6025                    false /* force dex */, false /* defer */, true /* include dependencies */);
6026        }
6027    }
6028
6029    @Override
6030    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6031        return performDexOpt(packageName, instructionSet, false);
6032    }
6033
6034    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6035        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6036        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6037        if (!dexopt && !updateUsage) {
6038            // We aren't going to dexopt or update usage, so bail early.
6039            return false;
6040        }
6041        PackageParser.Package p;
6042        final String targetInstructionSet;
6043        synchronized (mPackages) {
6044            p = mPackages.get(packageName);
6045            if (p == null) {
6046                return false;
6047            }
6048            if (updateUsage) {
6049                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6050            }
6051            mPackageUsage.write(false);
6052            if (!dexopt) {
6053                // We aren't going to dexopt, so bail early.
6054                return false;
6055            }
6056
6057            targetInstructionSet = instructionSet != null ? instructionSet :
6058                    getPrimaryInstructionSet(p.applicationInfo);
6059            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6060                return false;
6061            }
6062        }
6063
6064        synchronized (mInstallLock) {
6065            final String[] instructionSets = new String[] { targetInstructionSet };
6066            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6067                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
6068            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6069        }
6070    }
6071
6072    public ArraySet<String> getPackagesThatNeedDexOpt() {
6073        ArraySet<String> pkgs = null;
6074        synchronized (mPackages) {
6075            for (PackageParser.Package p : mPackages.values()) {
6076                if (DEBUG_DEXOPT) {
6077                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6078                }
6079                if (!p.mDexOptPerformed.isEmpty()) {
6080                    continue;
6081                }
6082                if (pkgs == null) {
6083                    pkgs = new ArraySet<String>();
6084                }
6085                pkgs.add(p.packageName);
6086            }
6087        }
6088        return pkgs;
6089    }
6090
6091    public void shutdown() {
6092        mPackageUsage.write(true);
6093    }
6094
6095    @Override
6096    public void forceDexOpt(String packageName) {
6097        enforceSystemOrRoot("forceDexOpt");
6098
6099        PackageParser.Package pkg;
6100        synchronized (mPackages) {
6101            pkg = mPackages.get(packageName);
6102            if (pkg == null) {
6103                throw new IllegalArgumentException("Missing package: " + packageName);
6104            }
6105        }
6106
6107        synchronized (mInstallLock) {
6108            final String[] instructionSets = new String[] {
6109                    getPrimaryInstructionSet(pkg.applicationInfo) };
6110            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6111                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6112            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6113                throw new IllegalStateException("Failed to dexopt: " + res);
6114            }
6115        }
6116    }
6117
6118    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6119        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6120            Slog.w(TAG, "Unable to update from " + oldPkg.name
6121                    + " to " + newPkg.packageName
6122                    + ": old package not in system partition");
6123            return false;
6124        } else if (mPackages.get(oldPkg.name) != null) {
6125            Slog.w(TAG, "Unable to update from " + oldPkg.name
6126                    + " to " + newPkg.packageName
6127                    + ": old package still exists");
6128            return false;
6129        }
6130        return true;
6131    }
6132
6133    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6134        int[] users = sUserManager.getUserIds();
6135        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6136        if (res < 0) {
6137            return res;
6138        }
6139        for (int user : users) {
6140            if (user != 0) {
6141                res = mInstaller.createUserData(volumeUuid, packageName,
6142                        UserHandle.getUid(user, uid), user, seinfo);
6143                if (res < 0) {
6144                    return res;
6145                }
6146            }
6147        }
6148        return res;
6149    }
6150
6151    private int removeDataDirsLI(String volumeUuid, String packageName) {
6152        int[] users = sUserManager.getUserIds();
6153        int res = 0;
6154        for (int user : users) {
6155            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6156            if (resInner < 0) {
6157                res = resInner;
6158            }
6159        }
6160
6161        return res;
6162    }
6163
6164    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6165        int[] users = sUserManager.getUserIds();
6166        int res = 0;
6167        for (int user : users) {
6168            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6169            if (resInner < 0) {
6170                res = resInner;
6171            }
6172        }
6173        return res;
6174    }
6175
6176    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6177            PackageParser.Package changingLib) {
6178        if (file.path != null) {
6179            usesLibraryFiles.add(file.path);
6180            return;
6181        }
6182        PackageParser.Package p = mPackages.get(file.apk);
6183        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6184            // If we are doing this while in the middle of updating a library apk,
6185            // then we need to make sure to use that new apk for determining the
6186            // dependencies here.  (We haven't yet finished committing the new apk
6187            // to the package manager state.)
6188            if (p == null || p.packageName.equals(changingLib.packageName)) {
6189                p = changingLib;
6190            }
6191        }
6192        if (p != null) {
6193            usesLibraryFiles.addAll(p.getAllCodePaths());
6194        }
6195    }
6196
6197    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6198            PackageParser.Package changingLib) throws PackageManagerException {
6199        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6200            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6201            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6202            for (int i=0; i<N; i++) {
6203                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6204                if (file == null) {
6205                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6206                            "Package " + pkg.packageName + " requires unavailable shared library "
6207                            + pkg.usesLibraries.get(i) + "; failing!");
6208                }
6209                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6210            }
6211            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6212            for (int i=0; i<N; i++) {
6213                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6214                if (file == null) {
6215                    Slog.w(TAG, "Package " + pkg.packageName
6216                            + " desires unavailable shared library "
6217                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6218                } else {
6219                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6220                }
6221            }
6222            N = usesLibraryFiles.size();
6223            if (N > 0) {
6224                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6225            } else {
6226                pkg.usesLibraryFiles = null;
6227            }
6228        }
6229    }
6230
6231    private static boolean hasString(List<String> list, List<String> which) {
6232        if (list == null) {
6233            return false;
6234        }
6235        for (int i=list.size()-1; i>=0; i--) {
6236            for (int j=which.size()-1; j>=0; j--) {
6237                if (which.get(j).equals(list.get(i))) {
6238                    return true;
6239                }
6240            }
6241        }
6242        return false;
6243    }
6244
6245    private void updateAllSharedLibrariesLPw() {
6246        for (PackageParser.Package pkg : mPackages.values()) {
6247            try {
6248                updateSharedLibrariesLPw(pkg, null);
6249            } catch (PackageManagerException e) {
6250                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6251            }
6252        }
6253    }
6254
6255    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6256            PackageParser.Package changingPkg) {
6257        ArrayList<PackageParser.Package> res = null;
6258        for (PackageParser.Package pkg : mPackages.values()) {
6259            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6260                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6261                if (res == null) {
6262                    res = new ArrayList<PackageParser.Package>();
6263                }
6264                res.add(pkg);
6265                try {
6266                    updateSharedLibrariesLPw(pkg, changingPkg);
6267                } catch (PackageManagerException e) {
6268                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6269                }
6270            }
6271        }
6272        return res;
6273    }
6274
6275    /**
6276     * Derive the value of the {@code cpuAbiOverride} based on the provided
6277     * value and an optional stored value from the package settings.
6278     */
6279    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6280        String cpuAbiOverride = null;
6281
6282        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6283            cpuAbiOverride = null;
6284        } else if (abiOverride != null) {
6285            cpuAbiOverride = abiOverride;
6286        } else if (settings != null) {
6287            cpuAbiOverride = settings.cpuAbiOverrideString;
6288        }
6289
6290        return cpuAbiOverride;
6291    }
6292
6293    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6294            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6295        boolean success = false;
6296        try {
6297            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6298                    currentTime, user);
6299            success = true;
6300            return res;
6301        } finally {
6302            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6303                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6304            }
6305        }
6306    }
6307
6308    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6309            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6310        final File scanFile = new File(pkg.codePath);
6311        if (pkg.applicationInfo.getCodePath() == null ||
6312                pkg.applicationInfo.getResourcePath() == null) {
6313            // Bail out. The resource and code paths haven't been set.
6314            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6315                    "Code and resource paths haven't been set correctly");
6316        }
6317
6318        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6319            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6320        } else {
6321            // Only allow system apps to be flagged as core apps.
6322            pkg.coreApp = false;
6323        }
6324
6325        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6326            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6327        }
6328
6329        if (mCustomResolverComponentName != null &&
6330                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6331            setUpCustomResolverActivity(pkg);
6332        }
6333
6334        if (pkg.packageName.equals("android")) {
6335            synchronized (mPackages) {
6336                if (mAndroidApplication != null) {
6337                    Slog.w(TAG, "*************************************************");
6338                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6339                    Slog.w(TAG, " file=" + scanFile);
6340                    Slog.w(TAG, "*************************************************");
6341                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6342                            "Core android package being redefined.  Skipping.");
6343                }
6344
6345                // Set up information for our fall-back user intent resolution activity.
6346                mPlatformPackage = pkg;
6347                pkg.mVersionCode = mSdkVersion;
6348                mAndroidApplication = pkg.applicationInfo;
6349
6350                if (!mResolverReplaced) {
6351                    mResolveActivity.applicationInfo = mAndroidApplication;
6352                    mResolveActivity.name = ResolverActivity.class.getName();
6353                    mResolveActivity.packageName = mAndroidApplication.packageName;
6354                    mResolveActivity.processName = "system:ui";
6355                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6356                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6357                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6358                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6359                    mResolveActivity.exported = true;
6360                    mResolveActivity.enabled = true;
6361                    mResolveInfo.activityInfo = mResolveActivity;
6362                    mResolveInfo.priority = 0;
6363                    mResolveInfo.preferredOrder = 0;
6364                    mResolveInfo.match = 0;
6365                    mResolveComponentName = new ComponentName(
6366                            mAndroidApplication.packageName, mResolveActivity.name);
6367                }
6368            }
6369        }
6370
6371        if (DEBUG_PACKAGE_SCANNING) {
6372            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6373                Log.d(TAG, "Scanning package " + pkg.packageName);
6374        }
6375
6376        if (mPackages.containsKey(pkg.packageName)
6377                || mSharedLibraries.containsKey(pkg.packageName)) {
6378            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6379                    "Application package " + pkg.packageName
6380                    + " already installed.  Skipping duplicate.");
6381        }
6382
6383        // If we're only installing presumed-existing packages, require that the
6384        // scanned APK is both already known and at the path previously established
6385        // for it.  Previously unknown packages we pick up normally, but if we have an
6386        // a priori expectation about this package's install presence, enforce it.
6387        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6388            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6389            if (known != null) {
6390                if (DEBUG_PACKAGE_SCANNING) {
6391                    Log.d(TAG, "Examining " + pkg.codePath
6392                            + " and requiring known paths " + known.codePathString
6393                            + " & " + known.resourcePathString);
6394                }
6395                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6396                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6397                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6398                            "Application package " + pkg.packageName
6399                            + " found at " + pkg.applicationInfo.getCodePath()
6400                            + " but expected at " + known.codePathString + "; ignoring.");
6401                }
6402            }
6403        }
6404
6405        // Initialize package source and resource directories
6406        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6407        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6408
6409        SharedUserSetting suid = null;
6410        PackageSetting pkgSetting = null;
6411
6412        if (!isSystemApp(pkg)) {
6413            // Only system apps can use these features.
6414            pkg.mOriginalPackages = null;
6415            pkg.mRealPackage = null;
6416            pkg.mAdoptPermissions = null;
6417        }
6418
6419        // writer
6420        synchronized (mPackages) {
6421            if (pkg.mSharedUserId != null) {
6422                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6423                if (suid == null) {
6424                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6425                            "Creating application package " + pkg.packageName
6426                            + " for shared user failed");
6427                }
6428                if (DEBUG_PACKAGE_SCANNING) {
6429                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6430                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6431                                + "): packages=" + suid.packages);
6432                }
6433            }
6434
6435            // Check if we are renaming from an original package name.
6436            PackageSetting origPackage = null;
6437            String realName = null;
6438            if (pkg.mOriginalPackages != null) {
6439                // This package may need to be renamed to a previously
6440                // installed name.  Let's check on that...
6441                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6442                if (pkg.mOriginalPackages.contains(renamed)) {
6443                    // This package had originally been installed as the
6444                    // original name, and we have already taken care of
6445                    // transitioning to the new one.  Just update the new
6446                    // one to continue using the old name.
6447                    realName = pkg.mRealPackage;
6448                    if (!pkg.packageName.equals(renamed)) {
6449                        // Callers into this function may have already taken
6450                        // care of renaming the package; only do it here if
6451                        // it is not already done.
6452                        pkg.setPackageName(renamed);
6453                    }
6454
6455                } else {
6456                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6457                        if ((origPackage = mSettings.peekPackageLPr(
6458                                pkg.mOriginalPackages.get(i))) != null) {
6459                            // We do have the package already installed under its
6460                            // original name...  should we use it?
6461                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6462                                // New package is not compatible with original.
6463                                origPackage = null;
6464                                continue;
6465                            } else if (origPackage.sharedUser != null) {
6466                                // Make sure uid is compatible between packages.
6467                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6468                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6469                                            + " to " + pkg.packageName + ": old uid "
6470                                            + origPackage.sharedUser.name
6471                                            + " differs from " + pkg.mSharedUserId);
6472                                    origPackage = null;
6473                                    continue;
6474                                }
6475                            } else {
6476                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6477                                        + pkg.packageName + " to old name " + origPackage.name);
6478                            }
6479                            break;
6480                        }
6481                    }
6482                }
6483            }
6484
6485            if (mTransferedPackages.contains(pkg.packageName)) {
6486                Slog.w(TAG, "Package " + pkg.packageName
6487                        + " was transferred to another, but its .apk remains");
6488            }
6489
6490            // Just create the setting, don't add it yet. For already existing packages
6491            // the PkgSetting exists already and doesn't have to be created.
6492            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6493                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6494                    pkg.applicationInfo.primaryCpuAbi,
6495                    pkg.applicationInfo.secondaryCpuAbi,
6496                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6497                    user, false);
6498            if (pkgSetting == null) {
6499                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6500                        "Creating application package " + pkg.packageName + " failed");
6501            }
6502
6503            if (pkgSetting.origPackage != null) {
6504                // If we are first transitioning from an original package,
6505                // fix up the new package's name now.  We need to do this after
6506                // looking up the package under its new name, so getPackageLP
6507                // can take care of fiddling things correctly.
6508                pkg.setPackageName(origPackage.name);
6509
6510                // File a report about this.
6511                String msg = "New package " + pkgSetting.realName
6512                        + " renamed to replace old package " + pkgSetting.name;
6513                reportSettingsProblem(Log.WARN, msg);
6514
6515                // Make a note of it.
6516                mTransferedPackages.add(origPackage.name);
6517
6518                // No longer need to retain this.
6519                pkgSetting.origPackage = null;
6520            }
6521
6522            if (realName != null) {
6523                // Make a note of it.
6524                mTransferedPackages.add(pkg.packageName);
6525            }
6526
6527            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6528                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6529            }
6530
6531            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6532                // Check all shared libraries and map to their actual file path.
6533                // We only do this here for apps not on a system dir, because those
6534                // are the only ones that can fail an install due to this.  We
6535                // will take care of the system apps by updating all of their
6536                // library paths after the scan is done.
6537                updateSharedLibrariesLPw(pkg, null);
6538            }
6539
6540            if (mFoundPolicyFile) {
6541                SELinuxMMAC.assignSeinfoValue(pkg);
6542            }
6543
6544            pkg.applicationInfo.uid = pkgSetting.appId;
6545            pkg.mExtras = pkgSetting;
6546            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6547                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6548                    // We just determined the app is signed correctly, so bring
6549                    // over the latest parsed certs.
6550                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6551                } else {
6552                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6553                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6554                                "Package " + pkg.packageName + " upgrade keys do not match the "
6555                                + "previously installed version");
6556                    } else {
6557                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6558                        String msg = "System package " + pkg.packageName
6559                            + " signature changed; retaining data.";
6560                        reportSettingsProblem(Log.WARN, msg);
6561                    }
6562                }
6563            } else {
6564                try {
6565                    verifySignaturesLP(pkgSetting, pkg);
6566                    // We just determined the app is signed correctly, so bring
6567                    // over the latest parsed certs.
6568                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6569                } catch (PackageManagerException e) {
6570                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6571                        throw e;
6572                    }
6573                    // The signature has changed, but this package is in the system
6574                    // image...  let's recover!
6575                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6576                    // However...  if this package is part of a shared user, but it
6577                    // doesn't match the signature of the shared user, let's fail.
6578                    // What this means is that you can't change the signatures
6579                    // associated with an overall shared user, which doesn't seem all
6580                    // that unreasonable.
6581                    if (pkgSetting.sharedUser != null) {
6582                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6583                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6584                            throw new PackageManagerException(
6585                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6586                                            "Signature mismatch for shared user : "
6587                                            + pkgSetting.sharedUser);
6588                        }
6589                    }
6590                    // File a report about this.
6591                    String msg = "System package " + pkg.packageName
6592                        + " signature changed; retaining data.";
6593                    reportSettingsProblem(Log.WARN, msg);
6594                }
6595            }
6596            // Verify that this new package doesn't have any content providers
6597            // that conflict with existing packages.  Only do this if the
6598            // package isn't already installed, since we don't want to break
6599            // things that are installed.
6600            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6601                final int N = pkg.providers.size();
6602                int i;
6603                for (i=0; i<N; i++) {
6604                    PackageParser.Provider p = pkg.providers.get(i);
6605                    if (p.info.authority != null) {
6606                        String names[] = p.info.authority.split(";");
6607                        for (int j = 0; j < names.length; j++) {
6608                            if (mProvidersByAuthority.containsKey(names[j])) {
6609                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6610                                final String otherPackageName =
6611                                        ((other != null && other.getComponentName() != null) ?
6612                                                other.getComponentName().getPackageName() : "?");
6613                                throw new PackageManagerException(
6614                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6615                                                "Can't install because provider name " + names[j]
6616                                                + " (in package " + pkg.applicationInfo.packageName
6617                                                + ") is already used by " + otherPackageName);
6618                            }
6619                        }
6620                    }
6621                }
6622            }
6623
6624            if (pkg.mAdoptPermissions != null) {
6625                // This package wants to adopt ownership of permissions from
6626                // another package.
6627                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6628                    final String origName = pkg.mAdoptPermissions.get(i);
6629                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6630                    if (orig != null) {
6631                        if (verifyPackageUpdateLPr(orig, pkg)) {
6632                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6633                                    + pkg.packageName);
6634                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6635                        }
6636                    }
6637                }
6638            }
6639        }
6640
6641        final String pkgName = pkg.packageName;
6642
6643        final long scanFileTime = scanFile.lastModified();
6644        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6645        pkg.applicationInfo.processName = fixProcessName(
6646                pkg.applicationInfo.packageName,
6647                pkg.applicationInfo.processName,
6648                pkg.applicationInfo.uid);
6649
6650        File dataPath;
6651        if (mPlatformPackage == pkg) {
6652            // The system package is special.
6653            dataPath = new File(Environment.getDataDirectory(), "system");
6654
6655            pkg.applicationInfo.dataDir = dataPath.getPath();
6656
6657        } else {
6658            // This is a normal package, need to make its data directory.
6659            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6660                    UserHandle.USER_OWNER, pkg.packageName);
6661
6662            boolean uidError = false;
6663            if (dataPath.exists()) {
6664                int currentUid = 0;
6665                try {
6666                    StructStat stat = Os.stat(dataPath.getPath());
6667                    currentUid = stat.st_uid;
6668                } catch (ErrnoException e) {
6669                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6670                }
6671
6672                // If we have mismatched owners for the data path, we have a problem.
6673                if (currentUid != pkg.applicationInfo.uid) {
6674                    boolean recovered = false;
6675                    if (currentUid == 0) {
6676                        // The directory somehow became owned by root.  Wow.
6677                        // This is probably because the system was stopped while
6678                        // installd was in the middle of messing with its libs
6679                        // directory.  Ask installd to fix that.
6680                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6681                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6682                        if (ret >= 0) {
6683                            recovered = true;
6684                            String msg = "Package " + pkg.packageName
6685                                    + " unexpectedly changed to uid 0; recovered to " +
6686                                    + pkg.applicationInfo.uid;
6687                            reportSettingsProblem(Log.WARN, msg);
6688                        }
6689                    }
6690                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6691                            || (scanFlags&SCAN_BOOTING) != 0)) {
6692                        // If this is a system app, we can at least delete its
6693                        // current data so the application will still work.
6694                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6695                        if (ret >= 0) {
6696                            // TODO: Kill the processes first
6697                            // Old data gone!
6698                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6699                                    ? "System package " : "Third party package ";
6700                            String msg = prefix + pkg.packageName
6701                                    + " has changed from uid: "
6702                                    + currentUid + " to "
6703                                    + pkg.applicationInfo.uid + "; old data erased";
6704                            reportSettingsProblem(Log.WARN, msg);
6705                            recovered = true;
6706
6707                            // And now re-install the app.
6708                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6709                                    pkg.applicationInfo.seinfo);
6710                            if (ret == -1) {
6711                                // Ack should not happen!
6712                                msg = prefix + pkg.packageName
6713                                        + " could not have data directory re-created after delete.";
6714                                reportSettingsProblem(Log.WARN, msg);
6715                                throw new PackageManagerException(
6716                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6717                            }
6718                        }
6719                        if (!recovered) {
6720                            mHasSystemUidErrors = true;
6721                        }
6722                    } else if (!recovered) {
6723                        // If we allow this install to proceed, we will be broken.
6724                        // Abort, abort!
6725                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6726                                "scanPackageLI");
6727                    }
6728                    if (!recovered) {
6729                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6730                            + pkg.applicationInfo.uid + "/fs_"
6731                            + currentUid;
6732                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6733                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6734                        String msg = "Package " + pkg.packageName
6735                                + " has mismatched uid: "
6736                                + currentUid + " on disk, "
6737                                + pkg.applicationInfo.uid + " in settings";
6738                        // writer
6739                        synchronized (mPackages) {
6740                            mSettings.mReadMessages.append(msg);
6741                            mSettings.mReadMessages.append('\n');
6742                            uidError = true;
6743                            if (!pkgSetting.uidError) {
6744                                reportSettingsProblem(Log.ERROR, msg);
6745                            }
6746                        }
6747                    }
6748                }
6749                pkg.applicationInfo.dataDir = dataPath.getPath();
6750                if (mShouldRestoreconData) {
6751                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6752                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6753                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6754                }
6755            } else {
6756                if (DEBUG_PACKAGE_SCANNING) {
6757                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6758                        Log.v(TAG, "Want this data dir: " + dataPath);
6759                }
6760                //invoke installer to do the actual installation
6761                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6762                        pkg.applicationInfo.seinfo);
6763                if (ret < 0) {
6764                    // Error from installer
6765                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6766                            "Unable to create data dirs [errorCode=" + ret + "]");
6767                }
6768
6769                if (dataPath.exists()) {
6770                    pkg.applicationInfo.dataDir = dataPath.getPath();
6771                } else {
6772                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6773                    pkg.applicationInfo.dataDir = null;
6774                }
6775            }
6776
6777            pkgSetting.uidError = uidError;
6778        }
6779
6780        final String path = scanFile.getPath();
6781        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6782
6783        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6784            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6785
6786            // Some system apps still use directory structure for native libraries
6787            // in which case we might end up not detecting abi solely based on apk
6788            // structure. Try to detect abi based on directory structure.
6789            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6790                    pkg.applicationInfo.primaryCpuAbi == null) {
6791                setBundledAppAbisAndRoots(pkg, pkgSetting);
6792                setNativeLibraryPaths(pkg);
6793            }
6794
6795        } else {
6796            if ((scanFlags & SCAN_MOVE) != 0) {
6797                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6798                // but we already have this packages package info in the PackageSetting. We just
6799                // use that and derive the native library path based on the new codepath.
6800                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6801                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6802            }
6803
6804            // Set native library paths again. For moves, the path will be updated based on the
6805            // ABIs we've determined above. For non-moves, the path will be updated based on the
6806            // ABIs we determined during compilation, but the path will depend on the final
6807            // package path (after the rename away from the stage path).
6808            setNativeLibraryPaths(pkg);
6809        }
6810
6811        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6812        final int[] userIds = sUserManager.getUserIds();
6813        synchronized (mInstallLock) {
6814            // Make sure all user data directories are ready to roll; we're okay
6815            // if they already exist
6816            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6817                for (int userId : userIds) {
6818                    if (userId != 0) {
6819                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6820                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6821                                pkg.applicationInfo.seinfo);
6822                    }
6823                }
6824            }
6825
6826            // Create a native library symlink only if we have native libraries
6827            // and if the native libraries are 32 bit libraries. We do not provide
6828            // this symlink for 64 bit libraries.
6829            if (pkg.applicationInfo.primaryCpuAbi != null &&
6830                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6831                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6832                for (int userId : userIds) {
6833                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6834                            nativeLibPath, userId) < 0) {
6835                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6836                                "Failed linking native library dir (user=" + userId + ")");
6837                    }
6838                }
6839            }
6840        }
6841
6842        // This is a special case for the "system" package, where the ABI is
6843        // dictated by the zygote configuration (and init.rc). We should keep track
6844        // of this ABI so that we can deal with "normal" applications that run under
6845        // the same UID correctly.
6846        if (mPlatformPackage == pkg) {
6847            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6848                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6849        }
6850
6851        // If there's a mismatch between the abi-override in the package setting
6852        // and the abiOverride specified for the install. Warn about this because we
6853        // would've already compiled the app without taking the package setting into
6854        // account.
6855        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6856            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6857                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6858                        " for package: " + pkg.packageName);
6859            }
6860        }
6861
6862        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6863        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6864        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6865
6866        // Copy the derived override back to the parsed package, so that we can
6867        // update the package settings accordingly.
6868        pkg.cpuAbiOverride = cpuAbiOverride;
6869
6870        if (DEBUG_ABI_SELECTION) {
6871            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6872                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6873                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6874        }
6875
6876        // Push the derived path down into PackageSettings so we know what to
6877        // clean up at uninstall time.
6878        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6879
6880        if (DEBUG_ABI_SELECTION) {
6881            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6882                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6883                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6884        }
6885
6886        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6887            // We don't do this here during boot because we can do it all
6888            // at once after scanning all existing packages.
6889            //
6890            // We also do this *before* we perform dexopt on this package, so that
6891            // we can avoid redundant dexopts, and also to make sure we've got the
6892            // code and package path correct.
6893            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6894                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6895        }
6896
6897        if ((scanFlags & SCAN_NO_DEX) == 0) {
6898            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6899                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6900            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6901                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6902            }
6903        }
6904        if (mFactoryTest && pkg.requestedPermissions.contains(
6905                android.Manifest.permission.FACTORY_TEST)) {
6906            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6907        }
6908
6909        ArrayList<PackageParser.Package> clientLibPkgs = null;
6910
6911        // writer
6912        synchronized (mPackages) {
6913            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6914                // Only system apps can add new shared libraries.
6915                if (pkg.libraryNames != null) {
6916                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6917                        String name = pkg.libraryNames.get(i);
6918                        boolean allowed = false;
6919                        if (pkg.isUpdatedSystemApp()) {
6920                            // New library entries can only be added through the
6921                            // system image.  This is important to get rid of a lot
6922                            // of nasty edge cases: for example if we allowed a non-
6923                            // system update of the app to add a library, then uninstalling
6924                            // the update would make the library go away, and assumptions
6925                            // we made such as through app install filtering would now
6926                            // have allowed apps on the device which aren't compatible
6927                            // with it.  Better to just have the restriction here, be
6928                            // conservative, and create many fewer cases that can negatively
6929                            // impact the user experience.
6930                            final PackageSetting sysPs = mSettings
6931                                    .getDisabledSystemPkgLPr(pkg.packageName);
6932                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6933                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6934                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6935                                        allowed = true;
6936                                        allowed = true;
6937                                        break;
6938                                    }
6939                                }
6940                            }
6941                        } else {
6942                            allowed = true;
6943                        }
6944                        if (allowed) {
6945                            if (!mSharedLibraries.containsKey(name)) {
6946                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6947                            } else if (!name.equals(pkg.packageName)) {
6948                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6949                                        + name + " already exists; skipping");
6950                            }
6951                        } else {
6952                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6953                                    + name + " that is not declared on system image; skipping");
6954                        }
6955                    }
6956                    if ((scanFlags&SCAN_BOOTING) == 0) {
6957                        // If we are not booting, we need to update any applications
6958                        // that are clients of our shared library.  If we are booting,
6959                        // this will all be done once the scan is complete.
6960                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6961                    }
6962                }
6963            }
6964        }
6965
6966        // We also need to dexopt any apps that are dependent on this library.  Note that
6967        // if these fail, we should abort the install since installing the library will
6968        // result in some apps being broken.
6969        if (clientLibPkgs != null) {
6970            if ((scanFlags & SCAN_NO_DEX) == 0) {
6971                for (int i = 0; i < clientLibPkgs.size(); i++) {
6972                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6973                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6974                            null /* instruction sets */, forceDex,
6975                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6976                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6977                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6978                                "scanPackageLI failed to dexopt clientLibPkgs");
6979                    }
6980                }
6981            }
6982        }
6983
6984        // Also need to kill any apps that are dependent on the library.
6985        if (clientLibPkgs != null) {
6986            for (int i=0; i<clientLibPkgs.size(); i++) {
6987                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6988                killApplication(clientPkg.applicationInfo.packageName,
6989                        clientPkg.applicationInfo.uid, "update lib");
6990            }
6991        }
6992
6993        // Make sure we're not adding any bogus keyset info
6994        KeySetManagerService ksms = mSettings.mKeySetManagerService;
6995        ksms.assertScannedPackageValid(pkg);
6996
6997        // writer
6998        synchronized (mPackages) {
6999            // We don't expect installation to fail beyond this point
7000
7001            // Add the new setting to mSettings
7002            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7003            // Add the new setting to mPackages
7004            mPackages.put(pkg.applicationInfo.packageName, pkg);
7005            // Make sure we don't accidentally delete its data.
7006            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7007            while (iter.hasNext()) {
7008                PackageCleanItem item = iter.next();
7009                if (pkgName.equals(item.packageName)) {
7010                    iter.remove();
7011                }
7012            }
7013
7014            // Take care of first install / last update times.
7015            if (currentTime != 0) {
7016                if (pkgSetting.firstInstallTime == 0) {
7017                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7018                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7019                    pkgSetting.lastUpdateTime = currentTime;
7020                }
7021            } else if (pkgSetting.firstInstallTime == 0) {
7022                // We need *something*.  Take time time stamp of the file.
7023                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7024            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7025                if (scanFileTime != pkgSetting.timeStamp) {
7026                    // A package on the system image has changed; consider this
7027                    // to be an update.
7028                    pkgSetting.lastUpdateTime = scanFileTime;
7029                }
7030            }
7031
7032            // Add the package's KeySets to the global KeySetManagerService
7033            ksms.addScannedPackageLPw(pkg);
7034
7035            int N = pkg.providers.size();
7036            StringBuilder r = null;
7037            int i;
7038            for (i=0; i<N; i++) {
7039                PackageParser.Provider p = pkg.providers.get(i);
7040                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7041                        p.info.processName, pkg.applicationInfo.uid);
7042                mProviders.addProvider(p);
7043                p.syncable = p.info.isSyncable;
7044                if (p.info.authority != null) {
7045                    String names[] = p.info.authority.split(";");
7046                    p.info.authority = null;
7047                    for (int j = 0; j < names.length; j++) {
7048                        if (j == 1 && p.syncable) {
7049                            // We only want the first authority for a provider to possibly be
7050                            // syncable, so if we already added this provider using a different
7051                            // authority clear the syncable flag. We copy the provider before
7052                            // changing it because the mProviders object contains a reference
7053                            // to a provider that we don't want to change.
7054                            // Only do this for the second authority since the resulting provider
7055                            // object can be the same for all future authorities for this provider.
7056                            p = new PackageParser.Provider(p);
7057                            p.syncable = false;
7058                        }
7059                        if (!mProvidersByAuthority.containsKey(names[j])) {
7060                            mProvidersByAuthority.put(names[j], p);
7061                            if (p.info.authority == null) {
7062                                p.info.authority = names[j];
7063                            } else {
7064                                p.info.authority = p.info.authority + ";" + names[j];
7065                            }
7066                            if (DEBUG_PACKAGE_SCANNING) {
7067                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7068                                    Log.d(TAG, "Registered content provider: " + names[j]
7069                                            + ", className = " + p.info.name + ", isSyncable = "
7070                                            + p.info.isSyncable);
7071                            }
7072                        } else {
7073                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7074                            Slog.w(TAG, "Skipping provider name " + names[j] +
7075                                    " (in package " + pkg.applicationInfo.packageName +
7076                                    "): name already used by "
7077                                    + ((other != null && other.getComponentName() != null)
7078                                            ? other.getComponentName().getPackageName() : "?"));
7079                        }
7080                    }
7081                }
7082                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7083                    if (r == null) {
7084                        r = new StringBuilder(256);
7085                    } else {
7086                        r.append(' ');
7087                    }
7088                    r.append(p.info.name);
7089                }
7090            }
7091            if (r != null) {
7092                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7093            }
7094
7095            N = pkg.services.size();
7096            r = null;
7097            for (i=0; i<N; i++) {
7098                PackageParser.Service s = pkg.services.get(i);
7099                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7100                        s.info.processName, pkg.applicationInfo.uid);
7101                mServices.addService(s);
7102                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7103                    if (r == null) {
7104                        r = new StringBuilder(256);
7105                    } else {
7106                        r.append(' ');
7107                    }
7108                    r.append(s.info.name);
7109                }
7110            }
7111            if (r != null) {
7112                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7113            }
7114
7115            N = pkg.receivers.size();
7116            r = null;
7117            for (i=0; i<N; i++) {
7118                PackageParser.Activity a = pkg.receivers.get(i);
7119                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7120                        a.info.processName, pkg.applicationInfo.uid);
7121                mReceivers.addActivity(a, "receiver");
7122                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7123                    if (r == null) {
7124                        r = new StringBuilder(256);
7125                    } else {
7126                        r.append(' ');
7127                    }
7128                    r.append(a.info.name);
7129                }
7130            }
7131            if (r != null) {
7132                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7133            }
7134
7135            N = pkg.activities.size();
7136            r = null;
7137            for (i=0; i<N; i++) {
7138                PackageParser.Activity a = pkg.activities.get(i);
7139                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7140                        a.info.processName, pkg.applicationInfo.uid);
7141                mActivities.addActivity(a, "activity");
7142                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7143                    if (r == null) {
7144                        r = new StringBuilder(256);
7145                    } else {
7146                        r.append(' ');
7147                    }
7148                    r.append(a.info.name);
7149                }
7150            }
7151            if (r != null) {
7152                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7153            }
7154
7155            N = pkg.permissionGroups.size();
7156            r = null;
7157            for (i=0; i<N; i++) {
7158                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7159                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7160                if (cur == null) {
7161                    mPermissionGroups.put(pg.info.name, pg);
7162                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7163                        if (r == null) {
7164                            r = new StringBuilder(256);
7165                        } else {
7166                            r.append(' ');
7167                        }
7168                        r.append(pg.info.name);
7169                    }
7170                } else {
7171                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7172                            + pg.info.packageName + " ignored: original from "
7173                            + cur.info.packageName);
7174                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7175                        if (r == null) {
7176                            r = new StringBuilder(256);
7177                        } else {
7178                            r.append(' ');
7179                        }
7180                        r.append("DUP:");
7181                        r.append(pg.info.name);
7182                    }
7183                }
7184            }
7185            if (r != null) {
7186                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7187            }
7188
7189            N = pkg.permissions.size();
7190            r = null;
7191            for (i=0; i<N; i++) {
7192                PackageParser.Permission p = pkg.permissions.get(i);
7193
7194                // Now that permission groups have a special meaning, we ignore permission
7195                // groups for legacy apps to prevent unexpected behavior. In particular,
7196                // permissions for one app being granted to someone just becuase they happen
7197                // to be in a group defined by another app (before this had no implications).
7198                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7199                    p.group = mPermissionGroups.get(p.info.group);
7200                    // Warn for a permission in an unknown group.
7201                    if (p.info.group != null && p.group == null) {
7202                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7203                                + p.info.packageName + " in an unknown group " + p.info.group);
7204                    }
7205                }
7206
7207                ArrayMap<String, BasePermission> permissionMap =
7208                        p.tree ? mSettings.mPermissionTrees
7209                                : mSettings.mPermissions;
7210                BasePermission bp = permissionMap.get(p.info.name);
7211
7212                // Allow system apps to redefine non-system permissions
7213                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7214                    final boolean currentOwnerIsSystem = (bp.perm != null
7215                            && isSystemApp(bp.perm.owner));
7216                    if (isSystemApp(p.owner)) {
7217                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7218                            // It's a built-in permission and no owner, take ownership now
7219                            bp.packageSetting = pkgSetting;
7220                            bp.perm = p;
7221                            bp.uid = pkg.applicationInfo.uid;
7222                            bp.sourcePackage = p.info.packageName;
7223                        } else if (!currentOwnerIsSystem) {
7224                            String msg = "New decl " + p.owner + " of permission  "
7225                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7226                            reportSettingsProblem(Log.WARN, msg);
7227                            bp = null;
7228                        }
7229                    }
7230                }
7231
7232                if (bp == null) {
7233                    bp = new BasePermission(p.info.name, p.info.packageName,
7234                            BasePermission.TYPE_NORMAL);
7235                    permissionMap.put(p.info.name, bp);
7236                }
7237
7238                if (bp.perm == null) {
7239                    if (bp.sourcePackage == null
7240                            || bp.sourcePackage.equals(p.info.packageName)) {
7241                        BasePermission tree = findPermissionTreeLP(p.info.name);
7242                        if (tree == null
7243                                || tree.sourcePackage.equals(p.info.packageName)) {
7244                            bp.packageSetting = pkgSetting;
7245                            bp.perm = p;
7246                            bp.uid = pkg.applicationInfo.uid;
7247                            bp.sourcePackage = p.info.packageName;
7248                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7249                                if (r == null) {
7250                                    r = new StringBuilder(256);
7251                                } else {
7252                                    r.append(' ');
7253                                }
7254                                r.append(p.info.name);
7255                            }
7256                        } else {
7257                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7258                                    + p.info.packageName + " ignored: base tree "
7259                                    + tree.name + " is from package "
7260                                    + tree.sourcePackage);
7261                        }
7262                    } else {
7263                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7264                                + p.info.packageName + " ignored: original from "
7265                                + bp.sourcePackage);
7266                    }
7267                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7268                    if (r == null) {
7269                        r = new StringBuilder(256);
7270                    } else {
7271                        r.append(' ');
7272                    }
7273                    r.append("DUP:");
7274                    r.append(p.info.name);
7275                }
7276                if (bp.perm == p) {
7277                    bp.protectionLevel = p.info.protectionLevel;
7278                }
7279            }
7280
7281            if (r != null) {
7282                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7283            }
7284
7285            N = pkg.instrumentation.size();
7286            r = null;
7287            for (i=0; i<N; i++) {
7288                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7289                a.info.packageName = pkg.applicationInfo.packageName;
7290                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7291                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7292                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7293                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7294                a.info.dataDir = pkg.applicationInfo.dataDir;
7295
7296                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7297                // need other information about the application, like the ABI and what not ?
7298                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7299                mInstrumentation.put(a.getComponentName(), a);
7300                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7301                    if (r == null) {
7302                        r = new StringBuilder(256);
7303                    } else {
7304                        r.append(' ');
7305                    }
7306                    r.append(a.info.name);
7307                }
7308            }
7309            if (r != null) {
7310                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7311            }
7312
7313            if (pkg.protectedBroadcasts != null) {
7314                N = pkg.protectedBroadcasts.size();
7315                for (i=0; i<N; i++) {
7316                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7317                }
7318            }
7319
7320            pkgSetting.setTimeStamp(scanFileTime);
7321
7322            // Create idmap files for pairs of (packages, overlay packages).
7323            // Note: "android", ie framework-res.apk, is handled by native layers.
7324            if (pkg.mOverlayTarget != null) {
7325                // This is an overlay package.
7326                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7327                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7328                        mOverlays.put(pkg.mOverlayTarget,
7329                                new ArrayMap<String, PackageParser.Package>());
7330                    }
7331                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7332                    map.put(pkg.packageName, pkg);
7333                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7334                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7335                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7336                                "scanPackageLI failed to createIdmap");
7337                    }
7338                }
7339            } else if (mOverlays.containsKey(pkg.packageName) &&
7340                    !pkg.packageName.equals("android")) {
7341                // This is a regular package, with one or more known overlay packages.
7342                createIdmapsForPackageLI(pkg);
7343            }
7344        }
7345
7346        return pkg;
7347    }
7348
7349    /**
7350     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7351     * is derived purely on the basis of the contents of {@code scanFile} and
7352     * {@code cpuAbiOverride}.
7353     *
7354     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7355     */
7356    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7357                                 String cpuAbiOverride, boolean extractLibs)
7358            throws PackageManagerException {
7359        // TODO: We can probably be smarter about this stuff. For installed apps,
7360        // we can calculate this information at install time once and for all. For
7361        // system apps, we can probably assume that this information doesn't change
7362        // after the first boot scan. As things stand, we do lots of unnecessary work.
7363
7364        // Give ourselves some initial paths; we'll come back for another
7365        // pass once we've determined ABI below.
7366        setNativeLibraryPaths(pkg);
7367
7368        // We would never need to extract libs for forward-locked and external packages,
7369        // since the container service will do it for us. We shouldn't attempt to
7370        // extract libs from system app when it was not updated.
7371        if (pkg.isForwardLocked() || isExternal(pkg) ||
7372            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7373            extractLibs = false;
7374        }
7375
7376        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7377        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7378
7379        NativeLibraryHelper.Handle handle = null;
7380        try {
7381            handle = NativeLibraryHelper.Handle.create(scanFile);
7382            // TODO(multiArch): This can be null for apps that didn't go through the
7383            // usual installation process. We can calculate it again, like we
7384            // do during install time.
7385            //
7386            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7387            // unnecessary.
7388            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7389
7390            // Null out the abis so that they can be recalculated.
7391            pkg.applicationInfo.primaryCpuAbi = null;
7392            pkg.applicationInfo.secondaryCpuAbi = null;
7393            if (isMultiArch(pkg.applicationInfo)) {
7394                // Warn if we've set an abiOverride for multi-lib packages..
7395                // By definition, we need to copy both 32 and 64 bit libraries for
7396                // such packages.
7397                if (pkg.cpuAbiOverride != null
7398                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7399                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7400                }
7401
7402                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7403                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7404                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7405                    if (extractLibs) {
7406                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7407                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7408                                useIsaSpecificSubdirs);
7409                    } else {
7410                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7411                    }
7412                }
7413
7414                maybeThrowExceptionForMultiArchCopy(
7415                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7416
7417                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7418                    if (extractLibs) {
7419                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7420                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7421                                useIsaSpecificSubdirs);
7422                    } else {
7423                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7424                    }
7425                }
7426
7427                maybeThrowExceptionForMultiArchCopy(
7428                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7429
7430                if (abi64 >= 0) {
7431                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7432                }
7433
7434                if (abi32 >= 0) {
7435                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7436                    if (abi64 >= 0) {
7437                        pkg.applicationInfo.secondaryCpuAbi = abi;
7438                    } else {
7439                        pkg.applicationInfo.primaryCpuAbi = abi;
7440                    }
7441                }
7442            } else {
7443                String[] abiList = (cpuAbiOverride != null) ?
7444                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7445
7446                // Enable gross and lame hacks for apps that are built with old
7447                // SDK tools. We must scan their APKs for renderscript bitcode and
7448                // not launch them if it's present. Don't bother checking on devices
7449                // that don't have 64 bit support.
7450                boolean needsRenderScriptOverride = false;
7451                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7452                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7453                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7454                    needsRenderScriptOverride = true;
7455                }
7456
7457                final int copyRet;
7458                if (extractLibs) {
7459                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7460                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7461                } else {
7462                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7463                }
7464
7465                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7466                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7467                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7468                }
7469
7470                if (copyRet >= 0) {
7471                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7472                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7473                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7474                } else if (needsRenderScriptOverride) {
7475                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7476                }
7477            }
7478        } catch (IOException ioe) {
7479            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7480        } finally {
7481            IoUtils.closeQuietly(handle);
7482        }
7483
7484        // Now that we've calculated the ABIs and determined if it's an internal app,
7485        // we will go ahead and populate the nativeLibraryPath.
7486        setNativeLibraryPaths(pkg);
7487    }
7488
7489    /**
7490     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7491     * i.e, so that all packages can be run inside a single process if required.
7492     *
7493     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7494     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7495     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7496     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7497     * updating a package that belongs to a shared user.
7498     *
7499     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7500     * adds unnecessary complexity.
7501     */
7502    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7503            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7504        String requiredInstructionSet = null;
7505        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7506            requiredInstructionSet = VMRuntime.getInstructionSet(
7507                     scannedPackage.applicationInfo.primaryCpuAbi);
7508        }
7509
7510        PackageSetting requirer = null;
7511        for (PackageSetting ps : packagesForUser) {
7512            // If packagesForUser contains scannedPackage, we skip it. This will happen
7513            // when scannedPackage is an update of an existing package. Without this check,
7514            // we will never be able to change the ABI of any package belonging to a shared
7515            // user, even if it's compatible with other packages.
7516            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7517                if (ps.primaryCpuAbiString == null) {
7518                    continue;
7519                }
7520
7521                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7522                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7523                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7524                    // this but there's not much we can do.
7525                    String errorMessage = "Instruction set mismatch, "
7526                            + ((requirer == null) ? "[caller]" : requirer)
7527                            + " requires " + requiredInstructionSet + " whereas " + ps
7528                            + " requires " + instructionSet;
7529                    Slog.w(TAG, errorMessage);
7530                }
7531
7532                if (requiredInstructionSet == null) {
7533                    requiredInstructionSet = instructionSet;
7534                    requirer = ps;
7535                }
7536            }
7537        }
7538
7539        if (requiredInstructionSet != null) {
7540            String adjustedAbi;
7541            if (requirer != null) {
7542                // requirer != null implies that either scannedPackage was null or that scannedPackage
7543                // did not require an ABI, in which case we have to adjust scannedPackage to match
7544                // the ABI of the set (which is the same as requirer's ABI)
7545                adjustedAbi = requirer.primaryCpuAbiString;
7546                if (scannedPackage != null) {
7547                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7548                }
7549            } else {
7550                // requirer == null implies that we're updating all ABIs in the set to
7551                // match scannedPackage.
7552                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7553            }
7554
7555            for (PackageSetting ps : packagesForUser) {
7556                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7557                    if (ps.primaryCpuAbiString != null) {
7558                        continue;
7559                    }
7560
7561                    ps.primaryCpuAbiString = adjustedAbi;
7562                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7563                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7564                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7565
7566                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7567                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7568                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7569                            ps.primaryCpuAbiString = null;
7570                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7571                            return;
7572                        } else {
7573                            mInstaller.rmdex(ps.codePathString,
7574                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7575                        }
7576                    }
7577                }
7578            }
7579        }
7580    }
7581
7582    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7583        synchronized (mPackages) {
7584            mResolverReplaced = true;
7585            // Set up information for custom user intent resolution activity.
7586            mResolveActivity.applicationInfo = pkg.applicationInfo;
7587            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7588            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7589            mResolveActivity.processName = pkg.applicationInfo.packageName;
7590            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7591            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7592                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7593            mResolveActivity.theme = 0;
7594            mResolveActivity.exported = true;
7595            mResolveActivity.enabled = true;
7596            mResolveInfo.activityInfo = mResolveActivity;
7597            mResolveInfo.priority = 0;
7598            mResolveInfo.preferredOrder = 0;
7599            mResolveInfo.match = 0;
7600            mResolveComponentName = mCustomResolverComponentName;
7601            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7602                    mResolveComponentName);
7603        }
7604    }
7605
7606    private static String calculateBundledApkRoot(final String codePathString) {
7607        final File codePath = new File(codePathString);
7608        final File codeRoot;
7609        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7610            codeRoot = Environment.getRootDirectory();
7611        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7612            codeRoot = Environment.getOemDirectory();
7613        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7614            codeRoot = Environment.getVendorDirectory();
7615        } else {
7616            // Unrecognized code path; take its top real segment as the apk root:
7617            // e.g. /something/app/blah.apk => /something
7618            try {
7619                File f = codePath.getCanonicalFile();
7620                File parent = f.getParentFile();    // non-null because codePath is a file
7621                File tmp;
7622                while ((tmp = parent.getParentFile()) != null) {
7623                    f = parent;
7624                    parent = tmp;
7625                }
7626                codeRoot = f;
7627                Slog.w(TAG, "Unrecognized code path "
7628                        + codePath + " - using " + codeRoot);
7629            } catch (IOException e) {
7630                // Can't canonicalize the code path -- shenanigans?
7631                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7632                return Environment.getRootDirectory().getPath();
7633            }
7634        }
7635        return codeRoot.getPath();
7636    }
7637
7638    /**
7639     * Derive and set the location of native libraries for the given package,
7640     * which varies depending on where and how the package was installed.
7641     */
7642    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7643        final ApplicationInfo info = pkg.applicationInfo;
7644        final String codePath = pkg.codePath;
7645        final File codeFile = new File(codePath);
7646        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7647        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7648
7649        info.nativeLibraryRootDir = null;
7650        info.nativeLibraryRootRequiresIsa = false;
7651        info.nativeLibraryDir = null;
7652        info.secondaryNativeLibraryDir = null;
7653
7654        if (isApkFile(codeFile)) {
7655            // Monolithic install
7656            if (bundledApp) {
7657                // If "/system/lib64/apkname" exists, assume that is the per-package
7658                // native library directory to use; otherwise use "/system/lib/apkname".
7659                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7660                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7661                        getPrimaryInstructionSet(info));
7662
7663                // This is a bundled system app so choose the path based on the ABI.
7664                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7665                // is just the default path.
7666                final String apkName = deriveCodePathName(codePath);
7667                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7668                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7669                        apkName).getAbsolutePath();
7670
7671                if (info.secondaryCpuAbi != null) {
7672                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7673                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7674                            secondaryLibDir, apkName).getAbsolutePath();
7675                }
7676            } else if (asecApp) {
7677                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7678                        .getAbsolutePath();
7679            } else {
7680                final String apkName = deriveCodePathName(codePath);
7681                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7682                        .getAbsolutePath();
7683            }
7684
7685            info.nativeLibraryRootRequiresIsa = false;
7686            info.nativeLibraryDir = info.nativeLibraryRootDir;
7687        } else {
7688            // Cluster install
7689            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7690            info.nativeLibraryRootRequiresIsa = true;
7691
7692            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7693                    getPrimaryInstructionSet(info)).getAbsolutePath();
7694
7695            if (info.secondaryCpuAbi != null) {
7696                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7697                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7698            }
7699        }
7700    }
7701
7702    /**
7703     * Calculate the abis and roots for a bundled app. These can uniquely
7704     * be determined from the contents of the system partition, i.e whether
7705     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7706     * of this information, and instead assume that the system was built
7707     * sensibly.
7708     */
7709    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7710                                           PackageSetting pkgSetting) {
7711        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7712
7713        // If "/system/lib64/apkname" exists, assume that is the per-package
7714        // native library directory to use; otherwise use "/system/lib/apkname".
7715        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7716        setBundledAppAbi(pkg, apkRoot, apkName);
7717        // pkgSetting might be null during rescan following uninstall of updates
7718        // to a bundled app, so accommodate that possibility.  The settings in
7719        // that case will be established later from the parsed package.
7720        //
7721        // If the settings aren't null, sync them up with what we've just derived.
7722        // note that apkRoot isn't stored in the package settings.
7723        if (pkgSetting != null) {
7724            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7725            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7726        }
7727    }
7728
7729    /**
7730     * Deduces the ABI of a bundled app and sets the relevant fields on the
7731     * parsed pkg object.
7732     *
7733     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7734     *        under which system libraries are installed.
7735     * @param apkName the name of the installed package.
7736     */
7737    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7738        final File codeFile = new File(pkg.codePath);
7739
7740        final boolean has64BitLibs;
7741        final boolean has32BitLibs;
7742        if (isApkFile(codeFile)) {
7743            // Monolithic install
7744            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7745            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7746        } else {
7747            // Cluster install
7748            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7749            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7750                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7751                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7752                has64BitLibs = (new File(rootDir, isa)).exists();
7753            } else {
7754                has64BitLibs = false;
7755            }
7756            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7757                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7758                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7759                has32BitLibs = (new File(rootDir, isa)).exists();
7760            } else {
7761                has32BitLibs = false;
7762            }
7763        }
7764
7765        if (has64BitLibs && !has32BitLibs) {
7766            // The package has 64 bit libs, but not 32 bit libs. Its primary
7767            // ABI should be 64 bit. We can safely assume here that the bundled
7768            // native libraries correspond to the most preferred ABI in the list.
7769
7770            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7771            pkg.applicationInfo.secondaryCpuAbi = null;
7772        } else if (has32BitLibs && !has64BitLibs) {
7773            // The package has 32 bit libs but not 64 bit libs. Its primary
7774            // ABI should be 32 bit.
7775
7776            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7777            pkg.applicationInfo.secondaryCpuAbi = null;
7778        } else if (has32BitLibs && has64BitLibs) {
7779            // The application has both 64 and 32 bit bundled libraries. We check
7780            // here that the app declares multiArch support, and warn if it doesn't.
7781            //
7782            // We will be lenient here and record both ABIs. The primary will be the
7783            // ABI that's higher on the list, i.e, a device that's configured to prefer
7784            // 64 bit apps will see a 64 bit primary ABI,
7785
7786            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7787                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7788            }
7789
7790            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7791                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7792                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7793            } else {
7794                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7795                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7796            }
7797        } else {
7798            pkg.applicationInfo.primaryCpuAbi = null;
7799            pkg.applicationInfo.secondaryCpuAbi = null;
7800        }
7801    }
7802
7803    private void killApplication(String pkgName, int appId, String reason) {
7804        // Request the ActivityManager to kill the process(only for existing packages)
7805        // so that we do not end up in a confused state while the user is still using the older
7806        // version of the application while the new one gets installed.
7807        IActivityManager am = ActivityManagerNative.getDefault();
7808        if (am != null) {
7809            try {
7810                am.killApplicationWithAppId(pkgName, appId, reason);
7811            } catch (RemoteException e) {
7812            }
7813        }
7814    }
7815
7816    void removePackageLI(PackageSetting ps, boolean chatty) {
7817        if (DEBUG_INSTALL) {
7818            if (chatty)
7819                Log.d(TAG, "Removing package " + ps.name);
7820        }
7821
7822        // writer
7823        synchronized (mPackages) {
7824            mPackages.remove(ps.name);
7825            final PackageParser.Package pkg = ps.pkg;
7826            if (pkg != null) {
7827                cleanPackageDataStructuresLILPw(pkg, chatty);
7828            }
7829        }
7830    }
7831
7832    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7833        if (DEBUG_INSTALL) {
7834            if (chatty)
7835                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7836        }
7837
7838        // writer
7839        synchronized (mPackages) {
7840            mPackages.remove(pkg.applicationInfo.packageName);
7841            cleanPackageDataStructuresLILPw(pkg, chatty);
7842        }
7843    }
7844
7845    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7846        int N = pkg.providers.size();
7847        StringBuilder r = null;
7848        int i;
7849        for (i=0; i<N; i++) {
7850            PackageParser.Provider p = pkg.providers.get(i);
7851            mProviders.removeProvider(p);
7852            if (p.info.authority == null) {
7853
7854                /* There was another ContentProvider with this authority when
7855                 * this app was installed so this authority is null,
7856                 * Ignore it as we don't have to unregister the provider.
7857                 */
7858                continue;
7859            }
7860            String names[] = p.info.authority.split(";");
7861            for (int j = 0; j < names.length; j++) {
7862                if (mProvidersByAuthority.get(names[j]) == p) {
7863                    mProvidersByAuthority.remove(names[j]);
7864                    if (DEBUG_REMOVE) {
7865                        if (chatty)
7866                            Log.d(TAG, "Unregistered content provider: " + names[j]
7867                                    + ", className = " + p.info.name + ", isSyncable = "
7868                                    + p.info.isSyncable);
7869                    }
7870                }
7871            }
7872            if (DEBUG_REMOVE && chatty) {
7873                if (r == null) {
7874                    r = new StringBuilder(256);
7875                } else {
7876                    r.append(' ');
7877                }
7878                r.append(p.info.name);
7879            }
7880        }
7881        if (r != null) {
7882            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7883        }
7884
7885        N = pkg.services.size();
7886        r = null;
7887        for (i=0; i<N; i++) {
7888            PackageParser.Service s = pkg.services.get(i);
7889            mServices.removeService(s);
7890            if (chatty) {
7891                if (r == null) {
7892                    r = new StringBuilder(256);
7893                } else {
7894                    r.append(' ');
7895                }
7896                r.append(s.info.name);
7897            }
7898        }
7899        if (r != null) {
7900            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7901        }
7902
7903        N = pkg.receivers.size();
7904        r = null;
7905        for (i=0; i<N; i++) {
7906            PackageParser.Activity a = pkg.receivers.get(i);
7907            mReceivers.removeActivity(a, "receiver");
7908            if (DEBUG_REMOVE && chatty) {
7909                if (r == null) {
7910                    r = new StringBuilder(256);
7911                } else {
7912                    r.append(' ');
7913                }
7914                r.append(a.info.name);
7915            }
7916        }
7917        if (r != null) {
7918            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7919        }
7920
7921        N = pkg.activities.size();
7922        r = null;
7923        for (i=0; i<N; i++) {
7924            PackageParser.Activity a = pkg.activities.get(i);
7925            mActivities.removeActivity(a, "activity");
7926            if (DEBUG_REMOVE && chatty) {
7927                if (r == null) {
7928                    r = new StringBuilder(256);
7929                } else {
7930                    r.append(' ');
7931                }
7932                r.append(a.info.name);
7933            }
7934        }
7935        if (r != null) {
7936            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7937        }
7938
7939        N = pkg.permissions.size();
7940        r = null;
7941        for (i=0; i<N; i++) {
7942            PackageParser.Permission p = pkg.permissions.get(i);
7943            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7944            if (bp == null) {
7945                bp = mSettings.mPermissionTrees.get(p.info.name);
7946            }
7947            if (bp != null && bp.perm == p) {
7948                bp.perm = null;
7949                if (DEBUG_REMOVE && chatty) {
7950                    if (r == null) {
7951                        r = new StringBuilder(256);
7952                    } else {
7953                        r.append(' ');
7954                    }
7955                    r.append(p.info.name);
7956                }
7957            }
7958            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7959                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7960                if (appOpPerms != null) {
7961                    appOpPerms.remove(pkg.packageName);
7962                }
7963            }
7964        }
7965        if (r != null) {
7966            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7967        }
7968
7969        N = pkg.requestedPermissions.size();
7970        r = null;
7971        for (i=0; i<N; i++) {
7972            String perm = pkg.requestedPermissions.get(i);
7973            BasePermission bp = mSettings.mPermissions.get(perm);
7974            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7975                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7976                if (appOpPerms != null) {
7977                    appOpPerms.remove(pkg.packageName);
7978                    if (appOpPerms.isEmpty()) {
7979                        mAppOpPermissionPackages.remove(perm);
7980                    }
7981                }
7982            }
7983        }
7984        if (r != null) {
7985            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7986        }
7987
7988        N = pkg.instrumentation.size();
7989        r = null;
7990        for (i=0; i<N; i++) {
7991            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7992            mInstrumentation.remove(a.getComponentName());
7993            if (DEBUG_REMOVE && chatty) {
7994                if (r == null) {
7995                    r = new StringBuilder(256);
7996                } else {
7997                    r.append(' ');
7998                }
7999                r.append(a.info.name);
8000            }
8001        }
8002        if (r != null) {
8003            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8004        }
8005
8006        r = null;
8007        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8008            // Only system apps can hold shared libraries.
8009            if (pkg.libraryNames != null) {
8010                for (i=0; i<pkg.libraryNames.size(); i++) {
8011                    String name = pkg.libraryNames.get(i);
8012                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8013                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8014                        mSharedLibraries.remove(name);
8015                        if (DEBUG_REMOVE && chatty) {
8016                            if (r == null) {
8017                                r = new StringBuilder(256);
8018                            } else {
8019                                r.append(' ');
8020                            }
8021                            r.append(name);
8022                        }
8023                    }
8024                }
8025            }
8026        }
8027        if (r != null) {
8028            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8029        }
8030    }
8031
8032    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8033        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8034            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8035                return true;
8036            }
8037        }
8038        return false;
8039    }
8040
8041    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8042    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8043    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8044
8045    private void updatePermissionsLPw(String changingPkg,
8046            PackageParser.Package pkgInfo, int flags) {
8047        // Make sure there are no dangling permission trees.
8048        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8049        while (it.hasNext()) {
8050            final BasePermission bp = it.next();
8051            if (bp.packageSetting == null) {
8052                // We may not yet have parsed the package, so just see if
8053                // we still know about its settings.
8054                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8055            }
8056            if (bp.packageSetting == null) {
8057                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8058                        + " from package " + bp.sourcePackage);
8059                it.remove();
8060            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8061                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8062                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8063                            + " from package " + bp.sourcePackage);
8064                    flags |= UPDATE_PERMISSIONS_ALL;
8065                    it.remove();
8066                }
8067            }
8068        }
8069
8070        // Make sure all dynamic permissions have been assigned to a package,
8071        // and make sure there are no dangling permissions.
8072        it = mSettings.mPermissions.values().iterator();
8073        while (it.hasNext()) {
8074            final BasePermission bp = it.next();
8075            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8076                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8077                        + bp.name + " pkg=" + bp.sourcePackage
8078                        + " info=" + bp.pendingInfo);
8079                if (bp.packageSetting == null && bp.pendingInfo != null) {
8080                    final BasePermission tree = findPermissionTreeLP(bp.name);
8081                    if (tree != null && tree.perm != null) {
8082                        bp.packageSetting = tree.packageSetting;
8083                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8084                                new PermissionInfo(bp.pendingInfo));
8085                        bp.perm.info.packageName = tree.perm.info.packageName;
8086                        bp.perm.info.name = bp.name;
8087                        bp.uid = tree.uid;
8088                    }
8089                }
8090            }
8091            if (bp.packageSetting == null) {
8092                // We may not yet have parsed the package, so just see if
8093                // we still know about its settings.
8094                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8095            }
8096            if (bp.packageSetting == null) {
8097                Slog.w(TAG, "Removing dangling permission: " + bp.name
8098                        + " from package " + bp.sourcePackage);
8099                it.remove();
8100            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8101                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8102                    Slog.i(TAG, "Removing old permission: " + bp.name
8103                            + " from package " + bp.sourcePackage);
8104                    flags |= UPDATE_PERMISSIONS_ALL;
8105                    it.remove();
8106                }
8107            }
8108        }
8109
8110        // Now update the permissions for all packages, in particular
8111        // replace the granted permissions of the system packages.
8112        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8113            for (PackageParser.Package pkg : mPackages.values()) {
8114                if (pkg != pkgInfo) {
8115                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8116                            changingPkg);
8117                }
8118            }
8119        }
8120
8121        if (pkgInfo != null) {
8122            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8123        }
8124    }
8125
8126    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8127            String packageOfInterest) {
8128        // IMPORTANT: There are two types of permissions: install and runtime.
8129        // Install time permissions are granted when the app is installed to
8130        // all device users and users added in the future. Runtime permissions
8131        // are granted at runtime explicitly to specific users. Normal and signature
8132        // protected permissions are install time permissions. Dangerous permissions
8133        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8134        // otherwise they are runtime permissions. This function does not manage
8135        // runtime permissions except for the case an app targeting Lollipop MR1
8136        // being upgraded to target a newer SDK, in which case dangerous permissions
8137        // are transformed from install time to runtime ones.
8138
8139        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8140        if (ps == null) {
8141            return;
8142        }
8143
8144        PermissionsState permissionsState = ps.getPermissionsState();
8145        PermissionsState origPermissions = permissionsState;
8146
8147        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8148
8149        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8150
8151        boolean changedInstallPermission = false;
8152
8153        if (replace) {
8154            ps.installPermissionsFixed = false;
8155            if (!ps.isSharedUser()) {
8156                origPermissions = new PermissionsState(permissionsState);
8157                permissionsState.reset();
8158            }
8159        }
8160
8161        permissionsState.setGlobalGids(mGlobalGids);
8162
8163        final int N = pkg.requestedPermissions.size();
8164        for (int i=0; i<N; i++) {
8165            final String name = pkg.requestedPermissions.get(i);
8166            final BasePermission bp = mSettings.mPermissions.get(name);
8167
8168            if (DEBUG_INSTALL) {
8169                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8170            }
8171
8172            if (bp == null || bp.packageSetting == null) {
8173                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8174                    Slog.w(TAG, "Unknown permission " + name
8175                            + " in package " + pkg.packageName);
8176                }
8177                continue;
8178            }
8179
8180            final String perm = bp.name;
8181            boolean allowedSig = false;
8182            int grant = GRANT_DENIED;
8183
8184            // Keep track of app op permissions.
8185            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8186                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8187                if (pkgs == null) {
8188                    pkgs = new ArraySet<>();
8189                    mAppOpPermissionPackages.put(bp.name, pkgs);
8190                }
8191                pkgs.add(pkg.packageName);
8192            }
8193
8194            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8195            switch (level) {
8196                case PermissionInfo.PROTECTION_NORMAL: {
8197                    // For all apps normal permissions are install time ones.
8198                    grant = GRANT_INSTALL;
8199                } break;
8200
8201                case PermissionInfo.PROTECTION_DANGEROUS: {
8202                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8203                        // For legacy apps dangerous permissions are install time ones.
8204                        grant = GRANT_INSTALL_LEGACY;
8205                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8206                        // For legacy apps that became modern, install becomes runtime.
8207                        grant = GRANT_UPGRADE;
8208                    } else {
8209                        // For modern apps keep runtime permissions unchanged.
8210                        grant = GRANT_RUNTIME;
8211                    }
8212                } break;
8213
8214                case PermissionInfo.PROTECTION_SIGNATURE: {
8215                    // For all apps signature permissions are install time ones.
8216                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8217                    if (allowedSig) {
8218                        grant = GRANT_INSTALL;
8219                    }
8220                } break;
8221            }
8222
8223            if (DEBUG_INSTALL) {
8224                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8225            }
8226
8227            if (grant != GRANT_DENIED) {
8228                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8229                    // If this is an existing, non-system package, then
8230                    // we can't add any new permissions to it.
8231                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8232                        // Except...  if this is a permission that was added
8233                        // to the platform (note: need to only do this when
8234                        // updating the platform).
8235                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8236                            grant = GRANT_DENIED;
8237                        }
8238                    }
8239                }
8240
8241                switch (grant) {
8242                    case GRANT_INSTALL: {
8243                        // Revoke this as runtime permission to handle the case of
8244                        // a runtime permission being downgraded to an install one.
8245                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8246                            if (origPermissions.getRuntimePermissionState(
8247                                    bp.name, userId) != null) {
8248                                // Revoke the runtime permission and clear the flags.
8249                                origPermissions.revokeRuntimePermission(bp, userId);
8250                                origPermissions.updatePermissionFlags(bp, userId,
8251                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8252                                // If we revoked a permission permission, we have to write.
8253                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8254                                        changedRuntimePermissionUserIds, userId);
8255                            }
8256                        }
8257                        // Grant an install permission.
8258                        if (permissionsState.grantInstallPermission(bp) !=
8259                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8260                            changedInstallPermission = true;
8261                        }
8262                    } break;
8263
8264                    case GRANT_INSTALL_LEGACY: {
8265                        // Grant an install permission.
8266                        if (permissionsState.grantInstallPermission(bp) !=
8267                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8268                            changedInstallPermission = true;
8269                        }
8270                    } break;
8271
8272                    case GRANT_RUNTIME: {
8273                        // Grant previously granted runtime permissions.
8274                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8275                            PermissionState permissionState = origPermissions
8276                                    .getRuntimePermissionState(bp.name, userId);
8277                            final int flags = permissionState != null
8278                                    ? permissionState.getFlags() : 0;
8279                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8280                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8281                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8282                                    // If we cannot put the permission as it was, we have to write.
8283                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8284                                            changedRuntimePermissionUserIds, userId);
8285                                }
8286                            }
8287                            // Propagate the permission flags.
8288                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8289                        }
8290                    } break;
8291
8292                    case GRANT_UPGRADE: {
8293                        // Grant runtime permissions for a previously held install permission.
8294                        PermissionState permissionState = origPermissions
8295                                .getInstallPermissionState(bp.name);
8296                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8297
8298                        if (origPermissions.revokeInstallPermission(bp)
8299                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8300                            // We will be transferring the permission flags, so clear them.
8301                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8302                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8303                            changedInstallPermission = true;
8304                        }
8305
8306                        // If the permission is not to be promoted to runtime we ignore it and
8307                        // also its other flags as they are not applicable to install permissions.
8308                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8309                            for (int userId : currentUserIds) {
8310                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8311                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8312                                    // Transfer the permission flags.
8313                                    permissionsState.updatePermissionFlags(bp, userId,
8314                                            flags, flags);
8315                                    // If we granted the permission, we have to write.
8316                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8317                                            changedRuntimePermissionUserIds, userId);
8318                                }
8319                            }
8320                        }
8321                    } break;
8322
8323                    default: {
8324                        if (packageOfInterest == null
8325                                || packageOfInterest.equals(pkg.packageName)) {
8326                            Slog.w(TAG, "Not granting permission " + perm
8327                                    + " to package " + pkg.packageName
8328                                    + " because it was previously installed without");
8329                        }
8330                    } break;
8331                }
8332            } else {
8333                if (permissionsState.revokeInstallPermission(bp) !=
8334                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8335                    // Also drop the permission flags.
8336                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8337                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8338                    changedInstallPermission = true;
8339                    Slog.i(TAG, "Un-granting permission " + perm
8340                            + " from package " + pkg.packageName
8341                            + " (protectionLevel=" + bp.protectionLevel
8342                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8343                            + ")");
8344                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8345                    // Don't print warning for app op permissions, since it is fine for them
8346                    // not to be granted, there is a UI for the user to decide.
8347                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8348                        Slog.w(TAG, "Not granting permission " + perm
8349                                + " to package " + pkg.packageName
8350                                + " (protectionLevel=" + bp.protectionLevel
8351                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8352                                + ")");
8353                    }
8354                }
8355            }
8356        }
8357
8358        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8359                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8360            // This is the first that we have heard about this package, so the
8361            // permissions we have now selected are fixed until explicitly
8362            // changed.
8363            ps.installPermissionsFixed = true;
8364        }
8365
8366        // Persist the runtime permissions state for users with changes.
8367        for (int userId : changedRuntimePermissionUserIds) {
8368            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8369        }
8370    }
8371
8372    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8373        boolean allowed = false;
8374        final int NP = PackageParser.NEW_PERMISSIONS.length;
8375        for (int ip=0; ip<NP; ip++) {
8376            final PackageParser.NewPermissionInfo npi
8377                    = PackageParser.NEW_PERMISSIONS[ip];
8378            if (npi.name.equals(perm)
8379                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8380                allowed = true;
8381                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8382                        + pkg.packageName);
8383                break;
8384            }
8385        }
8386        return allowed;
8387    }
8388
8389    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8390            BasePermission bp, PermissionsState origPermissions) {
8391        boolean allowed;
8392        allowed = (compareSignatures(
8393                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8394                        == PackageManager.SIGNATURE_MATCH)
8395                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8396                        == PackageManager.SIGNATURE_MATCH);
8397        if (!allowed && (bp.protectionLevel
8398                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
8399            if (isSystemApp(pkg)) {
8400                // For updated system applications, a system permission
8401                // is granted only if it had been defined by the original application.
8402                if (pkg.isUpdatedSystemApp()) {
8403                    final PackageSetting sysPs = mSettings
8404                            .getDisabledSystemPkgLPr(pkg.packageName);
8405                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8406                        // If the original was granted this permission, we take
8407                        // that grant decision as read and propagate it to the
8408                        // update.
8409                        if (sysPs.isPrivileged()) {
8410                            allowed = true;
8411                        }
8412                    } else {
8413                        // The system apk may have been updated with an older
8414                        // version of the one on the data partition, but which
8415                        // granted a new system permission that it didn't have
8416                        // before.  In this case we do want to allow the app to
8417                        // now get the new permission if the ancestral apk is
8418                        // privileged to get it.
8419                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8420                            for (int j=0;
8421                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8422                                if (perm.equals(
8423                                        sysPs.pkg.requestedPermissions.get(j))) {
8424                                    allowed = true;
8425                                    break;
8426                                }
8427                            }
8428                        }
8429                    }
8430                } else {
8431                    allowed = isPrivilegedApp(pkg);
8432                }
8433            }
8434        }
8435        if (!allowed && (bp.protectionLevel
8436                & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8437                && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8438            // If this was a previously normal/dangerous permission that got moved
8439            // to a system permission as part of the runtime permission redesign, then
8440            // we still want to blindly grant it to old apps.
8441            allowed = true;
8442        }
8443        if (!allowed && (bp.protectionLevel
8444                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8445            // For development permissions, a development permission
8446            // is granted only if it was already granted.
8447            allowed = origPermissions.hasInstallPermission(perm);
8448        }
8449        return allowed;
8450    }
8451
8452    final class ActivityIntentResolver
8453            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8454        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8455                boolean defaultOnly, int userId) {
8456            if (!sUserManager.exists(userId)) return null;
8457            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8458            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8459        }
8460
8461        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8462                int userId) {
8463            if (!sUserManager.exists(userId)) return null;
8464            mFlags = flags;
8465            return super.queryIntent(intent, resolvedType,
8466                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8467        }
8468
8469        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8470                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8471            if (!sUserManager.exists(userId)) return null;
8472            if (packageActivities == null) {
8473                return null;
8474            }
8475            mFlags = flags;
8476            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8477            final int N = packageActivities.size();
8478            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8479                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8480
8481            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8482            for (int i = 0; i < N; ++i) {
8483                intentFilters = packageActivities.get(i).intents;
8484                if (intentFilters != null && intentFilters.size() > 0) {
8485                    PackageParser.ActivityIntentInfo[] array =
8486                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8487                    intentFilters.toArray(array);
8488                    listCut.add(array);
8489                }
8490            }
8491            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8492        }
8493
8494        public final void addActivity(PackageParser.Activity a, String type) {
8495            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8496            mActivities.put(a.getComponentName(), a);
8497            if (DEBUG_SHOW_INFO)
8498                Log.v(
8499                TAG, "  " + type + " " +
8500                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8501            if (DEBUG_SHOW_INFO)
8502                Log.v(TAG, "    Class=" + a.info.name);
8503            final int NI = a.intents.size();
8504            for (int j=0; j<NI; j++) {
8505                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8506                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8507                    intent.setPriority(0);
8508                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8509                            + a.className + " with priority > 0, forcing to 0");
8510                }
8511                if (DEBUG_SHOW_INFO) {
8512                    Log.v(TAG, "    IntentFilter:");
8513                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8514                }
8515                if (!intent.debugCheck()) {
8516                    Log.w(TAG, "==> For Activity " + a.info.name);
8517                }
8518                addFilter(intent);
8519            }
8520        }
8521
8522        public final void removeActivity(PackageParser.Activity a, String type) {
8523            mActivities.remove(a.getComponentName());
8524            if (DEBUG_SHOW_INFO) {
8525                Log.v(TAG, "  " + type + " "
8526                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8527                                : a.info.name) + ":");
8528                Log.v(TAG, "    Class=" + a.info.name);
8529            }
8530            final int NI = a.intents.size();
8531            for (int j=0; j<NI; j++) {
8532                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8533                if (DEBUG_SHOW_INFO) {
8534                    Log.v(TAG, "    IntentFilter:");
8535                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8536                }
8537                removeFilter(intent);
8538            }
8539        }
8540
8541        @Override
8542        protected boolean allowFilterResult(
8543                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8544            ActivityInfo filterAi = filter.activity.info;
8545            for (int i=dest.size()-1; i>=0; i--) {
8546                ActivityInfo destAi = dest.get(i).activityInfo;
8547                if (destAi.name == filterAi.name
8548                        && destAi.packageName == filterAi.packageName) {
8549                    return false;
8550                }
8551            }
8552            return true;
8553        }
8554
8555        @Override
8556        protected ActivityIntentInfo[] newArray(int size) {
8557            return new ActivityIntentInfo[size];
8558        }
8559
8560        @Override
8561        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8562            if (!sUserManager.exists(userId)) return true;
8563            PackageParser.Package p = filter.activity.owner;
8564            if (p != null) {
8565                PackageSetting ps = (PackageSetting)p.mExtras;
8566                if (ps != null) {
8567                    // System apps are never considered stopped for purposes of
8568                    // filtering, because there may be no way for the user to
8569                    // actually re-launch them.
8570                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8571                            && ps.getStopped(userId);
8572                }
8573            }
8574            return false;
8575        }
8576
8577        @Override
8578        protected boolean isPackageForFilter(String packageName,
8579                PackageParser.ActivityIntentInfo info) {
8580            return packageName.equals(info.activity.owner.packageName);
8581        }
8582
8583        @Override
8584        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8585                int match, int userId) {
8586            if (!sUserManager.exists(userId)) return null;
8587            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8588                return null;
8589            }
8590            final PackageParser.Activity activity = info.activity;
8591            if (mSafeMode && (activity.info.applicationInfo.flags
8592                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8593                return null;
8594            }
8595            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8596            if (ps == null) {
8597                return null;
8598            }
8599            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8600                    ps.readUserState(userId), userId);
8601            if (ai == null) {
8602                return null;
8603            }
8604            final ResolveInfo res = new ResolveInfo();
8605            res.activityInfo = ai;
8606            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8607                res.filter = info;
8608            }
8609            if (info != null) {
8610                res.handleAllWebDataURI = info.handleAllWebDataURI();
8611            }
8612            res.priority = info.getPriority();
8613            res.preferredOrder = activity.owner.mPreferredOrder;
8614            //System.out.println("Result: " + res.activityInfo.className +
8615            //                   " = " + res.priority);
8616            res.match = match;
8617            res.isDefault = info.hasDefault;
8618            res.labelRes = info.labelRes;
8619            res.nonLocalizedLabel = info.nonLocalizedLabel;
8620            if (userNeedsBadging(userId)) {
8621                res.noResourceId = true;
8622            } else {
8623                res.icon = info.icon;
8624            }
8625            res.iconResourceId = info.icon;
8626            res.system = res.activityInfo.applicationInfo.isSystemApp();
8627            return res;
8628        }
8629
8630        @Override
8631        protected void sortResults(List<ResolveInfo> results) {
8632            Collections.sort(results, mResolvePrioritySorter);
8633        }
8634
8635        @Override
8636        protected void dumpFilter(PrintWriter out, String prefix,
8637                PackageParser.ActivityIntentInfo filter) {
8638            out.print(prefix); out.print(
8639                    Integer.toHexString(System.identityHashCode(filter.activity)));
8640                    out.print(' ');
8641                    filter.activity.printComponentShortName(out);
8642                    out.print(" filter ");
8643                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8644        }
8645
8646        @Override
8647        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8648            return filter.activity;
8649        }
8650
8651        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8652            PackageParser.Activity activity = (PackageParser.Activity)label;
8653            out.print(prefix); out.print(
8654                    Integer.toHexString(System.identityHashCode(activity)));
8655                    out.print(' ');
8656                    activity.printComponentShortName(out);
8657            if (count > 1) {
8658                out.print(" ("); out.print(count); out.print(" filters)");
8659            }
8660            out.println();
8661        }
8662
8663//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8664//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8665//            final List<ResolveInfo> retList = Lists.newArrayList();
8666//            while (i.hasNext()) {
8667//                final ResolveInfo resolveInfo = i.next();
8668//                if (isEnabledLP(resolveInfo.activityInfo)) {
8669//                    retList.add(resolveInfo);
8670//                }
8671//            }
8672//            return retList;
8673//        }
8674
8675        // Keys are String (activity class name), values are Activity.
8676        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8677                = new ArrayMap<ComponentName, PackageParser.Activity>();
8678        private int mFlags;
8679    }
8680
8681    private final class ServiceIntentResolver
8682            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8683        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8684                boolean defaultOnly, int userId) {
8685            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8686            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8687        }
8688
8689        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8690                int userId) {
8691            if (!sUserManager.exists(userId)) return null;
8692            mFlags = flags;
8693            return super.queryIntent(intent, resolvedType,
8694                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8695        }
8696
8697        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8698                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8699            if (!sUserManager.exists(userId)) return null;
8700            if (packageServices == null) {
8701                return null;
8702            }
8703            mFlags = flags;
8704            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8705            final int N = packageServices.size();
8706            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8707                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8708
8709            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8710            for (int i = 0; i < N; ++i) {
8711                intentFilters = packageServices.get(i).intents;
8712                if (intentFilters != null && intentFilters.size() > 0) {
8713                    PackageParser.ServiceIntentInfo[] array =
8714                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8715                    intentFilters.toArray(array);
8716                    listCut.add(array);
8717                }
8718            }
8719            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8720        }
8721
8722        public final void addService(PackageParser.Service s) {
8723            mServices.put(s.getComponentName(), s);
8724            if (DEBUG_SHOW_INFO) {
8725                Log.v(TAG, "  "
8726                        + (s.info.nonLocalizedLabel != null
8727                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8728                Log.v(TAG, "    Class=" + s.info.name);
8729            }
8730            final int NI = s.intents.size();
8731            int j;
8732            for (j=0; j<NI; j++) {
8733                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8734                if (DEBUG_SHOW_INFO) {
8735                    Log.v(TAG, "    IntentFilter:");
8736                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8737                }
8738                if (!intent.debugCheck()) {
8739                    Log.w(TAG, "==> For Service " + s.info.name);
8740                }
8741                addFilter(intent);
8742            }
8743        }
8744
8745        public final void removeService(PackageParser.Service s) {
8746            mServices.remove(s.getComponentName());
8747            if (DEBUG_SHOW_INFO) {
8748                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8749                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8750                Log.v(TAG, "    Class=" + s.info.name);
8751            }
8752            final int NI = s.intents.size();
8753            int j;
8754            for (j=0; j<NI; j++) {
8755                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8756                if (DEBUG_SHOW_INFO) {
8757                    Log.v(TAG, "    IntentFilter:");
8758                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8759                }
8760                removeFilter(intent);
8761            }
8762        }
8763
8764        @Override
8765        protected boolean allowFilterResult(
8766                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8767            ServiceInfo filterSi = filter.service.info;
8768            for (int i=dest.size()-1; i>=0; i--) {
8769                ServiceInfo destAi = dest.get(i).serviceInfo;
8770                if (destAi.name == filterSi.name
8771                        && destAi.packageName == filterSi.packageName) {
8772                    return false;
8773                }
8774            }
8775            return true;
8776        }
8777
8778        @Override
8779        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8780            return new PackageParser.ServiceIntentInfo[size];
8781        }
8782
8783        @Override
8784        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8785            if (!sUserManager.exists(userId)) return true;
8786            PackageParser.Package p = filter.service.owner;
8787            if (p != null) {
8788                PackageSetting ps = (PackageSetting)p.mExtras;
8789                if (ps != null) {
8790                    // System apps are never considered stopped for purposes of
8791                    // filtering, because there may be no way for the user to
8792                    // actually re-launch them.
8793                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8794                            && ps.getStopped(userId);
8795                }
8796            }
8797            return false;
8798        }
8799
8800        @Override
8801        protected boolean isPackageForFilter(String packageName,
8802                PackageParser.ServiceIntentInfo info) {
8803            return packageName.equals(info.service.owner.packageName);
8804        }
8805
8806        @Override
8807        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8808                int match, int userId) {
8809            if (!sUserManager.exists(userId)) return null;
8810            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8811            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8812                return null;
8813            }
8814            final PackageParser.Service service = info.service;
8815            if (mSafeMode && (service.info.applicationInfo.flags
8816                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8817                return null;
8818            }
8819            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8820            if (ps == null) {
8821                return null;
8822            }
8823            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8824                    ps.readUserState(userId), userId);
8825            if (si == null) {
8826                return null;
8827            }
8828            final ResolveInfo res = new ResolveInfo();
8829            res.serviceInfo = si;
8830            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8831                res.filter = filter;
8832            }
8833            res.priority = info.getPriority();
8834            res.preferredOrder = service.owner.mPreferredOrder;
8835            res.match = match;
8836            res.isDefault = info.hasDefault;
8837            res.labelRes = info.labelRes;
8838            res.nonLocalizedLabel = info.nonLocalizedLabel;
8839            res.icon = info.icon;
8840            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8841            return res;
8842        }
8843
8844        @Override
8845        protected void sortResults(List<ResolveInfo> results) {
8846            Collections.sort(results, mResolvePrioritySorter);
8847        }
8848
8849        @Override
8850        protected void dumpFilter(PrintWriter out, String prefix,
8851                PackageParser.ServiceIntentInfo filter) {
8852            out.print(prefix); out.print(
8853                    Integer.toHexString(System.identityHashCode(filter.service)));
8854                    out.print(' ');
8855                    filter.service.printComponentShortName(out);
8856                    out.print(" filter ");
8857                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8858        }
8859
8860        @Override
8861        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8862            return filter.service;
8863        }
8864
8865        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8866            PackageParser.Service service = (PackageParser.Service)label;
8867            out.print(prefix); out.print(
8868                    Integer.toHexString(System.identityHashCode(service)));
8869                    out.print(' ');
8870                    service.printComponentShortName(out);
8871            if (count > 1) {
8872                out.print(" ("); out.print(count); out.print(" filters)");
8873            }
8874            out.println();
8875        }
8876
8877//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8878//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8879//            final List<ResolveInfo> retList = Lists.newArrayList();
8880//            while (i.hasNext()) {
8881//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8882//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8883//                    retList.add(resolveInfo);
8884//                }
8885//            }
8886//            return retList;
8887//        }
8888
8889        // Keys are String (activity class name), values are Activity.
8890        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8891                = new ArrayMap<ComponentName, PackageParser.Service>();
8892        private int mFlags;
8893    };
8894
8895    private final class ProviderIntentResolver
8896            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8897        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8898                boolean defaultOnly, int userId) {
8899            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8900            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8901        }
8902
8903        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8904                int userId) {
8905            if (!sUserManager.exists(userId))
8906                return null;
8907            mFlags = flags;
8908            return super.queryIntent(intent, resolvedType,
8909                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8910        }
8911
8912        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8913                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8914            if (!sUserManager.exists(userId))
8915                return null;
8916            if (packageProviders == null) {
8917                return null;
8918            }
8919            mFlags = flags;
8920            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8921            final int N = packageProviders.size();
8922            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8923                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8924
8925            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8926            for (int i = 0; i < N; ++i) {
8927                intentFilters = packageProviders.get(i).intents;
8928                if (intentFilters != null && intentFilters.size() > 0) {
8929                    PackageParser.ProviderIntentInfo[] array =
8930                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8931                    intentFilters.toArray(array);
8932                    listCut.add(array);
8933                }
8934            }
8935            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8936        }
8937
8938        public final void addProvider(PackageParser.Provider p) {
8939            if (mProviders.containsKey(p.getComponentName())) {
8940                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8941                return;
8942            }
8943
8944            mProviders.put(p.getComponentName(), p);
8945            if (DEBUG_SHOW_INFO) {
8946                Log.v(TAG, "  "
8947                        + (p.info.nonLocalizedLabel != null
8948                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8949                Log.v(TAG, "    Class=" + p.info.name);
8950            }
8951            final int NI = p.intents.size();
8952            int j;
8953            for (j = 0; j < NI; j++) {
8954                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8955                if (DEBUG_SHOW_INFO) {
8956                    Log.v(TAG, "    IntentFilter:");
8957                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8958                }
8959                if (!intent.debugCheck()) {
8960                    Log.w(TAG, "==> For Provider " + p.info.name);
8961                }
8962                addFilter(intent);
8963            }
8964        }
8965
8966        public final void removeProvider(PackageParser.Provider p) {
8967            mProviders.remove(p.getComponentName());
8968            if (DEBUG_SHOW_INFO) {
8969                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8970                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8971                Log.v(TAG, "    Class=" + p.info.name);
8972            }
8973            final int NI = p.intents.size();
8974            int j;
8975            for (j = 0; j < NI; j++) {
8976                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8977                if (DEBUG_SHOW_INFO) {
8978                    Log.v(TAG, "    IntentFilter:");
8979                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8980                }
8981                removeFilter(intent);
8982            }
8983        }
8984
8985        @Override
8986        protected boolean allowFilterResult(
8987                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8988            ProviderInfo filterPi = filter.provider.info;
8989            for (int i = dest.size() - 1; i >= 0; i--) {
8990                ProviderInfo destPi = dest.get(i).providerInfo;
8991                if (destPi.name == filterPi.name
8992                        && destPi.packageName == filterPi.packageName) {
8993                    return false;
8994                }
8995            }
8996            return true;
8997        }
8998
8999        @Override
9000        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9001            return new PackageParser.ProviderIntentInfo[size];
9002        }
9003
9004        @Override
9005        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9006            if (!sUserManager.exists(userId))
9007                return true;
9008            PackageParser.Package p = filter.provider.owner;
9009            if (p != null) {
9010                PackageSetting ps = (PackageSetting) p.mExtras;
9011                if (ps != null) {
9012                    // System apps are never considered stopped for purposes of
9013                    // filtering, because there may be no way for the user to
9014                    // actually re-launch them.
9015                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9016                            && ps.getStopped(userId);
9017                }
9018            }
9019            return false;
9020        }
9021
9022        @Override
9023        protected boolean isPackageForFilter(String packageName,
9024                PackageParser.ProviderIntentInfo info) {
9025            return packageName.equals(info.provider.owner.packageName);
9026        }
9027
9028        @Override
9029        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9030                int match, int userId) {
9031            if (!sUserManager.exists(userId))
9032                return null;
9033            final PackageParser.ProviderIntentInfo info = filter;
9034            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9035                return null;
9036            }
9037            final PackageParser.Provider provider = info.provider;
9038            if (mSafeMode && (provider.info.applicationInfo.flags
9039                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9040                return null;
9041            }
9042            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9043            if (ps == null) {
9044                return null;
9045            }
9046            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9047                    ps.readUserState(userId), userId);
9048            if (pi == null) {
9049                return null;
9050            }
9051            final ResolveInfo res = new ResolveInfo();
9052            res.providerInfo = pi;
9053            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9054                res.filter = filter;
9055            }
9056            res.priority = info.getPriority();
9057            res.preferredOrder = provider.owner.mPreferredOrder;
9058            res.match = match;
9059            res.isDefault = info.hasDefault;
9060            res.labelRes = info.labelRes;
9061            res.nonLocalizedLabel = info.nonLocalizedLabel;
9062            res.icon = info.icon;
9063            res.system = res.providerInfo.applicationInfo.isSystemApp();
9064            return res;
9065        }
9066
9067        @Override
9068        protected void sortResults(List<ResolveInfo> results) {
9069            Collections.sort(results, mResolvePrioritySorter);
9070        }
9071
9072        @Override
9073        protected void dumpFilter(PrintWriter out, String prefix,
9074                PackageParser.ProviderIntentInfo filter) {
9075            out.print(prefix);
9076            out.print(
9077                    Integer.toHexString(System.identityHashCode(filter.provider)));
9078            out.print(' ');
9079            filter.provider.printComponentShortName(out);
9080            out.print(" filter ");
9081            out.println(Integer.toHexString(System.identityHashCode(filter)));
9082        }
9083
9084        @Override
9085        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9086            return filter.provider;
9087        }
9088
9089        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9090            PackageParser.Provider provider = (PackageParser.Provider)label;
9091            out.print(prefix); out.print(
9092                    Integer.toHexString(System.identityHashCode(provider)));
9093                    out.print(' ');
9094                    provider.printComponentShortName(out);
9095            if (count > 1) {
9096                out.print(" ("); out.print(count); out.print(" filters)");
9097            }
9098            out.println();
9099        }
9100
9101        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9102                = new ArrayMap<ComponentName, PackageParser.Provider>();
9103        private int mFlags;
9104    };
9105
9106    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9107            new Comparator<ResolveInfo>() {
9108        public int compare(ResolveInfo r1, ResolveInfo r2) {
9109            int v1 = r1.priority;
9110            int v2 = r2.priority;
9111            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9112            if (v1 != v2) {
9113                return (v1 > v2) ? -1 : 1;
9114            }
9115            v1 = r1.preferredOrder;
9116            v2 = r2.preferredOrder;
9117            if (v1 != v2) {
9118                return (v1 > v2) ? -1 : 1;
9119            }
9120            if (r1.isDefault != r2.isDefault) {
9121                return r1.isDefault ? -1 : 1;
9122            }
9123            v1 = r1.match;
9124            v2 = r2.match;
9125            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9126            if (v1 != v2) {
9127                return (v1 > v2) ? -1 : 1;
9128            }
9129            if (r1.system != r2.system) {
9130                return r1.system ? -1 : 1;
9131            }
9132            return 0;
9133        }
9134    };
9135
9136    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9137            new Comparator<ProviderInfo>() {
9138        public int compare(ProviderInfo p1, ProviderInfo p2) {
9139            final int v1 = p1.initOrder;
9140            final int v2 = p2.initOrder;
9141            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9142        }
9143    };
9144
9145    final void sendPackageBroadcast(final String action, final String pkg,
9146            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9147            final int[] userIds) {
9148        mHandler.post(new Runnable() {
9149            @Override
9150            public void run() {
9151                try {
9152                    final IActivityManager am = ActivityManagerNative.getDefault();
9153                    if (am == null) return;
9154                    final int[] resolvedUserIds;
9155                    if (userIds == null) {
9156                        resolvedUserIds = am.getRunningUserIds();
9157                    } else {
9158                        resolvedUserIds = userIds;
9159                    }
9160                    for (int id : resolvedUserIds) {
9161                        final Intent intent = new Intent(action,
9162                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9163                        if (extras != null) {
9164                            intent.putExtras(extras);
9165                        }
9166                        if (targetPkg != null) {
9167                            intent.setPackage(targetPkg);
9168                        }
9169                        // Modify the UID when posting to other users
9170                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9171                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9172                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9173                            intent.putExtra(Intent.EXTRA_UID, uid);
9174                        }
9175                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9176                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9177                        if (DEBUG_BROADCASTS) {
9178                            RuntimeException here = new RuntimeException("here");
9179                            here.fillInStackTrace();
9180                            Slog.d(TAG, "Sending to user " + id + ": "
9181                                    + intent.toShortString(false, true, false, false)
9182                                    + " " + intent.getExtras(), here);
9183                        }
9184                        am.broadcastIntent(null, intent, null, finishedReceiver,
9185                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9186                                null, finishedReceiver != null, false, id);
9187                    }
9188                } catch (RemoteException ex) {
9189                }
9190            }
9191        });
9192    }
9193
9194    /**
9195     * Check if the external storage media is available. This is true if there
9196     * is a mounted external storage medium or if the external storage is
9197     * emulated.
9198     */
9199    private boolean isExternalMediaAvailable() {
9200        return mMediaMounted || Environment.isExternalStorageEmulated();
9201    }
9202
9203    @Override
9204    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9205        // writer
9206        synchronized (mPackages) {
9207            if (!isExternalMediaAvailable()) {
9208                // If the external storage is no longer mounted at this point,
9209                // the caller may not have been able to delete all of this
9210                // packages files and can not delete any more.  Bail.
9211                return null;
9212            }
9213            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9214            if (lastPackage != null) {
9215                pkgs.remove(lastPackage);
9216            }
9217            if (pkgs.size() > 0) {
9218                return pkgs.get(0);
9219            }
9220        }
9221        return null;
9222    }
9223
9224    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9225        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9226                userId, andCode ? 1 : 0, packageName);
9227        if (mSystemReady) {
9228            msg.sendToTarget();
9229        } else {
9230            if (mPostSystemReadyMessages == null) {
9231                mPostSystemReadyMessages = new ArrayList<>();
9232            }
9233            mPostSystemReadyMessages.add(msg);
9234        }
9235    }
9236
9237    void startCleaningPackages() {
9238        // reader
9239        synchronized (mPackages) {
9240            if (!isExternalMediaAvailable()) {
9241                return;
9242            }
9243            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9244                return;
9245            }
9246        }
9247        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9248        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9249        IActivityManager am = ActivityManagerNative.getDefault();
9250        if (am != null) {
9251            try {
9252                am.startService(null, intent, null, mContext.getOpPackageName(),
9253                        UserHandle.USER_OWNER);
9254            } catch (RemoteException e) {
9255            }
9256        }
9257    }
9258
9259    @Override
9260    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9261            int installFlags, String installerPackageName, VerificationParams verificationParams,
9262            String packageAbiOverride) {
9263        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9264                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9265    }
9266
9267    @Override
9268    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9269            int installFlags, String installerPackageName, VerificationParams verificationParams,
9270            String packageAbiOverride, int userId) {
9271        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9272
9273        final int callingUid = Binder.getCallingUid();
9274        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9275
9276        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9277            try {
9278                if (observer != null) {
9279                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9280                }
9281            } catch (RemoteException re) {
9282            }
9283            return;
9284        }
9285
9286        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9287            installFlags |= PackageManager.INSTALL_FROM_ADB;
9288
9289        } else {
9290            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9291            // about installerPackageName.
9292
9293            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9294            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9295        }
9296
9297        UserHandle user;
9298        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9299            user = UserHandle.ALL;
9300        } else {
9301            user = new UserHandle(userId);
9302        }
9303
9304        // Only system components can circumvent runtime permissions when installing.
9305        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9306                && mContext.checkCallingOrSelfPermission(Manifest.permission
9307                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9308            throw new SecurityException("You need the "
9309                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9310                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9311        }
9312
9313        verificationParams.setInstallerUid(callingUid);
9314
9315        final File originFile = new File(originPath);
9316        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9317
9318        final Message msg = mHandler.obtainMessage(INIT_COPY);
9319        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9320                null, verificationParams, user, packageAbiOverride);
9321        mHandler.sendMessage(msg);
9322    }
9323
9324    void installStage(String packageName, File stagedDir, String stagedCid,
9325            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9326            String installerPackageName, int installerUid, UserHandle user) {
9327        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9328                params.referrerUri, installerUid, null);
9329        verifParams.setInstallerUid(installerUid);
9330
9331        final OriginInfo origin;
9332        if (stagedDir != null) {
9333            origin = OriginInfo.fromStagedFile(stagedDir);
9334        } else {
9335            origin = OriginInfo.fromStagedContainer(stagedCid);
9336        }
9337
9338        final Message msg = mHandler.obtainMessage(INIT_COPY);
9339        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9340                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9341        mHandler.sendMessage(msg);
9342    }
9343
9344    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9345        Bundle extras = new Bundle(1);
9346        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9347
9348        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9349                packageName, extras, null, null, new int[] {userId});
9350        try {
9351            IActivityManager am = ActivityManagerNative.getDefault();
9352            final boolean isSystem =
9353                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9354            if (isSystem && am.isUserRunning(userId, false)) {
9355                // The just-installed/enabled app is bundled on the system, so presumed
9356                // to be able to run automatically without needing an explicit launch.
9357                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9358                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9359                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9360                        .setPackage(packageName);
9361                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9362                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9363            }
9364        } catch (RemoteException e) {
9365            // shouldn't happen
9366            Slog.w(TAG, "Unable to bootstrap installed package", e);
9367        }
9368    }
9369
9370    @Override
9371    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9372            int userId) {
9373        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9374        PackageSetting pkgSetting;
9375        final int uid = Binder.getCallingUid();
9376        enforceCrossUserPermission(uid, userId, true, true,
9377                "setApplicationHiddenSetting for user " + userId);
9378
9379        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9380            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9381            return false;
9382        }
9383
9384        long callingId = Binder.clearCallingIdentity();
9385        try {
9386            boolean sendAdded = false;
9387            boolean sendRemoved = false;
9388            // writer
9389            synchronized (mPackages) {
9390                pkgSetting = mSettings.mPackages.get(packageName);
9391                if (pkgSetting == null) {
9392                    return false;
9393                }
9394                if (pkgSetting.getHidden(userId) != hidden) {
9395                    pkgSetting.setHidden(hidden, userId);
9396                    mSettings.writePackageRestrictionsLPr(userId);
9397                    if (hidden) {
9398                        sendRemoved = true;
9399                    } else {
9400                        sendAdded = true;
9401                    }
9402                }
9403            }
9404            if (sendAdded) {
9405                sendPackageAddedForUser(packageName, pkgSetting, userId);
9406                return true;
9407            }
9408            if (sendRemoved) {
9409                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9410                        "hiding pkg");
9411                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9412            }
9413        } finally {
9414            Binder.restoreCallingIdentity(callingId);
9415        }
9416        return false;
9417    }
9418
9419    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9420            int userId) {
9421        final PackageRemovedInfo info = new PackageRemovedInfo();
9422        info.removedPackage = packageName;
9423        info.removedUsers = new int[] {userId};
9424        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9425        info.sendBroadcast(false, false, false);
9426    }
9427
9428    /**
9429     * Returns true if application is not found or there was an error. Otherwise it returns
9430     * the hidden state of the package for the given user.
9431     */
9432    @Override
9433    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9434        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9435        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9436                false, "getApplicationHidden for user " + userId);
9437        PackageSetting pkgSetting;
9438        long callingId = Binder.clearCallingIdentity();
9439        try {
9440            // writer
9441            synchronized (mPackages) {
9442                pkgSetting = mSettings.mPackages.get(packageName);
9443                if (pkgSetting == null) {
9444                    return true;
9445                }
9446                return pkgSetting.getHidden(userId);
9447            }
9448        } finally {
9449            Binder.restoreCallingIdentity(callingId);
9450        }
9451    }
9452
9453    /**
9454     * @hide
9455     */
9456    @Override
9457    public int installExistingPackageAsUser(String packageName, int userId) {
9458        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9459                null);
9460        PackageSetting pkgSetting;
9461        final int uid = Binder.getCallingUid();
9462        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9463                + userId);
9464        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9465            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9466        }
9467
9468        long callingId = Binder.clearCallingIdentity();
9469        try {
9470            boolean sendAdded = false;
9471
9472            // writer
9473            synchronized (mPackages) {
9474                pkgSetting = mSettings.mPackages.get(packageName);
9475                if (pkgSetting == null) {
9476                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9477                }
9478                if (!pkgSetting.getInstalled(userId)) {
9479                    pkgSetting.setInstalled(true, userId);
9480                    pkgSetting.setHidden(false, userId);
9481                    mSettings.writePackageRestrictionsLPr(userId);
9482                    sendAdded = true;
9483                }
9484            }
9485
9486            if (sendAdded) {
9487                sendPackageAddedForUser(packageName, pkgSetting, userId);
9488            }
9489        } finally {
9490            Binder.restoreCallingIdentity(callingId);
9491        }
9492
9493        return PackageManager.INSTALL_SUCCEEDED;
9494    }
9495
9496    boolean isUserRestricted(int userId, String restrictionKey) {
9497        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9498        if (restrictions.getBoolean(restrictionKey, false)) {
9499            Log.w(TAG, "User is restricted: " + restrictionKey);
9500            return true;
9501        }
9502        return false;
9503    }
9504
9505    @Override
9506    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9507        mContext.enforceCallingOrSelfPermission(
9508                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9509                "Only package verification agents can verify applications");
9510
9511        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9512        final PackageVerificationResponse response = new PackageVerificationResponse(
9513                verificationCode, Binder.getCallingUid());
9514        msg.arg1 = id;
9515        msg.obj = response;
9516        mHandler.sendMessage(msg);
9517    }
9518
9519    @Override
9520    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9521            long millisecondsToDelay) {
9522        mContext.enforceCallingOrSelfPermission(
9523                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9524                "Only package verification agents can extend verification timeouts");
9525
9526        final PackageVerificationState state = mPendingVerification.get(id);
9527        final PackageVerificationResponse response = new PackageVerificationResponse(
9528                verificationCodeAtTimeout, Binder.getCallingUid());
9529
9530        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9531            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9532        }
9533        if (millisecondsToDelay < 0) {
9534            millisecondsToDelay = 0;
9535        }
9536        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9537                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9538            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9539        }
9540
9541        if ((state != null) && !state.timeoutExtended()) {
9542            state.extendTimeout();
9543
9544            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9545            msg.arg1 = id;
9546            msg.obj = response;
9547            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9548        }
9549    }
9550
9551    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9552            int verificationCode, UserHandle user) {
9553        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9554        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9555        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9556        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9557        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9558
9559        mContext.sendBroadcastAsUser(intent, user,
9560                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9561    }
9562
9563    private ComponentName matchComponentForVerifier(String packageName,
9564            List<ResolveInfo> receivers) {
9565        ActivityInfo targetReceiver = null;
9566
9567        final int NR = receivers.size();
9568        for (int i = 0; i < NR; i++) {
9569            final ResolveInfo info = receivers.get(i);
9570            if (info.activityInfo == null) {
9571                continue;
9572            }
9573
9574            if (packageName.equals(info.activityInfo.packageName)) {
9575                targetReceiver = info.activityInfo;
9576                break;
9577            }
9578        }
9579
9580        if (targetReceiver == null) {
9581            return null;
9582        }
9583
9584        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9585    }
9586
9587    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9588            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9589        if (pkgInfo.verifiers.length == 0) {
9590            return null;
9591        }
9592
9593        final int N = pkgInfo.verifiers.length;
9594        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9595        for (int i = 0; i < N; i++) {
9596            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9597
9598            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9599                    receivers);
9600            if (comp == null) {
9601                continue;
9602            }
9603
9604            final int verifierUid = getUidForVerifier(verifierInfo);
9605            if (verifierUid == -1) {
9606                continue;
9607            }
9608
9609            if (DEBUG_VERIFY) {
9610                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9611                        + " with the correct signature");
9612            }
9613            sufficientVerifiers.add(comp);
9614            verificationState.addSufficientVerifier(verifierUid);
9615        }
9616
9617        return sufficientVerifiers;
9618    }
9619
9620    private int getUidForVerifier(VerifierInfo verifierInfo) {
9621        synchronized (mPackages) {
9622            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9623            if (pkg == null) {
9624                return -1;
9625            } else if (pkg.mSignatures.length != 1) {
9626                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9627                        + " has more than one signature; ignoring");
9628                return -1;
9629            }
9630
9631            /*
9632             * If the public key of the package's signature does not match
9633             * our expected public key, then this is a different package and
9634             * we should skip.
9635             */
9636
9637            final byte[] expectedPublicKey;
9638            try {
9639                final Signature verifierSig = pkg.mSignatures[0];
9640                final PublicKey publicKey = verifierSig.getPublicKey();
9641                expectedPublicKey = publicKey.getEncoded();
9642            } catch (CertificateException e) {
9643                return -1;
9644            }
9645
9646            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9647
9648            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9649                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9650                        + " does not have the expected public key; ignoring");
9651                return -1;
9652            }
9653
9654            return pkg.applicationInfo.uid;
9655        }
9656    }
9657
9658    @Override
9659    public void finishPackageInstall(int token) {
9660        enforceSystemOrRoot("Only the system is allowed to finish installs");
9661
9662        if (DEBUG_INSTALL) {
9663            Slog.v(TAG, "BM finishing package install for " + token);
9664        }
9665
9666        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9667        mHandler.sendMessage(msg);
9668    }
9669
9670    /**
9671     * Get the verification agent timeout.
9672     *
9673     * @return verification timeout in milliseconds
9674     */
9675    private long getVerificationTimeout() {
9676        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9677                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9678                DEFAULT_VERIFICATION_TIMEOUT);
9679    }
9680
9681    /**
9682     * Get the default verification agent response code.
9683     *
9684     * @return default verification response code
9685     */
9686    private int getDefaultVerificationResponse() {
9687        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9688                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9689                DEFAULT_VERIFICATION_RESPONSE);
9690    }
9691
9692    /**
9693     * Check whether or not package verification has been enabled.
9694     *
9695     * @return true if verification should be performed
9696     */
9697    private boolean isVerificationEnabled(int userId, int installFlags) {
9698        if (!DEFAULT_VERIFY_ENABLE) {
9699            return false;
9700        }
9701
9702        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9703
9704        // Check if installing from ADB
9705        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9706            // Do not run verification in a test harness environment
9707            if (ActivityManager.isRunningInTestHarness()) {
9708                return false;
9709            }
9710            if (ensureVerifyAppsEnabled) {
9711                return true;
9712            }
9713            // Check if the developer does not want package verification for ADB installs
9714            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9715                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9716                return false;
9717            }
9718        }
9719
9720        if (ensureVerifyAppsEnabled) {
9721            return true;
9722        }
9723
9724        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9725                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9726    }
9727
9728    @Override
9729    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9730            throws RemoteException {
9731        mContext.enforceCallingOrSelfPermission(
9732                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9733                "Only intentfilter verification agents can verify applications");
9734
9735        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9736        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9737                Binder.getCallingUid(), verificationCode, failedDomains);
9738        msg.arg1 = id;
9739        msg.obj = response;
9740        mHandler.sendMessage(msg);
9741    }
9742
9743    @Override
9744    public int getIntentVerificationStatus(String packageName, int userId) {
9745        synchronized (mPackages) {
9746            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9747        }
9748    }
9749
9750    @Override
9751    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9752        mContext.enforceCallingOrSelfPermission(
9753                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9754
9755        boolean result = false;
9756        synchronized (mPackages) {
9757            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9758        }
9759        if (result) {
9760            scheduleWritePackageRestrictionsLocked(userId);
9761        }
9762        return result;
9763    }
9764
9765    @Override
9766    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9767        synchronized (mPackages) {
9768            return mSettings.getIntentFilterVerificationsLPr(packageName);
9769        }
9770    }
9771
9772    @Override
9773    public List<IntentFilter> getAllIntentFilters(String packageName) {
9774        if (TextUtils.isEmpty(packageName)) {
9775            return Collections.<IntentFilter>emptyList();
9776        }
9777        synchronized (mPackages) {
9778            PackageParser.Package pkg = mPackages.get(packageName);
9779            if (pkg == null || pkg.activities == null) {
9780                return Collections.<IntentFilter>emptyList();
9781            }
9782            final int count = pkg.activities.size();
9783            ArrayList<IntentFilter> result = new ArrayList<>();
9784            for (int n=0; n<count; n++) {
9785                PackageParser.Activity activity = pkg.activities.get(n);
9786                if (activity.intents != null || activity.intents.size() > 0) {
9787                    result.addAll(activity.intents);
9788                }
9789            }
9790            return result;
9791        }
9792    }
9793
9794    @Override
9795    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9796        mContext.enforceCallingOrSelfPermission(
9797                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9798
9799        synchronized (mPackages) {
9800            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9801            if (packageName != null) {
9802                result |= updateIntentVerificationStatus(packageName,
9803                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9804                        UserHandle.myUserId());
9805                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9806                        packageName, userId);
9807            }
9808            return result;
9809        }
9810    }
9811
9812    @Override
9813    public String getDefaultBrowserPackageName(int userId) {
9814        synchronized (mPackages) {
9815            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9816        }
9817    }
9818
9819    /**
9820     * Get the "allow unknown sources" setting.
9821     *
9822     * @return the current "allow unknown sources" setting
9823     */
9824    private int getUnknownSourcesSettings() {
9825        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9826                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9827                -1);
9828    }
9829
9830    @Override
9831    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9832        final int uid = Binder.getCallingUid();
9833        // writer
9834        synchronized (mPackages) {
9835            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9836            if (targetPackageSetting == null) {
9837                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9838            }
9839
9840            PackageSetting installerPackageSetting;
9841            if (installerPackageName != null) {
9842                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9843                if (installerPackageSetting == null) {
9844                    throw new IllegalArgumentException("Unknown installer package: "
9845                            + installerPackageName);
9846                }
9847            } else {
9848                installerPackageSetting = null;
9849            }
9850
9851            Signature[] callerSignature;
9852            Object obj = mSettings.getUserIdLPr(uid);
9853            if (obj != null) {
9854                if (obj instanceof SharedUserSetting) {
9855                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9856                } else if (obj instanceof PackageSetting) {
9857                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9858                } else {
9859                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9860                }
9861            } else {
9862                throw new SecurityException("Unknown calling uid " + uid);
9863            }
9864
9865            // Verify: can't set installerPackageName to a package that is
9866            // not signed with the same cert as the caller.
9867            if (installerPackageSetting != null) {
9868                if (compareSignatures(callerSignature,
9869                        installerPackageSetting.signatures.mSignatures)
9870                        != PackageManager.SIGNATURE_MATCH) {
9871                    throw new SecurityException(
9872                            "Caller does not have same cert as new installer package "
9873                            + installerPackageName);
9874                }
9875            }
9876
9877            // Verify: if target already has an installer package, it must
9878            // be signed with the same cert as the caller.
9879            if (targetPackageSetting.installerPackageName != null) {
9880                PackageSetting setting = mSettings.mPackages.get(
9881                        targetPackageSetting.installerPackageName);
9882                // If the currently set package isn't valid, then it's always
9883                // okay to change it.
9884                if (setting != null) {
9885                    if (compareSignatures(callerSignature,
9886                            setting.signatures.mSignatures)
9887                            != PackageManager.SIGNATURE_MATCH) {
9888                        throw new SecurityException(
9889                                "Caller does not have same cert as old installer package "
9890                                + targetPackageSetting.installerPackageName);
9891                    }
9892                }
9893            }
9894
9895            // Okay!
9896            targetPackageSetting.installerPackageName = installerPackageName;
9897            scheduleWriteSettingsLocked();
9898        }
9899    }
9900
9901    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9902        // Queue up an async operation since the package installation may take a little while.
9903        mHandler.post(new Runnable() {
9904            public void run() {
9905                mHandler.removeCallbacks(this);
9906                 // Result object to be returned
9907                PackageInstalledInfo res = new PackageInstalledInfo();
9908                res.returnCode = currentStatus;
9909                res.uid = -1;
9910                res.pkg = null;
9911                res.removedInfo = new PackageRemovedInfo();
9912                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9913                    args.doPreInstall(res.returnCode);
9914                    synchronized (mInstallLock) {
9915                        installPackageLI(args, res);
9916                    }
9917                    args.doPostInstall(res.returnCode, res.uid);
9918                }
9919
9920                // A restore should be performed at this point if (a) the install
9921                // succeeded, (b) the operation is not an update, and (c) the new
9922                // package has not opted out of backup participation.
9923                final boolean update = res.removedInfo.removedPackage != null;
9924                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9925                boolean doRestore = !update
9926                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9927
9928                // Set up the post-install work request bookkeeping.  This will be used
9929                // and cleaned up by the post-install event handling regardless of whether
9930                // there's a restore pass performed.  Token values are >= 1.
9931                int token;
9932                if (mNextInstallToken < 0) mNextInstallToken = 1;
9933                token = mNextInstallToken++;
9934
9935                PostInstallData data = new PostInstallData(args, res);
9936                mRunningInstalls.put(token, data);
9937                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9938
9939                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9940                    // Pass responsibility to the Backup Manager.  It will perform a
9941                    // restore if appropriate, then pass responsibility back to the
9942                    // Package Manager to run the post-install observer callbacks
9943                    // and broadcasts.
9944                    IBackupManager bm = IBackupManager.Stub.asInterface(
9945                            ServiceManager.getService(Context.BACKUP_SERVICE));
9946                    if (bm != null) {
9947                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9948                                + " to BM for possible restore");
9949                        try {
9950                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9951                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9952                            } else {
9953                                doRestore = false;
9954                            }
9955                        } catch (RemoteException e) {
9956                            // can't happen; the backup manager is local
9957                        } catch (Exception e) {
9958                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9959                            doRestore = false;
9960                        }
9961                    } else {
9962                        Slog.e(TAG, "Backup Manager not found!");
9963                        doRestore = false;
9964                    }
9965                }
9966
9967                if (!doRestore) {
9968                    // No restore possible, or the Backup Manager was mysteriously not
9969                    // available -- just fire the post-install work request directly.
9970                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9971                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9972                    mHandler.sendMessage(msg);
9973                }
9974            }
9975        });
9976    }
9977
9978    private abstract class HandlerParams {
9979        private static final int MAX_RETRIES = 4;
9980
9981        /**
9982         * Number of times startCopy() has been attempted and had a non-fatal
9983         * error.
9984         */
9985        private int mRetries = 0;
9986
9987        /** User handle for the user requesting the information or installation. */
9988        private final UserHandle mUser;
9989
9990        HandlerParams(UserHandle user) {
9991            mUser = user;
9992        }
9993
9994        UserHandle getUser() {
9995            return mUser;
9996        }
9997
9998        final boolean startCopy() {
9999            boolean res;
10000            try {
10001                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10002
10003                if (++mRetries > MAX_RETRIES) {
10004                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10005                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10006                    handleServiceError();
10007                    return false;
10008                } else {
10009                    handleStartCopy();
10010                    res = true;
10011                }
10012            } catch (RemoteException e) {
10013                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10014                mHandler.sendEmptyMessage(MCS_RECONNECT);
10015                res = false;
10016            }
10017            handleReturnCode();
10018            return res;
10019        }
10020
10021        final void serviceError() {
10022            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10023            handleServiceError();
10024            handleReturnCode();
10025        }
10026
10027        abstract void handleStartCopy() throws RemoteException;
10028        abstract void handleServiceError();
10029        abstract void handleReturnCode();
10030    }
10031
10032    class MeasureParams extends HandlerParams {
10033        private final PackageStats mStats;
10034        private boolean mSuccess;
10035
10036        private final IPackageStatsObserver mObserver;
10037
10038        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10039            super(new UserHandle(stats.userHandle));
10040            mObserver = observer;
10041            mStats = stats;
10042        }
10043
10044        @Override
10045        public String toString() {
10046            return "MeasureParams{"
10047                + Integer.toHexString(System.identityHashCode(this))
10048                + " " + mStats.packageName + "}";
10049        }
10050
10051        @Override
10052        void handleStartCopy() throws RemoteException {
10053            synchronized (mInstallLock) {
10054                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10055            }
10056
10057            if (mSuccess) {
10058                final boolean mounted;
10059                if (Environment.isExternalStorageEmulated()) {
10060                    mounted = true;
10061                } else {
10062                    final String status = Environment.getExternalStorageState();
10063                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10064                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10065                }
10066
10067                if (mounted) {
10068                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10069
10070                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10071                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10072
10073                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10074                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10075
10076                    // Always subtract cache size, since it's a subdirectory
10077                    mStats.externalDataSize -= mStats.externalCacheSize;
10078
10079                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10080                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10081
10082                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10083                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10084                }
10085            }
10086        }
10087
10088        @Override
10089        void handleReturnCode() {
10090            if (mObserver != null) {
10091                try {
10092                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10093                } catch (RemoteException e) {
10094                    Slog.i(TAG, "Observer no longer exists.");
10095                }
10096            }
10097        }
10098
10099        @Override
10100        void handleServiceError() {
10101            Slog.e(TAG, "Could not measure application " + mStats.packageName
10102                            + " external storage");
10103        }
10104    }
10105
10106    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10107            throws RemoteException {
10108        long result = 0;
10109        for (File path : paths) {
10110            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10111        }
10112        return result;
10113    }
10114
10115    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10116        for (File path : paths) {
10117            try {
10118                mcs.clearDirectory(path.getAbsolutePath());
10119            } catch (RemoteException e) {
10120            }
10121        }
10122    }
10123
10124    static class OriginInfo {
10125        /**
10126         * Location where install is coming from, before it has been
10127         * copied/renamed into place. This could be a single monolithic APK
10128         * file, or a cluster directory. This location may be untrusted.
10129         */
10130        final File file;
10131        final String cid;
10132
10133        /**
10134         * Flag indicating that {@link #file} or {@link #cid} has already been
10135         * staged, meaning downstream users don't need to defensively copy the
10136         * contents.
10137         */
10138        final boolean staged;
10139
10140        /**
10141         * Flag indicating that {@link #file} or {@link #cid} is an already
10142         * installed app that is being moved.
10143         */
10144        final boolean existing;
10145
10146        final String resolvedPath;
10147        final File resolvedFile;
10148
10149        static OriginInfo fromNothing() {
10150            return new OriginInfo(null, null, false, false);
10151        }
10152
10153        static OriginInfo fromUntrustedFile(File file) {
10154            return new OriginInfo(file, null, false, false);
10155        }
10156
10157        static OriginInfo fromExistingFile(File file) {
10158            return new OriginInfo(file, null, false, true);
10159        }
10160
10161        static OriginInfo fromStagedFile(File file) {
10162            return new OriginInfo(file, null, true, false);
10163        }
10164
10165        static OriginInfo fromStagedContainer(String cid) {
10166            return new OriginInfo(null, cid, true, false);
10167        }
10168
10169        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10170            this.file = file;
10171            this.cid = cid;
10172            this.staged = staged;
10173            this.existing = existing;
10174
10175            if (cid != null) {
10176                resolvedPath = PackageHelper.getSdDir(cid);
10177                resolvedFile = new File(resolvedPath);
10178            } else if (file != null) {
10179                resolvedPath = file.getAbsolutePath();
10180                resolvedFile = file;
10181            } else {
10182                resolvedPath = null;
10183                resolvedFile = null;
10184            }
10185        }
10186    }
10187
10188    class MoveInfo {
10189        final int moveId;
10190        final String fromUuid;
10191        final String toUuid;
10192        final String packageName;
10193        final String dataAppName;
10194        final int appId;
10195        final String seinfo;
10196
10197        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10198                String dataAppName, int appId, String seinfo) {
10199            this.moveId = moveId;
10200            this.fromUuid = fromUuid;
10201            this.toUuid = toUuid;
10202            this.packageName = packageName;
10203            this.dataAppName = dataAppName;
10204            this.appId = appId;
10205            this.seinfo = seinfo;
10206        }
10207    }
10208
10209    class InstallParams extends HandlerParams {
10210        final OriginInfo origin;
10211        final MoveInfo move;
10212        final IPackageInstallObserver2 observer;
10213        int installFlags;
10214        final String installerPackageName;
10215        final String volumeUuid;
10216        final VerificationParams verificationParams;
10217        private InstallArgs mArgs;
10218        private int mRet;
10219        final String packageAbiOverride;
10220
10221        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10222                int installFlags, String installerPackageName, String volumeUuid,
10223                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10224            super(user);
10225            this.origin = origin;
10226            this.move = move;
10227            this.observer = observer;
10228            this.installFlags = installFlags;
10229            this.installerPackageName = installerPackageName;
10230            this.volumeUuid = volumeUuid;
10231            this.verificationParams = verificationParams;
10232            this.packageAbiOverride = packageAbiOverride;
10233        }
10234
10235        @Override
10236        public String toString() {
10237            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10238                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10239        }
10240
10241        public ManifestDigest getManifestDigest() {
10242            if (verificationParams == null) {
10243                return null;
10244            }
10245            return verificationParams.getManifestDigest();
10246        }
10247
10248        private int installLocationPolicy(PackageInfoLite pkgLite) {
10249            String packageName = pkgLite.packageName;
10250            int installLocation = pkgLite.installLocation;
10251            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10252            // reader
10253            synchronized (mPackages) {
10254                PackageParser.Package pkg = mPackages.get(packageName);
10255                if (pkg != null) {
10256                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10257                        // Check for downgrading.
10258                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10259                            try {
10260                                checkDowngrade(pkg, pkgLite);
10261                            } catch (PackageManagerException e) {
10262                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10263                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10264                            }
10265                        }
10266                        // Check for updated system application.
10267                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10268                            if (onSd) {
10269                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10270                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10271                            }
10272                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10273                        } else {
10274                            if (onSd) {
10275                                // Install flag overrides everything.
10276                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10277                            }
10278                            // If current upgrade specifies particular preference
10279                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10280                                // Application explicitly specified internal.
10281                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10282                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10283                                // App explictly prefers external. Let policy decide
10284                            } else {
10285                                // Prefer previous location
10286                                if (isExternal(pkg)) {
10287                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10288                                }
10289                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10290                            }
10291                        }
10292                    } else {
10293                        // Invalid install. Return error code
10294                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10295                    }
10296                }
10297            }
10298            // All the special cases have been taken care of.
10299            // Return result based on recommended install location.
10300            if (onSd) {
10301                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10302            }
10303            return pkgLite.recommendedInstallLocation;
10304        }
10305
10306        /*
10307         * Invoke remote method to get package information and install
10308         * location values. Override install location based on default
10309         * policy if needed and then create install arguments based
10310         * on the install location.
10311         */
10312        public void handleStartCopy() throws RemoteException {
10313            int ret = PackageManager.INSTALL_SUCCEEDED;
10314
10315            // If we're already staged, we've firmly committed to an install location
10316            if (origin.staged) {
10317                if (origin.file != null) {
10318                    installFlags |= PackageManager.INSTALL_INTERNAL;
10319                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10320                } else if (origin.cid != null) {
10321                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10322                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10323                } else {
10324                    throw new IllegalStateException("Invalid stage location");
10325                }
10326            }
10327
10328            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10329            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10330
10331            PackageInfoLite pkgLite = null;
10332
10333            if (onInt && onSd) {
10334                // Check if both bits are set.
10335                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10336                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10337            } else {
10338                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10339                        packageAbiOverride);
10340
10341                /*
10342                 * If we have too little free space, try to free cache
10343                 * before giving up.
10344                 */
10345                if (!origin.staged && pkgLite.recommendedInstallLocation
10346                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10347                    // TODO: focus freeing disk space on the target device
10348                    final StorageManager storage = StorageManager.from(mContext);
10349                    final long lowThreshold = storage.getStorageLowBytes(
10350                            Environment.getDataDirectory());
10351
10352                    final long sizeBytes = mContainerService.calculateInstalledSize(
10353                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10354
10355                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10356                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10357                                installFlags, packageAbiOverride);
10358                    }
10359
10360                    /*
10361                     * The cache free must have deleted the file we
10362                     * downloaded to install.
10363                     *
10364                     * TODO: fix the "freeCache" call to not delete
10365                     *       the file we care about.
10366                     */
10367                    if (pkgLite.recommendedInstallLocation
10368                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10369                        pkgLite.recommendedInstallLocation
10370                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10371                    }
10372                }
10373            }
10374
10375            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10376                int loc = pkgLite.recommendedInstallLocation;
10377                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10378                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10379                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10380                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10381                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10382                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10383                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10384                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10385                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10386                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10387                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10388                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10389                } else {
10390                    // Override with defaults if needed.
10391                    loc = installLocationPolicy(pkgLite);
10392                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10393                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10394                    } else if (!onSd && !onInt) {
10395                        // Override install location with flags
10396                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10397                            // Set the flag to install on external media.
10398                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10399                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10400                        } else {
10401                            // Make sure the flag for installing on external
10402                            // media is unset
10403                            installFlags |= PackageManager.INSTALL_INTERNAL;
10404                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10405                        }
10406                    }
10407                }
10408            }
10409
10410            final InstallArgs args = createInstallArgs(this);
10411            mArgs = args;
10412
10413            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10414                 /*
10415                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10416                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10417                 */
10418                int userIdentifier = getUser().getIdentifier();
10419                if (userIdentifier == UserHandle.USER_ALL
10420                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10421                    userIdentifier = UserHandle.USER_OWNER;
10422                }
10423
10424                /*
10425                 * Determine if we have any installed package verifiers. If we
10426                 * do, then we'll defer to them to verify the packages.
10427                 */
10428                final int requiredUid = mRequiredVerifierPackage == null ? -1
10429                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10430                if (!origin.existing && requiredUid != -1
10431                        && isVerificationEnabled(userIdentifier, installFlags)) {
10432                    final Intent verification = new Intent(
10433                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10434                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10435                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10436                            PACKAGE_MIME_TYPE);
10437                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10438
10439                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10440                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10441                            0 /* TODO: Which userId? */);
10442
10443                    if (DEBUG_VERIFY) {
10444                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10445                                + verification.toString() + " with " + pkgLite.verifiers.length
10446                                + " optional verifiers");
10447                    }
10448
10449                    final int verificationId = mPendingVerificationToken++;
10450
10451                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10452
10453                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10454                            installerPackageName);
10455
10456                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10457                            installFlags);
10458
10459                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10460                            pkgLite.packageName);
10461
10462                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10463                            pkgLite.versionCode);
10464
10465                    if (verificationParams != null) {
10466                        if (verificationParams.getVerificationURI() != null) {
10467                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10468                                 verificationParams.getVerificationURI());
10469                        }
10470                        if (verificationParams.getOriginatingURI() != null) {
10471                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10472                                  verificationParams.getOriginatingURI());
10473                        }
10474                        if (verificationParams.getReferrer() != null) {
10475                            verification.putExtra(Intent.EXTRA_REFERRER,
10476                                  verificationParams.getReferrer());
10477                        }
10478                        if (verificationParams.getOriginatingUid() >= 0) {
10479                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10480                                  verificationParams.getOriginatingUid());
10481                        }
10482                        if (verificationParams.getInstallerUid() >= 0) {
10483                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10484                                  verificationParams.getInstallerUid());
10485                        }
10486                    }
10487
10488                    final PackageVerificationState verificationState = new PackageVerificationState(
10489                            requiredUid, args);
10490
10491                    mPendingVerification.append(verificationId, verificationState);
10492
10493                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10494                            receivers, verificationState);
10495
10496                    /*
10497                     * If any sufficient verifiers were listed in the package
10498                     * manifest, attempt to ask them.
10499                     */
10500                    if (sufficientVerifiers != null) {
10501                        final int N = sufficientVerifiers.size();
10502                        if (N == 0) {
10503                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10504                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10505                        } else {
10506                            for (int i = 0; i < N; i++) {
10507                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10508
10509                                final Intent sufficientIntent = new Intent(verification);
10510                                sufficientIntent.setComponent(verifierComponent);
10511
10512                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10513                            }
10514                        }
10515                    }
10516
10517                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10518                            mRequiredVerifierPackage, receivers);
10519                    if (ret == PackageManager.INSTALL_SUCCEEDED
10520                            && mRequiredVerifierPackage != null) {
10521                        /*
10522                         * Send the intent to the required verification agent,
10523                         * but only start the verification timeout after the
10524                         * target BroadcastReceivers have run.
10525                         */
10526                        verification.setComponent(requiredVerifierComponent);
10527                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10528                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10529                                new BroadcastReceiver() {
10530                                    @Override
10531                                    public void onReceive(Context context, Intent intent) {
10532                                        final Message msg = mHandler
10533                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10534                                        msg.arg1 = verificationId;
10535                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10536                                    }
10537                                }, null, 0, null, null);
10538
10539                        /*
10540                         * We don't want the copy to proceed until verification
10541                         * succeeds, so null out this field.
10542                         */
10543                        mArgs = null;
10544                    }
10545                } else {
10546                    /*
10547                     * No package verification is enabled, so immediately start
10548                     * the remote call to initiate copy using temporary file.
10549                     */
10550                    ret = args.copyApk(mContainerService, true);
10551                }
10552            }
10553
10554            mRet = ret;
10555        }
10556
10557        @Override
10558        void handleReturnCode() {
10559            // If mArgs is null, then MCS couldn't be reached. When it
10560            // reconnects, it will try again to install. At that point, this
10561            // will succeed.
10562            if (mArgs != null) {
10563                processPendingInstall(mArgs, mRet);
10564            }
10565        }
10566
10567        @Override
10568        void handleServiceError() {
10569            mArgs = createInstallArgs(this);
10570            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10571        }
10572
10573        public boolean isForwardLocked() {
10574            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10575        }
10576    }
10577
10578    /**
10579     * Used during creation of InstallArgs
10580     *
10581     * @param installFlags package installation flags
10582     * @return true if should be installed on external storage
10583     */
10584    private static boolean installOnExternalAsec(int installFlags) {
10585        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10586            return false;
10587        }
10588        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10589            return true;
10590        }
10591        return false;
10592    }
10593
10594    /**
10595     * Used during creation of InstallArgs
10596     *
10597     * @param installFlags package installation flags
10598     * @return true if should be installed as forward locked
10599     */
10600    private static boolean installForwardLocked(int installFlags) {
10601        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10602    }
10603
10604    private InstallArgs createInstallArgs(InstallParams params) {
10605        if (params.move != null) {
10606            return new MoveInstallArgs(params);
10607        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10608            return new AsecInstallArgs(params);
10609        } else {
10610            return new FileInstallArgs(params);
10611        }
10612    }
10613
10614    /**
10615     * Create args that describe an existing installed package. Typically used
10616     * when cleaning up old installs, or used as a move source.
10617     */
10618    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10619            String resourcePath, String[] instructionSets) {
10620        final boolean isInAsec;
10621        if (installOnExternalAsec(installFlags)) {
10622            /* Apps on SD card are always in ASEC containers. */
10623            isInAsec = true;
10624        } else if (installForwardLocked(installFlags)
10625                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10626            /*
10627             * Forward-locked apps are only in ASEC containers if they're the
10628             * new style
10629             */
10630            isInAsec = true;
10631        } else {
10632            isInAsec = false;
10633        }
10634
10635        if (isInAsec) {
10636            return new AsecInstallArgs(codePath, instructionSets,
10637                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10638        } else {
10639            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10640        }
10641    }
10642
10643    static abstract class InstallArgs {
10644        /** @see InstallParams#origin */
10645        final OriginInfo origin;
10646        /** @see InstallParams#move */
10647        final MoveInfo move;
10648
10649        final IPackageInstallObserver2 observer;
10650        // Always refers to PackageManager flags only
10651        final int installFlags;
10652        final String installerPackageName;
10653        final String volumeUuid;
10654        final ManifestDigest manifestDigest;
10655        final UserHandle user;
10656        final String abiOverride;
10657
10658        // The list of instruction sets supported by this app. This is currently
10659        // only used during the rmdex() phase to clean up resources. We can get rid of this
10660        // if we move dex files under the common app path.
10661        /* nullable */ String[] instructionSets;
10662
10663        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10664                int installFlags, String installerPackageName, String volumeUuid,
10665                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10666                String abiOverride) {
10667            this.origin = origin;
10668            this.move = move;
10669            this.installFlags = installFlags;
10670            this.observer = observer;
10671            this.installerPackageName = installerPackageName;
10672            this.volumeUuid = volumeUuid;
10673            this.manifestDigest = manifestDigest;
10674            this.user = user;
10675            this.instructionSets = instructionSets;
10676            this.abiOverride = abiOverride;
10677        }
10678
10679        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10680        abstract int doPreInstall(int status);
10681
10682        /**
10683         * Rename package into final resting place. All paths on the given
10684         * scanned package should be updated to reflect the rename.
10685         */
10686        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10687        abstract int doPostInstall(int status, int uid);
10688
10689        /** @see PackageSettingBase#codePathString */
10690        abstract String getCodePath();
10691        /** @see PackageSettingBase#resourcePathString */
10692        abstract String getResourcePath();
10693
10694        // Need installer lock especially for dex file removal.
10695        abstract void cleanUpResourcesLI();
10696        abstract boolean doPostDeleteLI(boolean delete);
10697
10698        /**
10699         * Called before the source arguments are copied. This is used mostly
10700         * for MoveParams when it needs to read the source file to put it in the
10701         * destination.
10702         */
10703        int doPreCopy() {
10704            return PackageManager.INSTALL_SUCCEEDED;
10705        }
10706
10707        /**
10708         * Called after the source arguments are copied. This is used mostly for
10709         * MoveParams when it needs to read the source file to put it in the
10710         * destination.
10711         *
10712         * @return
10713         */
10714        int doPostCopy(int uid) {
10715            return PackageManager.INSTALL_SUCCEEDED;
10716        }
10717
10718        protected boolean isFwdLocked() {
10719            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10720        }
10721
10722        protected boolean isExternalAsec() {
10723            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10724        }
10725
10726        UserHandle getUser() {
10727            return user;
10728        }
10729    }
10730
10731    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10732        if (!allCodePaths.isEmpty()) {
10733            if (instructionSets == null) {
10734                throw new IllegalStateException("instructionSet == null");
10735            }
10736            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10737            for (String codePath : allCodePaths) {
10738                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10739                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10740                    if (retCode < 0) {
10741                        Slog.w(TAG, "Couldn't remove dex file for package: "
10742                                + " at location " + codePath + ", retcode=" + retCode);
10743                        // we don't consider this to be a failure of the core package deletion
10744                    }
10745                }
10746            }
10747        }
10748    }
10749
10750    /**
10751     * Logic to handle installation of non-ASEC applications, including copying
10752     * and renaming logic.
10753     */
10754    class FileInstallArgs extends InstallArgs {
10755        private File codeFile;
10756        private File resourceFile;
10757
10758        // Example topology:
10759        // /data/app/com.example/base.apk
10760        // /data/app/com.example/split_foo.apk
10761        // /data/app/com.example/lib/arm/libfoo.so
10762        // /data/app/com.example/lib/arm64/libfoo.so
10763        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10764
10765        /** New install */
10766        FileInstallArgs(InstallParams params) {
10767            super(params.origin, params.move, params.observer, params.installFlags,
10768                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10769                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10770            if (isFwdLocked()) {
10771                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10772            }
10773        }
10774
10775        /** Existing install */
10776        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10777            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10778                    null);
10779            this.codeFile = (codePath != null) ? new File(codePath) : null;
10780            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10781        }
10782
10783        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10784            if (origin.staged) {
10785                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10786                codeFile = origin.file;
10787                resourceFile = origin.file;
10788                return PackageManager.INSTALL_SUCCEEDED;
10789            }
10790
10791            try {
10792                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10793                codeFile = tempDir;
10794                resourceFile = tempDir;
10795            } catch (IOException e) {
10796                Slog.w(TAG, "Failed to create copy file: " + e);
10797                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10798            }
10799
10800            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10801                @Override
10802                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10803                    if (!FileUtils.isValidExtFilename(name)) {
10804                        throw new IllegalArgumentException("Invalid filename: " + name);
10805                    }
10806                    try {
10807                        final File file = new File(codeFile, name);
10808                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10809                                O_RDWR | O_CREAT, 0644);
10810                        Os.chmod(file.getAbsolutePath(), 0644);
10811                        return new ParcelFileDescriptor(fd);
10812                    } catch (ErrnoException e) {
10813                        throw new RemoteException("Failed to open: " + e.getMessage());
10814                    }
10815                }
10816            };
10817
10818            int ret = PackageManager.INSTALL_SUCCEEDED;
10819            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10820            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10821                Slog.e(TAG, "Failed to copy package");
10822                return ret;
10823            }
10824
10825            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10826            NativeLibraryHelper.Handle handle = null;
10827            try {
10828                handle = NativeLibraryHelper.Handle.create(codeFile);
10829                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10830                        abiOverride);
10831            } catch (IOException e) {
10832                Slog.e(TAG, "Copying native libraries failed", e);
10833                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10834            } finally {
10835                IoUtils.closeQuietly(handle);
10836            }
10837
10838            return ret;
10839        }
10840
10841        int doPreInstall(int status) {
10842            if (status != PackageManager.INSTALL_SUCCEEDED) {
10843                cleanUp();
10844            }
10845            return status;
10846        }
10847
10848        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10849            if (status != PackageManager.INSTALL_SUCCEEDED) {
10850                cleanUp();
10851                return false;
10852            }
10853
10854            final File targetDir = codeFile.getParentFile();
10855            final File beforeCodeFile = codeFile;
10856            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10857
10858            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10859            try {
10860                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10861            } catch (ErrnoException e) {
10862                Slog.w(TAG, "Failed to rename", e);
10863                return false;
10864            }
10865
10866            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10867                Slog.w(TAG, "Failed to restorecon");
10868                return false;
10869            }
10870
10871            // Reflect the rename internally
10872            codeFile = afterCodeFile;
10873            resourceFile = afterCodeFile;
10874
10875            // Reflect the rename in scanned details
10876            pkg.codePath = afterCodeFile.getAbsolutePath();
10877            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10878                    pkg.baseCodePath);
10879            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10880                    pkg.splitCodePaths);
10881
10882            // Reflect the rename in app info
10883            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10884            pkg.applicationInfo.setCodePath(pkg.codePath);
10885            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10886            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10887            pkg.applicationInfo.setResourcePath(pkg.codePath);
10888            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10889            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10890
10891            return true;
10892        }
10893
10894        int doPostInstall(int status, int uid) {
10895            if (status != PackageManager.INSTALL_SUCCEEDED) {
10896                cleanUp();
10897            }
10898            return status;
10899        }
10900
10901        @Override
10902        String getCodePath() {
10903            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10904        }
10905
10906        @Override
10907        String getResourcePath() {
10908            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10909        }
10910
10911        private boolean cleanUp() {
10912            if (codeFile == null || !codeFile.exists()) {
10913                return false;
10914            }
10915
10916            if (codeFile.isDirectory()) {
10917                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10918            } else {
10919                codeFile.delete();
10920            }
10921
10922            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10923                resourceFile.delete();
10924            }
10925
10926            return true;
10927        }
10928
10929        void cleanUpResourcesLI() {
10930            // Try enumerating all code paths before deleting
10931            List<String> allCodePaths = Collections.EMPTY_LIST;
10932            if (codeFile != null && codeFile.exists()) {
10933                try {
10934                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10935                    allCodePaths = pkg.getAllCodePaths();
10936                } catch (PackageParserException e) {
10937                    // Ignored; we tried our best
10938                }
10939            }
10940
10941            cleanUp();
10942            removeDexFiles(allCodePaths, instructionSets);
10943        }
10944
10945        boolean doPostDeleteLI(boolean delete) {
10946            // XXX err, shouldn't we respect the delete flag?
10947            cleanUpResourcesLI();
10948            return true;
10949        }
10950    }
10951
10952    private boolean isAsecExternal(String cid) {
10953        final String asecPath = PackageHelper.getSdFilesystem(cid);
10954        return !asecPath.startsWith(mAsecInternalPath);
10955    }
10956
10957    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10958            PackageManagerException {
10959        if (copyRet < 0) {
10960            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10961                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10962                throw new PackageManagerException(copyRet, message);
10963            }
10964        }
10965    }
10966
10967    /**
10968     * Extract the MountService "container ID" from the full code path of an
10969     * .apk.
10970     */
10971    static String cidFromCodePath(String fullCodePath) {
10972        int eidx = fullCodePath.lastIndexOf("/");
10973        String subStr1 = fullCodePath.substring(0, eidx);
10974        int sidx = subStr1.lastIndexOf("/");
10975        return subStr1.substring(sidx+1, eidx);
10976    }
10977
10978    /**
10979     * Logic to handle installation of ASEC applications, including copying and
10980     * renaming logic.
10981     */
10982    class AsecInstallArgs extends InstallArgs {
10983        static final String RES_FILE_NAME = "pkg.apk";
10984        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10985
10986        String cid;
10987        String packagePath;
10988        String resourcePath;
10989
10990        /** New install */
10991        AsecInstallArgs(InstallParams params) {
10992            super(params.origin, params.move, params.observer, params.installFlags,
10993                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10994                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10995        }
10996
10997        /** Existing install */
10998        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10999                        boolean isExternal, boolean isForwardLocked) {
11000            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11001                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11002                    instructionSets, null);
11003            // Hackily pretend we're still looking at a full code path
11004            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11005                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11006            }
11007
11008            // Extract cid from fullCodePath
11009            int eidx = fullCodePath.lastIndexOf("/");
11010            String subStr1 = fullCodePath.substring(0, eidx);
11011            int sidx = subStr1.lastIndexOf("/");
11012            cid = subStr1.substring(sidx+1, eidx);
11013            setMountPath(subStr1);
11014        }
11015
11016        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11017            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11018                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11019                    instructionSets, null);
11020            this.cid = cid;
11021            setMountPath(PackageHelper.getSdDir(cid));
11022        }
11023
11024        void createCopyFile() {
11025            cid = mInstallerService.allocateExternalStageCidLegacy();
11026        }
11027
11028        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11029            if (origin.staged) {
11030                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11031                cid = origin.cid;
11032                setMountPath(PackageHelper.getSdDir(cid));
11033                return PackageManager.INSTALL_SUCCEEDED;
11034            }
11035
11036            if (temp) {
11037                createCopyFile();
11038            } else {
11039                /*
11040                 * Pre-emptively destroy the container since it's destroyed if
11041                 * copying fails due to it existing anyway.
11042                 */
11043                PackageHelper.destroySdDir(cid);
11044            }
11045
11046            final String newMountPath = imcs.copyPackageToContainer(
11047                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11048                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11049
11050            if (newMountPath != null) {
11051                setMountPath(newMountPath);
11052                return PackageManager.INSTALL_SUCCEEDED;
11053            } else {
11054                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11055            }
11056        }
11057
11058        @Override
11059        String getCodePath() {
11060            return packagePath;
11061        }
11062
11063        @Override
11064        String getResourcePath() {
11065            return resourcePath;
11066        }
11067
11068        int doPreInstall(int status) {
11069            if (status != PackageManager.INSTALL_SUCCEEDED) {
11070                // Destroy container
11071                PackageHelper.destroySdDir(cid);
11072            } else {
11073                boolean mounted = PackageHelper.isContainerMounted(cid);
11074                if (!mounted) {
11075                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11076                            Process.SYSTEM_UID);
11077                    if (newMountPath != null) {
11078                        setMountPath(newMountPath);
11079                    } else {
11080                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11081                    }
11082                }
11083            }
11084            return status;
11085        }
11086
11087        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11088            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11089            String newMountPath = null;
11090            if (PackageHelper.isContainerMounted(cid)) {
11091                // Unmount the container
11092                if (!PackageHelper.unMountSdDir(cid)) {
11093                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11094                    return false;
11095                }
11096            }
11097            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11098                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11099                        " which might be stale. Will try to clean up.");
11100                // Clean up the stale container and proceed to recreate.
11101                if (!PackageHelper.destroySdDir(newCacheId)) {
11102                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11103                    return false;
11104                }
11105                // Successfully cleaned up stale container. Try to rename again.
11106                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11107                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11108                            + " inspite of cleaning it up.");
11109                    return false;
11110                }
11111            }
11112            if (!PackageHelper.isContainerMounted(newCacheId)) {
11113                Slog.w(TAG, "Mounting container " + newCacheId);
11114                newMountPath = PackageHelper.mountSdDir(newCacheId,
11115                        getEncryptKey(), Process.SYSTEM_UID);
11116            } else {
11117                newMountPath = PackageHelper.getSdDir(newCacheId);
11118            }
11119            if (newMountPath == null) {
11120                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11121                return false;
11122            }
11123            Log.i(TAG, "Succesfully renamed " + cid +
11124                    " to " + newCacheId +
11125                    " at new path: " + newMountPath);
11126            cid = newCacheId;
11127
11128            final File beforeCodeFile = new File(packagePath);
11129            setMountPath(newMountPath);
11130            final File afterCodeFile = new File(packagePath);
11131
11132            // Reflect the rename in scanned details
11133            pkg.codePath = afterCodeFile.getAbsolutePath();
11134            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11135                    pkg.baseCodePath);
11136            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11137                    pkg.splitCodePaths);
11138
11139            // Reflect the rename in app info
11140            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11141            pkg.applicationInfo.setCodePath(pkg.codePath);
11142            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11143            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11144            pkg.applicationInfo.setResourcePath(pkg.codePath);
11145            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11146            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11147
11148            return true;
11149        }
11150
11151        private void setMountPath(String mountPath) {
11152            final File mountFile = new File(mountPath);
11153
11154            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11155            if (monolithicFile.exists()) {
11156                packagePath = monolithicFile.getAbsolutePath();
11157                if (isFwdLocked()) {
11158                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11159                } else {
11160                    resourcePath = packagePath;
11161                }
11162            } else {
11163                packagePath = mountFile.getAbsolutePath();
11164                resourcePath = packagePath;
11165            }
11166        }
11167
11168        int doPostInstall(int status, int uid) {
11169            if (status != PackageManager.INSTALL_SUCCEEDED) {
11170                cleanUp();
11171            } else {
11172                final int groupOwner;
11173                final String protectedFile;
11174                if (isFwdLocked()) {
11175                    groupOwner = UserHandle.getSharedAppGid(uid);
11176                    protectedFile = RES_FILE_NAME;
11177                } else {
11178                    groupOwner = -1;
11179                    protectedFile = null;
11180                }
11181
11182                if (uid < Process.FIRST_APPLICATION_UID
11183                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11184                    Slog.e(TAG, "Failed to finalize " + cid);
11185                    PackageHelper.destroySdDir(cid);
11186                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11187                }
11188
11189                boolean mounted = PackageHelper.isContainerMounted(cid);
11190                if (!mounted) {
11191                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11192                }
11193            }
11194            return status;
11195        }
11196
11197        private void cleanUp() {
11198            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11199
11200            // Destroy secure container
11201            PackageHelper.destroySdDir(cid);
11202        }
11203
11204        private List<String> getAllCodePaths() {
11205            final File codeFile = new File(getCodePath());
11206            if (codeFile != null && codeFile.exists()) {
11207                try {
11208                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11209                    return pkg.getAllCodePaths();
11210                } catch (PackageParserException e) {
11211                    // Ignored; we tried our best
11212                }
11213            }
11214            return Collections.EMPTY_LIST;
11215        }
11216
11217        void cleanUpResourcesLI() {
11218            // Enumerate all code paths before deleting
11219            cleanUpResourcesLI(getAllCodePaths());
11220        }
11221
11222        private void cleanUpResourcesLI(List<String> allCodePaths) {
11223            cleanUp();
11224            removeDexFiles(allCodePaths, instructionSets);
11225        }
11226
11227        String getPackageName() {
11228            return getAsecPackageName(cid);
11229        }
11230
11231        boolean doPostDeleteLI(boolean delete) {
11232            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11233            final List<String> allCodePaths = getAllCodePaths();
11234            boolean mounted = PackageHelper.isContainerMounted(cid);
11235            if (mounted) {
11236                // Unmount first
11237                if (PackageHelper.unMountSdDir(cid)) {
11238                    mounted = false;
11239                }
11240            }
11241            if (!mounted && delete) {
11242                cleanUpResourcesLI(allCodePaths);
11243            }
11244            return !mounted;
11245        }
11246
11247        @Override
11248        int doPreCopy() {
11249            if (isFwdLocked()) {
11250                if (!PackageHelper.fixSdPermissions(cid,
11251                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11252                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11253                }
11254            }
11255
11256            return PackageManager.INSTALL_SUCCEEDED;
11257        }
11258
11259        @Override
11260        int doPostCopy(int uid) {
11261            if (isFwdLocked()) {
11262                if (uid < Process.FIRST_APPLICATION_UID
11263                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11264                                RES_FILE_NAME)) {
11265                    Slog.e(TAG, "Failed to finalize " + cid);
11266                    PackageHelper.destroySdDir(cid);
11267                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11268                }
11269            }
11270
11271            return PackageManager.INSTALL_SUCCEEDED;
11272        }
11273    }
11274
11275    /**
11276     * Logic to handle movement of existing installed applications.
11277     */
11278    class MoveInstallArgs extends InstallArgs {
11279        private File codeFile;
11280        private File resourceFile;
11281
11282        /** New install */
11283        MoveInstallArgs(InstallParams params) {
11284            super(params.origin, params.move, params.observer, params.installFlags,
11285                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11286                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11287        }
11288
11289        int copyApk(IMediaContainerService imcs, boolean temp) {
11290            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11291                    + move.fromUuid + " to " + move.toUuid);
11292            synchronized (mInstaller) {
11293                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11294                        move.dataAppName, move.appId, move.seinfo) != 0) {
11295                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11296                }
11297            }
11298
11299            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11300            resourceFile = codeFile;
11301            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11302
11303            return PackageManager.INSTALL_SUCCEEDED;
11304        }
11305
11306        int doPreInstall(int status) {
11307            if (status != PackageManager.INSTALL_SUCCEEDED) {
11308                cleanUp(move.toUuid);
11309            }
11310            return status;
11311        }
11312
11313        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11314            if (status != PackageManager.INSTALL_SUCCEEDED) {
11315                cleanUp(move.toUuid);
11316                return false;
11317            }
11318
11319            // Reflect the move in app info
11320            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11321            pkg.applicationInfo.setCodePath(pkg.codePath);
11322            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11323            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11324            pkg.applicationInfo.setResourcePath(pkg.codePath);
11325            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11326            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11327
11328            return true;
11329        }
11330
11331        int doPostInstall(int status, int uid) {
11332            if (status == PackageManager.INSTALL_SUCCEEDED) {
11333                cleanUp(move.fromUuid);
11334            } else {
11335                cleanUp(move.toUuid);
11336            }
11337            return status;
11338        }
11339
11340        @Override
11341        String getCodePath() {
11342            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11343        }
11344
11345        @Override
11346        String getResourcePath() {
11347            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11348        }
11349
11350        private boolean cleanUp(String volumeUuid) {
11351            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11352                    move.dataAppName);
11353            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11354            synchronized (mInstallLock) {
11355                // Clean up both app data and code
11356                removeDataDirsLI(volumeUuid, move.packageName);
11357                if (codeFile.isDirectory()) {
11358                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11359                } else {
11360                    codeFile.delete();
11361                }
11362            }
11363            return true;
11364        }
11365
11366        void cleanUpResourcesLI() {
11367            throw new UnsupportedOperationException();
11368        }
11369
11370        boolean doPostDeleteLI(boolean delete) {
11371            throw new UnsupportedOperationException();
11372        }
11373    }
11374
11375    static String getAsecPackageName(String packageCid) {
11376        int idx = packageCid.lastIndexOf("-");
11377        if (idx == -1) {
11378            return packageCid;
11379        }
11380        return packageCid.substring(0, idx);
11381    }
11382
11383    // Utility method used to create code paths based on package name and available index.
11384    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11385        String idxStr = "";
11386        int idx = 1;
11387        // Fall back to default value of idx=1 if prefix is not
11388        // part of oldCodePath
11389        if (oldCodePath != null) {
11390            String subStr = oldCodePath;
11391            // Drop the suffix right away
11392            if (suffix != null && subStr.endsWith(suffix)) {
11393                subStr = subStr.substring(0, subStr.length() - suffix.length());
11394            }
11395            // If oldCodePath already contains prefix find out the
11396            // ending index to either increment or decrement.
11397            int sidx = subStr.lastIndexOf(prefix);
11398            if (sidx != -1) {
11399                subStr = subStr.substring(sidx + prefix.length());
11400                if (subStr != null) {
11401                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11402                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11403                    }
11404                    try {
11405                        idx = Integer.parseInt(subStr);
11406                        if (idx <= 1) {
11407                            idx++;
11408                        } else {
11409                            idx--;
11410                        }
11411                    } catch(NumberFormatException e) {
11412                    }
11413                }
11414            }
11415        }
11416        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11417        return prefix + idxStr;
11418    }
11419
11420    private File getNextCodePath(File targetDir, String packageName) {
11421        int suffix = 1;
11422        File result;
11423        do {
11424            result = new File(targetDir, packageName + "-" + suffix);
11425            suffix++;
11426        } while (result.exists());
11427        return result;
11428    }
11429
11430    // Utility method that returns the relative package path with respect
11431    // to the installation directory. Like say for /data/data/com.test-1.apk
11432    // string com.test-1 is returned.
11433    static String deriveCodePathName(String codePath) {
11434        if (codePath == null) {
11435            return null;
11436        }
11437        final File codeFile = new File(codePath);
11438        final String name = codeFile.getName();
11439        if (codeFile.isDirectory()) {
11440            return name;
11441        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11442            final int lastDot = name.lastIndexOf('.');
11443            return name.substring(0, lastDot);
11444        } else {
11445            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11446            return null;
11447        }
11448    }
11449
11450    class PackageInstalledInfo {
11451        String name;
11452        int uid;
11453        // The set of users that originally had this package installed.
11454        int[] origUsers;
11455        // The set of users that now have this package installed.
11456        int[] newUsers;
11457        PackageParser.Package pkg;
11458        int returnCode;
11459        String returnMsg;
11460        PackageRemovedInfo removedInfo;
11461
11462        public void setError(int code, String msg) {
11463            returnCode = code;
11464            returnMsg = msg;
11465            Slog.w(TAG, msg);
11466        }
11467
11468        public void setError(String msg, PackageParserException e) {
11469            returnCode = e.error;
11470            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11471            Slog.w(TAG, msg, e);
11472        }
11473
11474        public void setError(String msg, PackageManagerException e) {
11475            returnCode = e.error;
11476            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11477            Slog.w(TAG, msg, e);
11478        }
11479
11480        // In some error cases we want to convey more info back to the observer
11481        String origPackage;
11482        String origPermission;
11483    }
11484
11485    /*
11486     * Install a non-existing package.
11487     */
11488    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11489            UserHandle user, String installerPackageName, String volumeUuid,
11490            PackageInstalledInfo res) {
11491        // Remember this for later, in case we need to rollback this install
11492        String pkgName = pkg.packageName;
11493
11494        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11495        final boolean dataDirExists = Environment
11496                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11497        synchronized(mPackages) {
11498            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11499                // A package with the same name is already installed, though
11500                // it has been renamed to an older name.  The package we
11501                // are trying to install should be installed as an update to
11502                // the existing one, but that has not been requested, so bail.
11503                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11504                        + " without first uninstalling package running as "
11505                        + mSettings.mRenamedPackages.get(pkgName));
11506                return;
11507            }
11508            if (mPackages.containsKey(pkgName)) {
11509                // Don't allow installation over an existing package with the same name.
11510                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11511                        + " without first uninstalling.");
11512                return;
11513            }
11514        }
11515
11516        try {
11517            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11518                    System.currentTimeMillis(), user);
11519
11520            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11521            // delete the partially installed application. the data directory will have to be
11522            // restored if it was already existing
11523            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11524                // remove package from internal structures.  Note that we want deletePackageX to
11525                // delete the package data and cache directories that it created in
11526                // scanPackageLocked, unless those directories existed before we even tried to
11527                // install.
11528                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11529                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11530                                res.removedInfo, true);
11531            }
11532
11533        } catch (PackageManagerException e) {
11534            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11535        }
11536    }
11537
11538    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11539        // Can't rotate keys during boot or if sharedUser.
11540        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11541                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11542            return false;
11543        }
11544        // app is using upgradeKeySets; make sure all are valid
11545        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11546        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11547        for (int i = 0; i < upgradeKeySets.length; i++) {
11548            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11549                Slog.wtf(TAG, "Package "
11550                         + (oldPs.name != null ? oldPs.name : "<null>")
11551                         + " contains upgrade-key-set reference to unknown key-set: "
11552                         + upgradeKeySets[i]
11553                         + " reverting to signatures check.");
11554                return false;
11555            }
11556        }
11557        return true;
11558    }
11559
11560    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11561        // Upgrade keysets are being used.  Determine if new package has a superset of the
11562        // required keys.
11563        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11564        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11565        for (int i = 0; i < upgradeKeySets.length; i++) {
11566            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11567            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11568                return true;
11569            }
11570        }
11571        return false;
11572    }
11573
11574    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11575            UserHandle user, String installerPackageName, String volumeUuid,
11576            PackageInstalledInfo res) {
11577        final PackageParser.Package oldPackage;
11578        final String pkgName = pkg.packageName;
11579        final int[] allUsers;
11580        final boolean[] perUserInstalled;
11581        final boolean weFroze;
11582
11583        // First find the old package info and check signatures
11584        synchronized(mPackages) {
11585            oldPackage = mPackages.get(pkgName);
11586            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11587            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11588            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11589                if(!checkUpgradeKeySetLP(ps, pkg)) {
11590                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11591                            "New package not signed by keys specified by upgrade-keysets: "
11592                            + pkgName);
11593                    return;
11594                }
11595            } else {
11596                // default to original signature matching
11597                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11598                    != PackageManager.SIGNATURE_MATCH) {
11599                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11600                            "New package has a different signature: " + pkgName);
11601                    return;
11602                }
11603            }
11604
11605            // In case of rollback, remember per-user/profile install state
11606            allUsers = sUserManager.getUserIds();
11607            perUserInstalled = new boolean[allUsers.length];
11608            for (int i = 0; i < allUsers.length; i++) {
11609                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11610            }
11611
11612            // Mark the app as frozen to prevent launching during the upgrade
11613            // process, and then kill all running instances
11614            if (!ps.frozen) {
11615                ps.frozen = true;
11616                weFroze = true;
11617            } else {
11618                weFroze = false;
11619            }
11620        }
11621
11622        // Now that we're guarded by frozen state, kill app during upgrade
11623        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11624
11625        try {
11626            boolean sysPkg = (isSystemApp(oldPackage));
11627            if (sysPkg) {
11628                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11629                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11630            } else {
11631                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11632                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11633            }
11634        } finally {
11635            // Regardless of success or failure of upgrade steps above, always
11636            // unfreeze the package if we froze it
11637            if (weFroze) {
11638                unfreezePackage(pkgName);
11639            }
11640        }
11641    }
11642
11643    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11644            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11645            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11646            String volumeUuid, PackageInstalledInfo res) {
11647        String pkgName = deletedPackage.packageName;
11648        boolean deletedPkg = true;
11649        boolean updatedSettings = false;
11650
11651        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11652                + deletedPackage);
11653        long origUpdateTime;
11654        if (pkg.mExtras != null) {
11655            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11656        } else {
11657            origUpdateTime = 0;
11658        }
11659
11660        // First delete the existing package while retaining the data directory
11661        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11662                res.removedInfo, true)) {
11663            // If the existing package wasn't successfully deleted
11664            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11665            deletedPkg = false;
11666        } else {
11667            // Successfully deleted the old package; proceed with replace.
11668
11669            // If deleted package lived in a container, give users a chance to
11670            // relinquish resources before killing.
11671            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11672                if (DEBUG_INSTALL) {
11673                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11674                }
11675                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11676                final ArrayList<String> pkgList = new ArrayList<String>(1);
11677                pkgList.add(deletedPackage.applicationInfo.packageName);
11678                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11679            }
11680
11681            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11682            try {
11683                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11684                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11685                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11686                        perUserInstalled, res, user);
11687                updatedSettings = true;
11688            } catch (PackageManagerException e) {
11689                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11690            }
11691        }
11692
11693        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11694            // remove package from internal structures.  Note that we want deletePackageX to
11695            // delete the package data and cache directories that it created in
11696            // scanPackageLocked, unless those directories existed before we even tried to
11697            // install.
11698            if(updatedSettings) {
11699                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11700                deletePackageLI(
11701                        pkgName, null, true, allUsers, perUserInstalled,
11702                        PackageManager.DELETE_KEEP_DATA,
11703                                res.removedInfo, true);
11704            }
11705            // Since we failed to install the new package we need to restore the old
11706            // package that we deleted.
11707            if (deletedPkg) {
11708                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11709                File restoreFile = new File(deletedPackage.codePath);
11710                // Parse old package
11711                boolean oldExternal = isExternal(deletedPackage);
11712                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11713                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11714                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11715                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11716                try {
11717                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11718                } catch (PackageManagerException e) {
11719                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11720                            + e.getMessage());
11721                    return;
11722                }
11723                // Restore of old package succeeded. Update permissions.
11724                // writer
11725                synchronized (mPackages) {
11726                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11727                            UPDATE_PERMISSIONS_ALL);
11728                    // can downgrade to reader
11729                    mSettings.writeLPr();
11730                }
11731                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11732            }
11733        }
11734    }
11735
11736    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11737            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11738            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11739            String volumeUuid, PackageInstalledInfo res) {
11740        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11741                + ", old=" + deletedPackage);
11742        boolean disabledSystem = false;
11743        boolean updatedSettings = false;
11744        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11745        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11746                != 0) {
11747            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11748        }
11749        String packageName = deletedPackage.packageName;
11750        if (packageName == null) {
11751            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11752                    "Attempt to delete null packageName.");
11753            return;
11754        }
11755        PackageParser.Package oldPkg;
11756        PackageSetting oldPkgSetting;
11757        // reader
11758        synchronized (mPackages) {
11759            oldPkg = mPackages.get(packageName);
11760            oldPkgSetting = mSettings.mPackages.get(packageName);
11761            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11762                    (oldPkgSetting == null)) {
11763                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11764                        "Couldn't find package:" + packageName + " information");
11765                return;
11766            }
11767        }
11768
11769        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11770        res.removedInfo.removedPackage = packageName;
11771        // Remove existing system package
11772        removePackageLI(oldPkgSetting, true);
11773        // writer
11774        synchronized (mPackages) {
11775            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11776            if (!disabledSystem && deletedPackage != null) {
11777                // We didn't need to disable the .apk as a current system package,
11778                // which means we are replacing another update that is already
11779                // installed.  We need to make sure to delete the older one's .apk.
11780                res.removedInfo.args = createInstallArgsForExisting(0,
11781                        deletedPackage.applicationInfo.getCodePath(),
11782                        deletedPackage.applicationInfo.getResourcePath(),
11783                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11784            } else {
11785                res.removedInfo.args = null;
11786            }
11787        }
11788
11789        // Successfully disabled the old package. Now proceed with re-installation
11790        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11791
11792        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11793        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11794
11795        PackageParser.Package newPackage = null;
11796        try {
11797            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11798            if (newPackage.mExtras != null) {
11799                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11800                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11801                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11802
11803                // is the update attempting to change shared user? that isn't going to work...
11804                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11805                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11806                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11807                            + " to " + newPkgSetting.sharedUser);
11808                    updatedSettings = true;
11809                }
11810            }
11811
11812            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11813                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11814                        perUserInstalled, res, user);
11815                updatedSettings = true;
11816            }
11817
11818        } catch (PackageManagerException e) {
11819            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11820        }
11821
11822        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11823            // Re installation failed. Restore old information
11824            // Remove new pkg information
11825            if (newPackage != null) {
11826                removeInstalledPackageLI(newPackage, true);
11827            }
11828            // Add back the old system package
11829            try {
11830                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11831            } catch (PackageManagerException e) {
11832                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11833            }
11834            // Restore the old system information in Settings
11835            synchronized (mPackages) {
11836                if (disabledSystem) {
11837                    mSettings.enableSystemPackageLPw(packageName);
11838                }
11839                if (updatedSettings) {
11840                    mSettings.setInstallerPackageName(packageName,
11841                            oldPkgSetting.installerPackageName);
11842                }
11843                mSettings.writeLPr();
11844            }
11845        }
11846    }
11847
11848    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11849            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11850            UserHandle user) {
11851        String pkgName = newPackage.packageName;
11852        synchronized (mPackages) {
11853            //write settings. the installStatus will be incomplete at this stage.
11854            //note that the new package setting would have already been
11855            //added to mPackages. It hasn't been persisted yet.
11856            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11857            mSettings.writeLPr();
11858        }
11859
11860        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11861
11862        synchronized (mPackages) {
11863            updatePermissionsLPw(newPackage.packageName, newPackage,
11864                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11865                            ? UPDATE_PERMISSIONS_ALL : 0));
11866            // For system-bundled packages, we assume that installing an upgraded version
11867            // of the package implies that the user actually wants to run that new code,
11868            // so we enable the package.
11869            PackageSetting ps = mSettings.mPackages.get(pkgName);
11870            if (ps != null) {
11871                if (isSystemApp(newPackage)) {
11872                    // NB: implicit assumption that system package upgrades apply to all users
11873                    if (DEBUG_INSTALL) {
11874                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11875                    }
11876                    if (res.origUsers != null) {
11877                        for (int userHandle : res.origUsers) {
11878                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11879                                    userHandle, installerPackageName);
11880                        }
11881                    }
11882                    // Also convey the prior install/uninstall state
11883                    if (allUsers != null && perUserInstalled != null) {
11884                        for (int i = 0; i < allUsers.length; i++) {
11885                            if (DEBUG_INSTALL) {
11886                                Slog.d(TAG, "    user " + allUsers[i]
11887                                        + " => " + perUserInstalled[i]);
11888                            }
11889                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11890                        }
11891                        // these install state changes will be persisted in the
11892                        // upcoming call to mSettings.writeLPr().
11893                    }
11894                }
11895                // It's implied that when a user requests installation, they want the app to be
11896                // installed and enabled.
11897                int userId = user.getIdentifier();
11898                if (userId != UserHandle.USER_ALL) {
11899                    ps.setInstalled(true, userId);
11900                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11901                }
11902            }
11903            res.name = pkgName;
11904            res.uid = newPackage.applicationInfo.uid;
11905            res.pkg = newPackage;
11906            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11907            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11908            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11909            //to update install status
11910            mSettings.writeLPr();
11911        }
11912    }
11913
11914    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11915        final int installFlags = args.installFlags;
11916        final String installerPackageName = args.installerPackageName;
11917        final String volumeUuid = args.volumeUuid;
11918        final File tmpPackageFile = new File(args.getCodePath());
11919        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11920        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11921                || (args.volumeUuid != null));
11922        boolean replace = false;
11923        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11924        if (args.move != null) {
11925            // moving a complete application; perfom an initial scan on the new install location
11926            scanFlags |= SCAN_INITIAL;
11927        }
11928        // Result object to be returned
11929        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11930
11931        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11932        // Retrieve PackageSettings and parse package
11933        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11934                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11935                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11936        PackageParser pp = new PackageParser();
11937        pp.setSeparateProcesses(mSeparateProcesses);
11938        pp.setDisplayMetrics(mMetrics);
11939
11940        final PackageParser.Package pkg;
11941        try {
11942            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11943        } catch (PackageParserException e) {
11944            res.setError("Failed parse during installPackageLI", e);
11945            return;
11946        }
11947
11948        // Mark that we have an install time CPU ABI override.
11949        pkg.cpuAbiOverride = args.abiOverride;
11950
11951        String pkgName = res.name = pkg.packageName;
11952        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11953            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11954                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11955                return;
11956            }
11957        }
11958
11959        try {
11960            pp.collectCertificates(pkg, parseFlags);
11961            pp.collectManifestDigest(pkg);
11962        } catch (PackageParserException e) {
11963            res.setError("Failed collect during installPackageLI", e);
11964            return;
11965        }
11966
11967        /* If the installer passed in a manifest digest, compare it now. */
11968        if (args.manifestDigest != null) {
11969            if (DEBUG_INSTALL) {
11970                final String parsedManifest = pkg.manifestDigest == null ? "null"
11971                        : pkg.manifestDigest.toString();
11972                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11973                        + parsedManifest);
11974            }
11975
11976            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11977                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11978                return;
11979            }
11980        } else if (DEBUG_INSTALL) {
11981            final String parsedManifest = pkg.manifestDigest == null
11982                    ? "null" : pkg.manifestDigest.toString();
11983            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11984        }
11985
11986        // Get rid of all references to package scan path via parser.
11987        pp = null;
11988        String oldCodePath = null;
11989        boolean systemApp = false;
11990        synchronized (mPackages) {
11991            // Check if installing already existing package
11992            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11993                String oldName = mSettings.mRenamedPackages.get(pkgName);
11994                if (pkg.mOriginalPackages != null
11995                        && pkg.mOriginalPackages.contains(oldName)
11996                        && mPackages.containsKey(oldName)) {
11997                    // This package is derived from an original package,
11998                    // and this device has been updating from that original
11999                    // name.  We must continue using the original name, so
12000                    // rename the new package here.
12001                    pkg.setPackageName(oldName);
12002                    pkgName = pkg.packageName;
12003                    replace = true;
12004                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12005                            + oldName + " pkgName=" + pkgName);
12006                } else if (mPackages.containsKey(pkgName)) {
12007                    // This package, under its official name, already exists
12008                    // on the device; we should replace it.
12009                    replace = true;
12010                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12011                }
12012
12013                // Prevent apps opting out from runtime permissions
12014                if (replace) {
12015                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12016                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12017                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12018                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12019                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12020                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12021                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12022                                        + " doesn't support runtime permissions but the old"
12023                                        + " target SDK " + oldTargetSdk + " does.");
12024                        return;
12025                    }
12026                }
12027            }
12028
12029            PackageSetting ps = mSettings.mPackages.get(pkgName);
12030            if (ps != null) {
12031                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12032
12033                // Quick sanity check that we're signed correctly if updating;
12034                // we'll check this again later when scanning, but we want to
12035                // bail early here before tripping over redefined permissions.
12036                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12037                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12038                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12039                                + pkg.packageName + " upgrade keys do not match the "
12040                                + "previously installed version");
12041                        return;
12042                    }
12043                } else {
12044                    try {
12045                        verifySignaturesLP(ps, pkg);
12046                    } catch (PackageManagerException e) {
12047                        res.setError(e.error, e.getMessage());
12048                        return;
12049                    }
12050                }
12051
12052                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12053                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12054                    systemApp = (ps.pkg.applicationInfo.flags &
12055                            ApplicationInfo.FLAG_SYSTEM) != 0;
12056                }
12057                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12058            }
12059
12060            // Check whether the newly-scanned package wants to define an already-defined perm
12061            int N = pkg.permissions.size();
12062            for (int i = N-1; i >= 0; i--) {
12063                PackageParser.Permission perm = pkg.permissions.get(i);
12064                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12065                if (bp != null) {
12066                    // If the defining package is signed with our cert, it's okay.  This
12067                    // also includes the "updating the same package" case, of course.
12068                    // "updating same package" could also involve key-rotation.
12069                    final boolean sigsOk;
12070                    if (bp.sourcePackage.equals(pkg.packageName)
12071                            && (bp.packageSetting instanceof PackageSetting)
12072                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12073                                    scanFlags))) {
12074                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12075                    } else {
12076                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12077                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12078                    }
12079                    if (!sigsOk) {
12080                        // If the owning package is the system itself, we log but allow
12081                        // install to proceed; we fail the install on all other permission
12082                        // redefinitions.
12083                        if (!bp.sourcePackage.equals("android")) {
12084                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12085                                    + pkg.packageName + " attempting to redeclare permission "
12086                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12087                            res.origPermission = perm.info.name;
12088                            res.origPackage = bp.sourcePackage;
12089                            return;
12090                        } else {
12091                            Slog.w(TAG, "Package " + pkg.packageName
12092                                    + " attempting to redeclare system permission "
12093                                    + perm.info.name + "; ignoring new declaration");
12094                            pkg.permissions.remove(i);
12095                        }
12096                    }
12097                }
12098            }
12099
12100        }
12101
12102        if (systemApp && onExternal) {
12103            // Disable updates to system apps on sdcard
12104            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12105                    "Cannot install updates to system apps on sdcard");
12106            return;
12107        }
12108
12109        if (args.move != null) {
12110            // We did an in-place move, so dex is ready to roll
12111            scanFlags |= SCAN_NO_DEX;
12112            scanFlags |= SCAN_MOVE;
12113        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12114            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12115            scanFlags |= SCAN_NO_DEX;
12116
12117            try {
12118                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12119                        true /* extract libs */);
12120            } catch (PackageManagerException pme) {
12121                Slog.e(TAG, "Error deriving application ABI", pme);
12122                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12123                return;
12124            }
12125
12126            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12127            int result = mPackageDexOptimizer
12128                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12129                            false /* defer */, false /* inclDependencies */);
12130            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12131                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12132                return;
12133            }
12134        }
12135
12136        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12137            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12138            return;
12139        }
12140
12141        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12142
12143        if (replace) {
12144            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12145                    installerPackageName, volumeUuid, res);
12146        } else {
12147            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12148                    args.user, installerPackageName, volumeUuid, res);
12149        }
12150        synchronized (mPackages) {
12151            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12152            if (ps != null) {
12153                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12154            }
12155        }
12156    }
12157
12158    private void startIntentFilterVerifications(int userId, boolean replacing,
12159            PackageParser.Package pkg) {
12160        if (mIntentFilterVerifierComponent == null) {
12161            Slog.w(TAG, "No IntentFilter verification will not be done as "
12162                    + "there is no IntentFilterVerifier available!");
12163            return;
12164        }
12165
12166        final int verifierUid = getPackageUid(
12167                mIntentFilterVerifierComponent.getPackageName(),
12168                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12169
12170        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12171        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12172        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12173        mHandler.sendMessage(msg);
12174    }
12175
12176    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12177            PackageParser.Package pkg) {
12178        int size = pkg.activities.size();
12179        if (size == 0) {
12180            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12181                    "No activity, so no need to verify any IntentFilter!");
12182            return;
12183        }
12184
12185        final boolean hasDomainURLs = hasDomainURLs(pkg);
12186        if (!hasDomainURLs) {
12187            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12188                    "No domain URLs, so no need to verify any IntentFilter!");
12189            return;
12190        }
12191
12192        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12193                + " if any IntentFilter from the " + size
12194                + " Activities needs verification ...");
12195
12196        int count = 0;
12197        final String packageName = pkg.packageName;
12198
12199        synchronized (mPackages) {
12200            // If this is a new install and we see that we've already run verification for this
12201            // package, we have nothing to do: it means the state was restored from backup.
12202            if (!replacing) {
12203                IntentFilterVerificationInfo ivi =
12204                        mSettings.getIntentFilterVerificationLPr(packageName);
12205                if (ivi != null) {
12206                    if (DEBUG_DOMAIN_VERIFICATION) {
12207                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12208                                + ivi.getStatusString());
12209                    }
12210                    return;
12211                }
12212            }
12213
12214            // If any filters need to be verified, then all need to be.
12215            boolean needToVerify = false;
12216            for (PackageParser.Activity a : pkg.activities) {
12217                for (ActivityIntentInfo filter : a.intents) {
12218                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12219                        if (DEBUG_DOMAIN_VERIFICATION) {
12220                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12221                        }
12222                        needToVerify = true;
12223                        break;
12224                    }
12225                }
12226            }
12227
12228            if (needToVerify) {
12229                final int verificationId = mIntentFilterVerificationToken++;
12230                for (PackageParser.Activity a : pkg.activities) {
12231                    for (ActivityIntentInfo filter : a.intents) {
12232                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12233                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12234                                    "Verification needed for IntentFilter:" + filter.toString());
12235                            mIntentFilterVerifier.addOneIntentFilterVerification(
12236                                    verifierUid, userId, verificationId, filter, packageName);
12237                            count++;
12238                        }
12239                    }
12240                }
12241            }
12242        }
12243
12244        if (count > 0) {
12245            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12246                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12247                    +  " for userId:" + userId);
12248            mIntentFilterVerifier.startVerifications(userId);
12249        } else {
12250            if (DEBUG_DOMAIN_VERIFICATION) {
12251                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12252            }
12253        }
12254    }
12255
12256    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12257        final ComponentName cn  = filter.activity.getComponentName();
12258        final String packageName = cn.getPackageName();
12259
12260        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12261                packageName);
12262        if (ivi == null) {
12263            return true;
12264        }
12265        int status = ivi.getStatus();
12266        switch (status) {
12267            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12268            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12269                return true;
12270
12271            default:
12272                // Nothing to do
12273                return false;
12274        }
12275    }
12276
12277    private static boolean isMultiArch(PackageSetting ps) {
12278        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12279    }
12280
12281    private static boolean isMultiArch(ApplicationInfo info) {
12282        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12283    }
12284
12285    private static boolean isExternal(PackageParser.Package pkg) {
12286        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12287    }
12288
12289    private static boolean isExternal(PackageSetting ps) {
12290        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12291    }
12292
12293    private static boolean isExternal(ApplicationInfo info) {
12294        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12295    }
12296
12297    private static boolean isSystemApp(PackageParser.Package pkg) {
12298        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12299    }
12300
12301    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12302        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12303    }
12304
12305    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12306        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12307    }
12308
12309    private static boolean isSystemApp(PackageSetting ps) {
12310        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12311    }
12312
12313    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12314        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12315    }
12316
12317    private int packageFlagsToInstallFlags(PackageSetting ps) {
12318        int installFlags = 0;
12319        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12320            // This existing package was an external ASEC install when we have
12321            // the external flag without a UUID
12322            installFlags |= PackageManager.INSTALL_EXTERNAL;
12323        }
12324        if (ps.isForwardLocked()) {
12325            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12326        }
12327        return installFlags;
12328    }
12329
12330    private void deleteTempPackageFiles() {
12331        final FilenameFilter filter = new FilenameFilter() {
12332            public boolean accept(File dir, String name) {
12333                return name.startsWith("vmdl") && name.endsWith(".tmp");
12334            }
12335        };
12336        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12337            file.delete();
12338        }
12339    }
12340
12341    @Override
12342    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12343            int flags) {
12344        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12345                flags);
12346    }
12347
12348    @Override
12349    public void deletePackage(final String packageName,
12350            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12351        mContext.enforceCallingOrSelfPermission(
12352                android.Manifest.permission.DELETE_PACKAGES, null);
12353        Preconditions.checkNotNull(packageName);
12354        Preconditions.checkNotNull(observer);
12355        final int uid = Binder.getCallingUid();
12356        if (UserHandle.getUserId(uid) != userId) {
12357            mContext.enforceCallingPermission(
12358                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12359                    "deletePackage for user " + userId);
12360        }
12361        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12362            try {
12363                observer.onPackageDeleted(packageName,
12364                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12365            } catch (RemoteException re) {
12366            }
12367            return;
12368        }
12369
12370        boolean uninstallBlocked = false;
12371        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12372            int[] users = sUserManager.getUserIds();
12373            for (int i = 0; i < users.length; ++i) {
12374                if (getBlockUninstallForUser(packageName, users[i])) {
12375                    uninstallBlocked = true;
12376                    break;
12377                }
12378            }
12379        } else {
12380            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12381        }
12382        if (uninstallBlocked) {
12383            try {
12384                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12385                        null);
12386            } catch (RemoteException re) {
12387            }
12388            return;
12389        }
12390
12391        if (DEBUG_REMOVE) {
12392            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12393        }
12394        // Queue up an async operation since the package deletion may take a little while.
12395        mHandler.post(new Runnable() {
12396            public void run() {
12397                mHandler.removeCallbacks(this);
12398                final int returnCode = deletePackageX(packageName, userId, flags);
12399                if (observer != null) {
12400                    try {
12401                        observer.onPackageDeleted(packageName, returnCode, null);
12402                    } catch (RemoteException e) {
12403                        Log.i(TAG, "Observer no longer exists.");
12404                    } //end catch
12405                } //end if
12406            } //end run
12407        });
12408    }
12409
12410    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12411        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12412                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12413        try {
12414            if (dpm != null) {
12415                if (dpm.isDeviceOwner(packageName)) {
12416                    return true;
12417                }
12418                int[] users;
12419                if (userId == UserHandle.USER_ALL) {
12420                    users = sUserManager.getUserIds();
12421                } else {
12422                    users = new int[]{userId};
12423                }
12424                for (int i = 0; i < users.length; ++i) {
12425                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12426                        return true;
12427                    }
12428                }
12429            }
12430        } catch (RemoteException e) {
12431        }
12432        return false;
12433    }
12434
12435    /**
12436     *  This method is an internal method that could be get invoked either
12437     *  to delete an installed package or to clean up a failed installation.
12438     *  After deleting an installed package, a broadcast is sent to notify any
12439     *  listeners that the package has been installed. For cleaning up a failed
12440     *  installation, the broadcast is not necessary since the package's
12441     *  installation wouldn't have sent the initial broadcast either
12442     *  The key steps in deleting a package are
12443     *  deleting the package information in internal structures like mPackages,
12444     *  deleting the packages base directories through installd
12445     *  updating mSettings to reflect current status
12446     *  persisting settings for later use
12447     *  sending a broadcast if necessary
12448     */
12449    private int deletePackageX(String packageName, int userId, int flags) {
12450        final PackageRemovedInfo info = new PackageRemovedInfo();
12451        final boolean res;
12452
12453        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12454                ? UserHandle.ALL : new UserHandle(userId);
12455
12456        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12457            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12458            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12459        }
12460
12461        boolean removedForAllUsers = false;
12462        boolean systemUpdate = false;
12463
12464        // for the uninstall-updates case and restricted profiles, remember the per-
12465        // userhandle installed state
12466        int[] allUsers;
12467        boolean[] perUserInstalled;
12468        synchronized (mPackages) {
12469            PackageSetting ps = mSettings.mPackages.get(packageName);
12470            allUsers = sUserManager.getUserIds();
12471            perUserInstalled = new boolean[allUsers.length];
12472            for (int i = 0; i < allUsers.length; i++) {
12473                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12474            }
12475        }
12476
12477        synchronized (mInstallLock) {
12478            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12479            res = deletePackageLI(packageName, removeForUser,
12480                    true, allUsers, perUserInstalled,
12481                    flags | REMOVE_CHATTY, info, true);
12482            systemUpdate = info.isRemovedPackageSystemUpdate;
12483            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12484                removedForAllUsers = true;
12485            }
12486            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12487                    + " removedForAllUsers=" + removedForAllUsers);
12488        }
12489
12490        if (res) {
12491            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12492
12493            // If the removed package was a system update, the old system package
12494            // was re-enabled; we need to broadcast this information
12495            if (systemUpdate) {
12496                Bundle extras = new Bundle(1);
12497                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12498                        ? info.removedAppId : info.uid);
12499                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12500
12501                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12502                        extras, null, null, null);
12503                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12504                        extras, null, null, null);
12505                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12506                        null, packageName, null, null);
12507            }
12508        }
12509        // Force a gc here.
12510        Runtime.getRuntime().gc();
12511        // Delete the resources here after sending the broadcast to let
12512        // other processes clean up before deleting resources.
12513        if (info.args != null) {
12514            synchronized (mInstallLock) {
12515                info.args.doPostDeleteLI(true);
12516            }
12517        }
12518
12519        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12520    }
12521
12522    class PackageRemovedInfo {
12523        String removedPackage;
12524        int uid = -1;
12525        int removedAppId = -1;
12526        int[] removedUsers = null;
12527        boolean isRemovedPackageSystemUpdate = false;
12528        // Clean up resources deleted packages.
12529        InstallArgs args = null;
12530
12531        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12532            Bundle extras = new Bundle(1);
12533            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12534            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12535            if (replacing) {
12536                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12537            }
12538            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12539            if (removedPackage != null) {
12540                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12541                        extras, null, null, removedUsers);
12542                if (fullRemove && !replacing) {
12543                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12544                            extras, null, null, removedUsers);
12545                }
12546            }
12547            if (removedAppId >= 0) {
12548                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12549                        removedUsers);
12550            }
12551        }
12552    }
12553
12554    /*
12555     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12556     * flag is not set, the data directory is removed as well.
12557     * make sure this flag is set for partially installed apps. If not its meaningless to
12558     * delete a partially installed application.
12559     */
12560    private void removePackageDataLI(PackageSetting ps,
12561            int[] allUserHandles, boolean[] perUserInstalled,
12562            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12563        String packageName = ps.name;
12564        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12565        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12566        // Retrieve object to delete permissions for shared user later on
12567        final PackageSetting deletedPs;
12568        // reader
12569        synchronized (mPackages) {
12570            deletedPs = mSettings.mPackages.get(packageName);
12571            if (outInfo != null) {
12572                outInfo.removedPackage = packageName;
12573                outInfo.removedUsers = deletedPs != null
12574                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12575                        : null;
12576            }
12577        }
12578        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12579            removeDataDirsLI(ps.volumeUuid, packageName);
12580            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12581        }
12582        // writer
12583        synchronized (mPackages) {
12584            if (deletedPs != null) {
12585                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12586                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12587                    clearDefaultBrowserIfNeeded(packageName);
12588                    if (outInfo != null) {
12589                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12590                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12591                    }
12592                    updatePermissionsLPw(deletedPs.name, null, 0);
12593                    if (deletedPs.sharedUser != null) {
12594                        // Remove permissions associated with package. Since runtime
12595                        // permissions are per user we have to kill the removed package
12596                        // or packages running under the shared user of the removed
12597                        // package if revoking the permissions requested only by the removed
12598                        // package is successful and this causes a change in gids.
12599                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12600                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12601                                    userId);
12602                            if (userIdToKill == UserHandle.USER_ALL
12603                                    || userIdToKill >= UserHandle.USER_OWNER) {
12604                                // If gids changed for this user, kill all affected packages.
12605                                mHandler.post(new Runnable() {
12606                                    @Override
12607                                    public void run() {
12608                                        // This has to happen with no lock held.
12609                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12610                                                KILL_APP_REASON_GIDS_CHANGED);
12611                                    }
12612                                });
12613                            break;
12614                            }
12615                        }
12616                    }
12617                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12618                }
12619                // make sure to preserve per-user disabled state if this removal was just
12620                // a downgrade of a system app to the factory package
12621                if (allUserHandles != null && perUserInstalled != null) {
12622                    if (DEBUG_REMOVE) {
12623                        Slog.d(TAG, "Propagating install state across downgrade");
12624                    }
12625                    for (int i = 0; i < allUserHandles.length; i++) {
12626                        if (DEBUG_REMOVE) {
12627                            Slog.d(TAG, "    user " + allUserHandles[i]
12628                                    + " => " + perUserInstalled[i]);
12629                        }
12630                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12631                    }
12632                }
12633            }
12634            // can downgrade to reader
12635            if (writeSettings) {
12636                // Save settings now
12637                mSettings.writeLPr();
12638            }
12639        }
12640        if (outInfo != null) {
12641            // A user ID was deleted here. Go through all users and remove it
12642            // from KeyStore.
12643            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12644        }
12645    }
12646
12647    static boolean locationIsPrivileged(File path) {
12648        try {
12649            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12650                    .getCanonicalPath();
12651            return path.getCanonicalPath().startsWith(privilegedAppDir);
12652        } catch (IOException e) {
12653            Slog.e(TAG, "Unable to access code path " + path);
12654        }
12655        return false;
12656    }
12657
12658    /*
12659     * Tries to delete system package.
12660     */
12661    private boolean deleteSystemPackageLI(PackageSetting newPs,
12662            int[] allUserHandles, boolean[] perUserInstalled,
12663            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12664        final boolean applyUserRestrictions
12665                = (allUserHandles != null) && (perUserInstalled != null);
12666        PackageSetting disabledPs = null;
12667        // Confirm if the system package has been updated
12668        // An updated system app can be deleted. This will also have to restore
12669        // the system pkg from system partition
12670        // reader
12671        synchronized (mPackages) {
12672            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12673        }
12674        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12675                + " disabledPs=" + disabledPs);
12676        if (disabledPs == null) {
12677            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12678            return false;
12679        } else if (DEBUG_REMOVE) {
12680            Slog.d(TAG, "Deleting system pkg from data partition");
12681        }
12682        if (DEBUG_REMOVE) {
12683            if (applyUserRestrictions) {
12684                Slog.d(TAG, "Remembering install states:");
12685                for (int i = 0; i < allUserHandles.length; i++) {
12686                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12687                }
12688            }
12689        }
12690        // Delete the updated package
12691        outInfo.isRemovedPackageSystemUpdate = true;
12692        if (disabledPs.versionCode < newPs.versionCode) {
12693            // Delete data for downgrades
12694            flags &= ~PackageManager.DELETE_KEEP_DATA;
12695        } else {
12696            // Preserve data by setting flag
12697            flags |= PackageManager.DELETE_KEEP_DATA;
12698        }
12699        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12700                allUserHandles, perUserInstalled, outInfo, writeSettings);
12701        if (!ret) {
12702            return false;
12703        }
12704        // writer
12705        synchronized (mPackages) {
12706            // Reinstate the old system package
12707            mSettings.enableSystemPackageLPw(newPs.name);
12708            // Remove any native libraries from the upgraded package.
12709            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12710        }
12711        // Install the system package
12712        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12713        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12714        if (locationIsPrivileged(disabledPs.codePath)) {
12715            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12716        }
12717
12718        final PackageParser.Package newPkg;
12719        try {
12720            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12721        } catch (PackageManagerException e) {
12722            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12723            return false;
12724        }
12725
12726        // writer
12727        synchronized (mPackages) {
12728            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12729            updatePermissionsLPw(newPkg.packageName, newPkg,
12730                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12731            if (applyUserRestrictions) {
12732                if (DEBUG_REMOVE) {
12733                    Slog.d(TAG, "Propagating install state across reinstall");
12734                }
12735                for (int i = 0; i < allUserHandles.length; i++) {
12736                    if (DEBUG_REMOVE) {
12737                        Slog.d(TAG, "    user " + allUserHandles[i]
12738                                + " => " + perUserInstalled[i]);
12739                    }
12740                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12741                }
12742                // Regardless of writeSettings we need to ensure that this restriction
12743                // state propagation is persisted
12744                mSettings.writeAllUsersPackageRestrictionsLPr();
12745            }
12746            // can downgrade to reader here
12747            if (writeSettings) {
12748                mSettings.writeLPr();
12749            }
12750        }
12751        return true;
12752    }
12753
12754    private boolean deleteInstalledPackageLI(PackageSetting ps,
12755            boolean deleteCodeAndResources, int flags,
12756            int[] allUserHandles, boolean[] perUserInstalled,
12757            PackageRemovedInfo outInfo, boolean writeSettings) {
12758        if (outInfo != null) {
12759            outInfo.uid = ps.appId;
12760        }
12761
12762        // Delete package data from internal structures and also remove data if flag is set
12763        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12764
12765        // Delete application code and resources
12766        if (deleteCodeAndResources && (outInfo != null)) {
12767            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12768                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12769            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12770        }
12771        return true;
12772    }
12773
12774    @Override
12775    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12776            int userId) {
12777        mContext.enforceCallingOrSelfPermission(
12778                android.Manifest.permission.DELETE_PACKAGES, null);
12779        synchronized (mPackages) {
12780            PackageSetting ps = mSettings.mPackages.get(packageName);
12781            if (ps == null) {
12782                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12783                return false;
12784            }
12785            if (!ps.getInstalled(userId)) {
12786                // Can't block uninstall for an app that is not installed or enabled.
12787                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12788                return false;
12789            }
12790            ps.setBlockUninstall(blockUninstall, userId);
12791            mSettings.writePackageRestrictionsLPr(userId);
12792        }
12793        return true;
12794    }
12795
12796    @Override
12797    public boolean getBlockUninstallForUser(String packageName, int userId) {
12798        synchronized (mPackages) {
12799            PackageSetting ps = mSettings.mPackages.get(packageName);
12800            if (ps == null) {
12801                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12802                return false;
12803            }
12804            return ps.getBlockUninstall(userId);
12805        }
12806    }
12807
12808    /*
12809     * This method handles package deletion in general
12810     */
12811    private boolean deletePackageLI(String packageName, UserHandle user,
12812            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12813            int flags, PackageRemovedInfo outInfo,
12814            boolean writeSettings) {
12815        if (packageName == null) {
12816            Slog.w(TAG, "Attempt to delete null packageName.");
12817            return false;
12818        }
12819        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12820        PackageSetting ps;
12821        boolean dataOnly = false;
12822        int removeUser = -1;
12823        int appId = -1;
12824        synchronized (mPackages) {
12825            ps = mSettings.mPackages.get(packageName);
12826            if (ps == null) {
12827                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12828                return false;
12829            }
12830            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12831                    && user.getIdentifier() != UserHandle.USER_ALL) {
12832                // The caller is asking that the package only be deleted for a single
12833                // user.  To do this, we just mark its uninstalled state and delete
12834                // its data.  If this is a system app, we only allow this to happen if
12835                // they have set the special DELETE_SYSTEM_APP which requests different
12836                // semantics than normal for uninstalling system apps.
12837                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12838                ps.setUserState(user.getIdentifier(),
12839                        COMPONENT_ENABLED_STATE_DEFAULT,
12840                        false, //installed
12841                        true,  //stopped
12842                        true,  //notLaunched
12843                        false, //hidden
12844                        null, null, null,
12845                        false, // blockUninstall
12846                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12847                if (!isSystemApp(ps)) {
12848                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12849                        // Other user still have this package installed, so all
12850                        // we need to do is clear this user's data and save that
12851                        // it is uninstalled.
12852                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12853                        removeUser = user.getIdentifier();
12854                        appId = ps.appId;
12855                        scheduleWritePackageRestrictionsLocked(removeUser);
12856                    } else {
12857                        // We need to set it back to 'installed' so the uninstall
12858                        // broadcasts will be sent correctly.
12859                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12860                        ps.setInstalled(true, user.getIdentifier());
12861                    }
12862                } else {
12863                    // This is a system app, so we assume that the
12864                    // other users still have this package installed, so all
12865                    // we need to do is clear this user's data and save that
12866                    // it is uninstalled.
12867                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12868                    removeUser = user.getIdentifier();
12869                    appId = ps.appId;
12870                    scheduleWritePackageRestrictionsLocked(removeUser);
12871                }
12872            }
12873        }
12874
12875        if (removeUser >= 0) {
12876            // From above, we determined that we are deleting this only
12877            // for a single user.  Continue the work here.
12878            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12879            if (outInfo != null) {
12880                outInfo.removedPackage = packageName;
12881                outInfo.removedAppId = appId;
12882                outInfo.removedUsers = new int[] {removeUser};
12883            }
12884            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12885            removeKeystoreDataIfNeeded(removeUser, appId);
12886            schedulePackageCleaning(packageName, removeUser, false);
12887            synchronized (mPackages) {
12888                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12889                    scheduleWritePackageRestrictionsLocked(removeUser);
12890                }
12891                revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(),
12892                        removeUser);
12893            }
12894            return true;
12895        }
12896
12897        if (dataOnly) {
12898            // Delete application data first
12899            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12900            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12901            return true;
12902        }
12903
12904        boolean ret = false;
12905        if (isSystemApp(ps)) {
12906            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12907            // When an updated system application is deleted we delete the existing resources as well and
12908            // fall back to existing code in system partition
12909            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12910                    flags, outInfo, writeSettings);
12911        } else {
12912            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12913            // Kill application pre-emptively especially for apps on sd.
12914            killApplication(packageName, ps.appId, "uninstall pkg");
12915            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12916                    allUserHandles, perUserInstalled,
12917                    outInfo, writeSettings);
12918        }
12919
12920        return ret;
12921    }
12922
12923    private final class ClearStorageConnection implements ServiceConnection {
12924        IMediaContainerService mContainerService;
12925
12926        @Override
12927        public void onServiceConnected(ComponentName name, IBinder service) {
12928            synchronized (this) {
12929                mContainerService = IMediaContainerService.Stub.asInterface(service);
12930                notifyAll();
12931            }
12932        }
12933
12934        @Override
12935        public void onServiceDisconnected(ComponentName name) {
12936        }
12937    }
12938
12939    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12940        final boolean mounted;
12941        if (Environment.isExternalStorageEmulated()) {
12942            mounted = true;
12943        } else {
12944            final String status = Environment.getExternalStorageState();
12945
12946            mounted = status.equals(Environment.MEDIA_MOUNTED)
12947                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12948        }
12949
12950        if (!mounted) {
12951            return;
12952        }
12953
12954        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12955        int[] users;
12956        if (userId == UserHandle.USER_ALL) {
12957            users = sUserManager.getUserIds();
12958        } else {
12959            users = new int[] { userId };
12960        }
12961        final ClearStorageConnection conn = new ClearStorageConnection();
12962        if (mContext.bindServiceAsUser(
12963                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12964            try {
12965                for (int curUser : users) {
12966                    long timeout = SystemClock.uptimeMillis() + 5000;
12967                    synchronized (conn) {
12968                        long now = SystemClock.uptimeMillis();
12969                        while (conn.mContainerService == null && now < timeout) {
12970                            try {
12971                                conn.wait(timeout - now);
12972                            } catch (InterruptedException e) {
12973                            }
12974                        }
12975                    }
12976                    if (conn.mContainerService == null) {
12977                        return;
12978                    }
12979
12980                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12981                    clearDirectory(conn.mContainerService,
12982                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12983                    if (allData) {
12984                        clearDirectory(conn.mContainerService,
12985                                userEnv.buildExternalStorageAppDataDirs(packageName));
12986                        clearDirectory(conn.mContainerService,
12987                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12988                    }
12989                }
12990            } finally {
12991                mContext.unbindService(conn);
12992            }
12993        }
12994    }
12995
12996    @Override
12997    public void clearApplicationUserData(final String packageName,
12998            final IPackageDataObserver observer, final int userId) {
12999        mContext.enforceCallingOrSelfPermission(
13000                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13001        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13002        // Queue up an async operation since the package deletion may take a little while.
13003        mHandler.post(new Runnable() {
13004            public void run() {
13005                mHandler.removeCallbacks(this);
13006                final boolean succeeded;
13007                synchronized (mInstallLock) {
13008                    succeeded = clearApplicationUserDataLI(packageName, userId);
13009                }
13010                clearExternalStorageDataSync(packageName, userId, true);
13011                if (succeeded) {
13012                    // invoke DeviceStorageMonitor's update method to clear any notifications
13013                    DeviceStorageMonitorInternal
13014                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13015                    if (dsm != null) {
13016                        dsm.checkMemory();
13017                    }
13018                }
13019                if(observer != null) {
13020                    try {
13021                        observer.onRemoveCompleted(packageName, succeeded);
13022                    } catch (RemoteException e) {
13023                        Log.i(TAG, "Observer no longer exists.");
13024                    }
13025                } //end if observer
13026            } //end run
13027        });
13028    }
13029
13030    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13031        if (packageName == null) {
13032            Slog.w(TAG, "Attempt to delete null packageName.");
13033            return false;
13034        }
13035
13036        // Try finding details about the requested package
13037        PackageParser.Package pkg;
13038        synchronized (mPackages) {
13039            pkg = mPackages.get(packageName);
13040            if (pkg == null) {
13041                final PackageSetting ps = mSettings.mPackages.get(packageName);
13042                if (ps != null) {
13043                    pkg = ps.pkg;
13044                }
13045            }
13046
13047            if (pkg == null) {
13048                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13049                return false;
13050            }
13051
13052            PackageSetting ps = (PackageSetting) pkg.mExtras;
13053            PermissionsState permissionsState = ps.getPermissionsState();
13054            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
13055        }
13056
13057        // Always delete data directories for package, even if we found no other
13058        // record of app. This helps users recover from UID mismatches without
13059        // resorting to a full data wipe.
13060        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13061        if (retCode < 0) {
13062            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13063            return false;
13064        }
13065
13066        final int appId = pkg.applicationInfo.uid;
13067        removeKeystoreDataIfNeeded(userId, appId);
13068
13069        // Create a native library symlink only if we have native libraries
13070        // and if the native libraries are 32 bit libraries. We do not provide
13071        // this symlink for 64 bit libraries.
13072        if (pkg.applicationInfo.primaryCpuAbi != null &&
13073                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13074            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13075            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13076                    nativeLibPath, userId) < 0) {
13077                Slog.w(TAG, "Failed linking native library dir");
13078                return false;
13079            }
13080        }
13081
13082        return true;
13083    }
13084
13085
13086    /**
13087     * Revokes granted runtime permissions and clears resettable flags
13088     * which are flags that can be set by a user interaction.
13089     *
13090     * @param permissionsState The permission state to reset.
13091     * @param userId The device user for which to do a reset.
13092     */
13093    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
13094            PermissionsState permissionsState, int userId) {
13095        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
13096                | PackageManager.FLAG_PERMISSION_USER_FIXED
13097                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13098
13099        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags);
13100    }
13101
13102    /**
13103     * Revokes granted runtime permissions and clears all flags.
13104     *
13105     * @param permissionsState The permission state to reset.
13106     * @param userId The device user for which to do a reset.
13107     */
13108    private void revokeRuntimePermissionsAndClearAllFlagsLocked(
13109            PermissionsState permissionsState, int userId) {
13110        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId,
13111                PackageManager.MASK_PERMISSION_FLAGS);
13112    }
13113
13114    /**
13115     * Revokes granted runtime permissions and clears certain flags.
13116     *
13117     * @param permissionsState The permission state to reset.
13118     * @param userId The device user for which to do a reset.
13119     * @param flags The flags that is going to be reset.
13120     */
13121    private void revokeRuntimePermissionsAndClearFlagsLocked(
13122            PermissionsState permissionsState, final int userId, int flags) {
13123        boolean needsWrite = false;
13124
13125        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
13126            BasePermission bp = mSettings.mPermissions.get(state.getName());
13127            if (bp != null) {
13128                permissionsState.revokeRuntimePermission(bp, userId);
13129                permissionsState.updatePermissionFlags(bp, userId, flags, 0);
13130                needsWrite = true;
13131            }
13132        }
13133
13134        // Ensure default permissions are never cleared.
13135        mHandler.post(new Runnable() {
13136            @Override
13137            public void run() {
13138                mDefaultPermissionPolicy.grantDefaultPermissions(userId);
13139            }
13140        });
13141
13142        if (needsWrite) {
13143            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13144        }
13145    }
13146
13147    /**
13148     * Remove entries from the keystore daemon. Will only remove it if the
13149     * {@code appId} is valid.
13150     */
13151    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13152        if (appId < 0) {
13153            return;
13154        }
13155
13156        final KeyStore keyStore = KeyStore.getInstance();
13157        if (keyStore != null) {
13158            if (userId == UserHandle.USER_ALL) {
13159                for (final int individual : sUserManager.getUserIds()) {
13160                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13161                }
13162            } else {
13163                keyStore.clearUid(UserHandle.getUid(userId, appId));
13164            }
13165        } else {
13166            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13167        }
13168    }
13169
13170    @Override
13171    public void deleteApplicationCacheFiles(final String packageName,
13172            final IPackageDataObserver observer) {
13173        mContext.enforceCallingOrSelfPermission(
13174                android.Manifest.permission.DELETE_CACHE_FILES, null);
13175        // Queue up an async operation since the package deletion may take a little while.
13176        final int userId = UserHandle.getCallingUserId();
13177        mHandler.post(new Runnable() {
13178            public void run() {
13179                mHandler.removeCallbacks(this);
13180                final boolean succeded;
13181                synchronized (mInstallLock) {
13182                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13183                }
13184                clearExternalStorageDataSync(packageName, userId, false);
13185                if (observer != null) {
13186                    try {
13187                        observer.onRemoveCompleted(packageName, succeded);
13188                    } catch (RemoteException e) {
13189                        Log.i(TAG, "Observer no longer exists.");
13190                    }
13191                } //end if observer
13192            } //end run
13193        });
13194    }
13195
13196    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13197        if (packageName == null) {
13198            Slog.w(TAG, "Attempt to delete null packageName.");
13199            return false;
13200        }
13201        PackageParser.Package p;
13202        synchronized (mPackages) {
13203            p = mPackages.get(packageName);
13204        }
13205        if (p == null) {
13206            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13207            return false;
13208        }
13209        final ApplicationInfo applicationInfo = p.applicationInfo;
13210        if (applicationInfo == null) {
13211            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13212            return false;
13213        }
13214        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13215        if (retCode < 0) {
13216            Slog.w(TAG, "Couldn't remove cache files for package: "
13217                       + packageName + " u" + userId);
13218            return false;
13219        }
13220        return true;
13221    }
13222
13223    @Override
13224    public void getPackageSizeInfo(final String packageName, int userHandle,
13225            final IPackageStatsObserver observer) {
13226        mContext.enforceCallingOrSelfPermission(
13227                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13228        if (packageName == null) {
13229            throw new IllegalArgumentException("Attempt to get size of null packageName");
13230        }
13231
13232        PackageStats stats = new PackageStats(packageName, userHandle);
13233
13234        /*
13235         * Queue up an async operation since the package measurement may take a
13236         * little while.
13237         */
13238        Message msg = mHandler.obtainMessage(INIT_COPY);
13239        msg.obj = new MeasureParams(stats, observer);
13240        mHandler.sendMessage(msg);
13241    }
13242
13243    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13244            PackageStats pStats) {
13245        if (packageName == null) {
13246            Slog.w(TAG, "Attempt to get size of null packageName.");
13247            return false;
13248        }
13249        PackageParser.Package p;
13250        boolean dataOnly = false;
13251        String libDirRoot = null;
13252        String asecPath = null;
13253        PackageSetting ps = null;
13254        synchronized (mPackages) {
13255            p = mPackages.get(packageName);
13256            ps = mSettings.mPackages.get(packageName);
13257            if(p == null) {
13258                dataOnly = true;
13259                if((ps == null) || (ps.pkg == null)) {
13260                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13261                    return false;
13262                }
13263                p = ps.pkg;
13264            }
13265            if (ps != null) {
13266                libDirRoot = ps.legacyNativeLibraryPathString;
13267            }
13268            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13269                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13270                if (secureContainerId != null) {
13271                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13272                }
13273            }
13274        }
13275        String publicSrcDir = null;
13276        if(!dataOnly) {
13277            final ApplicationInfo applicationInfo = p.applicationInfo;
13278            if (applicationInfo == null) {
13279                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13280                return false;
13281            }
13282            if (p.isForwardLocked()) {
13283                publicSrcDir = applicationInfo.getBaseResourcePath();
13284            }
13285        }
13286        // TODO: extend to measure size of split APKs
13287        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13288        // not just the first level.
13289        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13290        // just the primary.
13291        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13292        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13293                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13294        if (res < 0) {
13295            return false;
13296        }
13297
13298        // Fix-up for forward-locked applications in ASEC containers.
13299        if (!isExternal(p)) {
13300            pStats.codeSize += pStats.externalCodeSize;
13301            pStats.externalCodeSize = 0L;
13302        }
13303
13304        return true;
13305    }
13306
13307
13308    @Override
13309    public void addPackageToPreferred(String packageName) {
13310        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13311    }
13312
13313    @Override
13314    public void removePackageFromPreferred(String packageName) {
13315        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13316    }
13317
13318    @Override
13319    public List<PackageInfo> getPreferredPackages(int flags) {
13320        return new ArrayList<PackageInfo>();
13321    }
13322
13323    private int getUidTargetSdkVersionLockedLPr(int uid) {
13324        Object obj = mSettings.getUserIdLPr(uid);
13325        if (obj instanceof SharedUserSetting) {
13326            final SharedUserSetting sus = (SharedUserSetting) obj;
13327            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13328            final Iterator<PackageSetting> it = sus.packages.iterator();
13329            while (it.hasNext()) {
13330                final PackageSetting ps = it.next();
13331                if (ps.pkg != null) {
13332                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13333                    if (v < vers) vers = v;
13334                }
13335            }
13336            return vers;
13337        } else if (obj instanceof PackageSetting) {
13338            final PackageSetting ps = (PackageSetting) obj;
13339            if (ps.pkg != null) {
13340                return ps.pkg.applicationInfo.targetSdkVersion;
13341            }
13342        }
13343        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13344    }
13345
13346    @Override
13347    public void addPreferredActivity(IntentFilter filter, int match,
13348            ComponentName[] set, ComponentName activity, int userId) {
13349        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13350                "Adding preferred");
13351    }
13352
13353    private void addPreferredActivityInternal(IntentFilter filter, int match,
13354            ComponentName[] set, ComponentName activity, boolean always, int userId,
13355            String opname) {
13356        // writer
13357        int callingUid = Binder.getCallingUid();
13358        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13359        if (filter.countActions() == 0) {
13360            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13361            return;
13362        }
13363        synchronized (mPackages) {
13364            if (mContext.checkCallingOrSelfPermission(
13365                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13366                    != PackageManager.PERMISSION_GRANTED) {
13367                if (getUidTargetSdkVersionLockedLPr(callingUid)
13368                        < Build.VERSION_CODES.FROYO) {
13369                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13370                            + callingUid);
13371                    return;
13372                }
13373                mContext.enforceCallingOrSelfPermission(
13374                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13375            }
13376
13377            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13378            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13379                    + userId + ":");
13380            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13381            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13382            scheduleWritePackageRestrictionsLocked(userId);
13383        }
13384    }
13385
13386    @Override
13387    public void replacePreferredActivity(IntentFilter filter, int match,
13388            ComponentName[] set, ComponentName activity, int userId) {
13389        if (filter.countActions() != 1) {
13390            throw new IllegalArgumentException(
13391                    "replacePreferredActivity expects filter to have only 1 action.");
13392        }
13393        if (filter.countDataAuthorities() != 0
13394                || filter.countDataPaths() != 0
13395                || filter.countDataSchemes() > 1
13396                || filter.countDataTypes() != 0) {
13397            throw new IllegalArgumentException(
13398                    "replacePreferredActivity expects filter to have no data authorities, " +
13399                    "paths, or types; and at most one scheme.");
13400        }
13401
13402        final int callingUid = Binder.getCallingUid();
13403        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13404        synchronized (mPackages) {
13405            if (mContext.checkCallingOrSelfPermission(
13406                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13407                    != PackageManager.PERMISSION_GRANTED) {
13408                if (getUidTargetSdkVersionLockedLPr(callingUid)
13409                        < Build.VERSION_CODES.FROYO) {
13410                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13411                            + Binder.getCallingUid());
13412                    return;
13413                }
13414                mContext.enforceCallingOrSelfPermission(
13415                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13416            }
13417
13418            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13419            if (pir != null) {
13420                // Get all of the existing entries that exactly match this filter.
13421                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13422                if (existing != null && existing.size() == 1) {
13423                    PreferredActivity cur = existing.get(0);
13424                    if (DEBUG_PREFERRED) {
13425                        Slog.i(TAG, "Checking replace of preferred:");
13426                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13427                        if (!cur.mPref.mAlways) {
13428                            Slog.i(TAG, "  -- CUR; not mAlways!");
13429                        } else {
13430                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13431                            Slog.i(TAG, "  -- CUR: mSet="
13432                                    + Arrays.toString(cur.mPref.mSetComponents));
13433                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13434                            Slog.i(TAG, "  -- NEW: mMatch="
13435                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13436                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13437                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13438                        }
13439                    }
13440                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13441                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13442                            && cur.mPref.sameSet(set)) {
13443                        // Setting the preferred activity to what it happens to be already
13444                        if (DEBUG_PREFERRED) {
13445                            Slog.i(TAG, "Replacing with same preferred activity "
13446                                    + cur.mPref.mShortComponent + " for user "
13447                                    + userId + ":");
13448                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13449                        }
13450                        return;
13451                    }
13452                }
13453
13454                if (existing != null) {
13455                    if (DEBUG_PREFERRED) {
13456                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13457                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13458                    }
13459                    for (int i = 0; i < existing.size(); i++) {
13460                        PreferredActivity pa = existing.get(i);
13461                        if (DEBUG_PREFERRED) {
13462                            Slog.i(TAG, "Removing existing preferred activity "
13463                                    + pa.mPref.mComponent + ":");
13464                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13465                        }
13466                        pir.removeFilter(pa);
13467                    }
13468                }
13469            }
13470            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13471                    "Replacing preferred");
13472        }
13473    }
13474
13475    @Override
13476    public void clearPackagePreferredActivities(String packageName) {
13477        final int uid = Binder.getCallingUid();
13478        // writer
13479        synchronized (mPackages) {
13480            PackageParser.Package pkg = mPackages.get(packageName);
13481            if (pkg == null || pkg.applicationInfo.uid != uid) {
13482                if (mContext.checkCallingOrSelfPermission(
13483                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13484                        != PackageManager.PERMISSION_GRANTED) {
13485                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13486                            < Build.VERSION_CODES.FROYO) {
13487                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13488                                + Binder.getCallingUid());
13489                        return;
13490                    }
13491                    mContext.enforceCallingOrSelfPermission(
13492                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13493                }
13494            }
13495
13496            int user = UserHandle.getCallingUserId();
13497            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13498                scheduleWritePackageRestrictionsLocked(user);
13499            }
13500        }
13501    }
13502
13503    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13504    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13505        ArrayList<PreferredActivity> removed = null;
13506        boolean changed = false;
13507        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13508            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13509            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13510            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13511                continue;
13512            }
13513            Iterator<PreferredActivity> it = pir.filterIterator();
13514            while (it.hasNext()) {
13515                PreferredActivity pa = it.next();
13516                // Mark entry for removal only if it matches the package name
13517                // and the entry is of type "always".
13518                if (packageName == null ||
13519                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13520                                && pa.mPref.mAlways)) {
13521                    if (removed == null) {
13522                        removed = new ArrayList<PreferredActivity>();
13523                    }
13524                    removed.add(pa);
13525                }
13526            }
13527            if (removed != null) {
13528                for (int j=0; j<removed.size(); j++) {
13529                    PreferredActivity pa = removed.get(j);
13530                    pir.removeFilter(pa);
13531                }
13532                changed = true;
13533            }
13534        }
13535        return changed;
13536    }
13537
13538    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13539    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13540        if (userId == UserHandle.USER_ALL) {
13541            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13542                    sUserManager.getUserIds())) {
13543                for (int oneUserId : sUserManager.getUserIds()) {
13544                    scheduleWritePackageRestrictionsLocked(oneUserId);
13545                }
13546            }
13547        } else {
13548            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13549                scheduleWritePackageRestrictionsLocked(userId);
13550            }
13551        }
13552    }
13553
13554
13555    void clearDefaultBrowserIfNeeded(String packageName) {
13556        for (int oneUserId : sUserManager.getUserIds()) {
13557            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13558            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13559            if (packageName.equals(defaultBrowserPackageName)) {
13560                setDefaultBrowserPackageName(null, oneUserId);
13561            }
13562        }
13563    }
13564
13565    @Override
13566    public void resetPreferredActivities(int userId) {
13567        mContext.enforceCallingOrSelfPermission(
13568                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13569        // writer
13570        synchronized (mPackages) {
13571            clearPackagePreferredActivitiesLPw(null, userId);
13572            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13573            applyFactoryDefaultBrowserLPw(userId);
13574
13575            scheduleWritePackageRestrictionsLocked(userId);
13576        }
13577    }
13578
13579    @Override
13580    public int getPreferredActivities(List<IntentFilter> outFilters,
13581            List<ComponentName> outActivities, String packageName) {
13582
13583        int num = 0;
13584        final int userId = UserHandle.getCallingUserId();
13585        // reader
13586        synchronized (mPackages) {
13587            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13588            if (pir != null) {
13589                final Iterator<PreferredActivity> it = pir.filterIterator();
13590                while (it.hasNext()) {
13591                    final PreferredActivity pa = it.next();
13592                    if (packageName == null
13593                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13594                                    && pa.mPref.mAlways)) {
13595                        if (outFilters != null) {
13596                            outFilters.add(new IntentFilter(pa));
13597                        }
13598                        if (outActivities != null) {
13599                            outActivities.add(pa.mPref.mComponent);
13600                        }
13601                    }
13602                }
13603            }
13604        }
13605
13606        return num;
13607    }
13608
13609    @Override
13610    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13611            int userId) {
13612        int callingUid = Binder.getCallingUid();
13613        if (callingUid != Process.SYSTEM_UID) {
13614            throw new SecurityException(
13615                    "addPersistentPreferredActivity can only be run by the system");
13616        }
13617        if (filter.countActions() == 0) {
13618            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13619            return;
13620        }
13621        synchronized (mPackages) {
13622            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13623                    " :");
13624            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13625            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13626                    new PersistentPreferredActivity(filter, activity));
13627            scheduleWritePackageRestrictionsLocked(userId);
13628        }
13629    }
13630
13631    @Override
13632    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13633        int callingUid = Binder.getCallingUid();
13634        if (callingUid != Process.SYSTEM_UID) {
13635            throw new SecurityException(
13636                    "clearPackagePersistentPreferredActivities can only be run by the system");
13637        }
13638        ArrayList<PersistentPreferredActivity> removed = null;
13639        boolean changed = false;
13640        synchronized (mPackages) {
13641            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13642                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13643                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13644                        .valueAt(i);
13645                if (userId != thisUserId) {
13646                    continue;
13647                }
13648                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13649                while (it.hasNext()) {
13650                    PersistentPreferredActivity ppa = it.next();
13651                    // Mark entry for removal only if it matches the package name.
13652                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13653                        if (removed == null) {
13654                            removed = new ArrayList<PersistentPreferredActivity>();
13655                        }
13656                        removed.add(ppa);
13657                    }
13658                }
13659                if (removed != null) {
13660                    for (int j=0; j<removed.size(); j++) {
13661                        PersistentPreferredActivity ppa = removed.get(j);
13662                        ppir.removeFilter(ppa);
13663                    }
13664                    changed = true;
13665                }
13666            }
13667
13668            if (changed) {
13669                scheduleWritePackageRestrictionsLocked(userId);
13670            }
13671        }
13672    }
13673
13674    /**
13675     * Common machinery for picking apart a restored XML blob and passing
13676     * it to a caller-supplied functor to be applied to the running system.
13677     */
13678    private void restoreFromXml(XmlPullParser parser, int userId,
13679            String expectedStartTag, BlobXmlRestorer functor)
13680            throws IOException, XmlPullParserException {
13681        int type;
13682        while ((type = parser.next()) != XmlPullParser.START_TAG
13683                && type != XmlPullParser.END_DOCUMENT) {
13684        }
13685        if (type != XmlPullParser.START_TAG) {
13686            // oops didn't find a start tag?!
13687            if (DEBUG_BACKUP) {
13688                Slog.e(TAG, "Didn't find start tag during restore");
13689            }
13690            return;
13691        }
13692
13693        // this is supposed to be TAG_PREFERRED_BACKUP
13694        if (!expectedStartTag.equals(parser.getName())) {
13695            if (DEBUG_BACKUP) {
13696                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13697            }
13698            return;
13699        }
13700
13701        // skip interfering stuff, then we're aligned with the backing implementation
13702        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13703        functor.apply(parser, userId);
13704    }
13705
13706    private interface BlobXmlRestorer {
13707        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13708    }
13709
13710    /**
13711     * Non-Binder method, support for the backup/restore mechanism: write the
13712     * full set of preferred activities in its canonical XML format.  Returns the
13713     * XML output as a byte array, or null if there is none.
13714     */
13715    @Override
13716    public byte[] getPreferredActivityBackup(int userId) {
13717        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13718            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13719        }
13720
13721        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13722        try {
13723            final XmlSerializer serializer = new FastXmlSerializer();
13724            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13725            serializer.startDocument(null, true);
13726            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13727
13728            synchronized (mPackages) {
13729                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13730            }
13731
13732            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13733            serializer.endDocument();
13734            serializer.flush();
13735        } catch (Exception e) {
13736            if (DEBUG_BACKUP) {
13737                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13738            }
13739            return null;
13740        }
13741
13742        return dataStream.toByteArray();
13743    }
13744
13745    @Override
13746    public void restorePreferredActivities(byte[] backup, int userId) {
13747        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13748            throw new SecurityException("Only the system may call restorePreferredActivities()");
13749        }
13750
13751        try {
13752            final XmlPullParser parser = Xml.newPullParser();
13753            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13754            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13755                    new BlobXmlRestorer() {
13756                        @Override
13757                        public void apply(XmlPullParser parser, int userId)
13758                                throws XmlPullParserException, IOException {
13759                            synchronized (mPackages) {
13760                                mSettings.readPreferredActivitiesLPw(parser, userId);
13761                            }
13762                        }
13763                    } );
13764        } catch (Exception e) {
13765            if (DEBUG_BACKUP) {
13766                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13767            }
13768        }
13769    }
13770
13771    /**
13772     * Non-Binder method, support for the backup/restore mechanism: write the
13773     * default browser (etc) settings in its canonical XML format.  Returns the default
13774     * browser XML representation as a byte array, or null if there is none.
13775     */
13776    @Override
13777    public byte[] getDefaultAppsBackup(int userId) {
13778        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13779            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13780        }
13781
13782        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13783        try {
13784            final XmlSerializer serializer = new FastXmlSerializer();
13785            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13786            serializer.startDocument(null, true);
13787            serializer.startTag(null, TAG_DEFAULT_APPS);
13788
13789            synchronized (mPackages) {
13790                mSettings.writeDefaultAppsLPr(serializer, userId);
13791            }
13792
13793            serializer.endTag(null, TAG_DEFAULT_APPS);
13794            serializer.endDocument();
13795            serializer.flush();
13796        } catch (Exception e) {
13797            if (DEBUG_BACKUP) {
13798                Slog.e(TAG, "Unable to write default apps for backup", e);
13799            }
13800            return null;
13801        }
13802
13803        return dataStream.toByteArray();
13804    }
13805
13806    @Override
13807    public void restoreDefaultApps(byte[] backup, int userId) {
13808        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13809            throw new SecurityException("Only the system may call restoreDefaultApps()");
13810        }
13811
13812        try {
13813            final XmlPullParser parser = Xml.newPullParser();
13814            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13815            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13816                    new BlobXmlRestorer() {
13817                        @Override
13818                        public void apply(XmlPullParser parser, int userId)
13819                                throws XmlPullParserException, IOException {
13820                            synchronized (mPackages) {
13821                                mSettings.readDefaultAppsLPw(parser, userId);
13822                            }
13823                        }
13824                    } );
13825        } catch (Exception e) {
13826            if (DEBUG_BACKUP) {
13827                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13828            }
13829        }
13830    }
13831
13832    @Override
13833    public byte[] getIntentFilterVerificationBackup(int userId) {
13834        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13835            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
13836        }
13837
13838        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13839        try {
13840            final XmlSerializer serializer = new FastXmlSerializer();
13841            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13842            serializer.startDocument(null, true);
13843            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
13844
13845            synchronized (mPackages) {
13846                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
13847            }
13848
13849            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
13850            serializer.endDocument();
13851            serializer.flush();
13852        } catch (Exception e) {
13853            if (DEBUG_BACKUP) {
13854                Slog.e(TAG, "Unable to write default apps for backup", e);
13855            }
13856            return null;
13857        }
13858
13859        return dataStream.toByteArray();
13860    }
13861
13862    @Override
13863    public void restoreIntentFilterVerification(byte[] backup, int userId) {
13864        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13865            throw new SecurityException("Only the system may call restorePreferredActivities()");
13866        }
13867
13868        try {
13869            final XmlPullParser parser = Xml.newPullParser();
13870            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13871            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
13872                    new BlobXmlRestorer() {
13873                        @Override
13874                        public void apply(XmlPullParser parser, int userId)
13875                                throws XmlPullParserException, IOException {
13876                            synchronized (mPackages) {
13877                                mSettings.readAllDomainVerificationsLPr(parser, userId);
13878                                mSettings.writeLPr();
13879                            }
13880                        }
13881                    } );
13882        } catch (Exception e) {
13883            if (DEBUG_BACKUP) {
13884                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13885            }
13886        }
13887    }
13888
13889    @Override
13890    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13891            int sourceUserId, int targetUserId, int flags) {
13892        mContext.enforceCallingOrSelfPermission(
13893                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13894        int callingUid = Binder.getCallingUid();
13895        enforceOwnerRights(ownerPackage, callingUid);
13896        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13897        if (intentFilter.countActions() == 0) {
13898            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13899            return;
13900        }
13901        synchronized (mPackages) {
13902            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13903                    ownerPackage, targetUserId, flags);
13904            CrossProfileIntentResolver resolver =
13905                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13906            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13907            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13908            if (existing != null) {
13909                int size = existing.size();
13910                for (int i = 0; i < size; i++) {
13911                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13912                        return;
13913                    }
13914                }
13915            }
13916            resolver.addFilter(newFilter);
13917            scheduleWritePackageRestrictionsLocked(sourceUserId);
13918        }
13919    }
13920
13921    @Override
13922    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13923        mContext.enforceCallingOrSelfPermission(
13924                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13925        int callingUid = Binder.getCallingUid();
13926        enforceOwnerRights(ownerPackage, callingUid);
13927        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13928        synchronized (mPackages) {
13929            CrossProfileIntentResolver resolver =
13930                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13931            ArraySet<CrossProfileIntentFilter> set =
13932                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13933            for (CrossProfileIntentFilter filter : set) {
13934                if (filter.getOwnerPackage().equals(ownerPackage)) {
13935                    resolver.removeFilter(filter);
13936                }
13937            }
13938            scheduleWritePackageRestrictionsLocked(sourceUserId);
13939        }
13940    }
13941
13942    // Enforcing that callingUid is owning pkg on userId
13943    private void enforceOwnerRights(String pkg, int callingUid) {
13944        // The system owns everything.
13945        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13946            return;
13947        }
13948        int callingUserId = UserHandle.getUserId(callingUid);
13949        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13950        if (pi == null) {
13951            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13952                    + callingUserId);
13953        }
13954        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13955            throw new SecurityException("Calling uid " + callingUid
13956                    + " does not own package " + pkg);
13957        }
13958    }
13959
13960    @Override
13961    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13962        Intent intent = new Intent(Intent.ACTION_MAIN);
13963        intent.addCategory(Intent.CATEGORY_HOME);
13964
13965        final int callingUserId = UserHandle.getCallingUserId();
13966        List<ResolveInfo> list = queryIntentActivities(intent, null,
13967                PackageManager.GET_META_DATA, callingUserId);
13968        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13969                true, false, false, callingUserId);
13970
13971        allHomeCandidates.clear();
13972        if (list != null) {
13973            for (ResolveInfo ri : list) {
13974                allHomeCandidates.add(ri);
13975            }
13976        }
13977        return (preferred == null || preferred.activityInfo == null)
13978                ? null
13979                : new ComponentName(preferred.activityInfo.packageName,
13980                        preferred.activityInfo.name);
13981    }
13982
13983    @Override
13984    public void setApplicationEnabledSetting(String appPackageName,
13985            int newState, int flags, int userId, String callingPackage) {
13986        if (!sUserManager.exists(userId)) return;
13987        if (callingPackage == null) {
13988            callingPackage = Integer.toString(Binder.getCallingUid());
13989        }
13990        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13991    }
13992
13993    @Override
13994    public void setComponentEnabledSetting(ComponentName componentName,
13995            int newState, int flags, int userId) {
13996        if (!sUserManager.exists(userId)) return;
13997        setEnabledSetting(componentName.getPackageName(),
13998                componentName.getClassName(), newState, flags, userId, null);
13999    }
14000
14001    private void setEnabledSetting(final String packageName, String className, int newState,
14002            final int flags, int userId, String callingPackage) {
14003        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14004              || newState == COMPONENT_ENABLED_STATE_ENABLED
14005              || newState == COMPONENT_ENABLED_STATE_DISABLED
14006              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14007              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14008            throw new IllegalArgumentException("Invalid new component state: "
14009                    + newState);
14010        }
14011        PackageSetting pkgSetting;
14012        final int uid = Binder.getCallingUid();
14013        final int permission = mContext.checkCallingOrSelfPermission(
14014                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14015        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14016        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14017        boolean sendNow = false;
14018        boolean isApp = (className == null);
14019        String componentName = isApp ? packageName : className;
14020        int packageUid = -1;
14021        ArrayList<String> components;
14022
14023        // writer
14024        synchronized (mPackages) {
14025            pkgSetting = mSettings.mPackages.get(packageName);
14026            if (pkgSetting == null) {
14027                if (className == null) {
14028                    throw new IllegalArgumentException(
14029                            "Unknown package: " + packageName);
14030                }
14031                throw new IllegalArgumentException(
14032                        "Unknown component: " + packageName
14033                        + "/" + className);
14034            }
14035            // Allow root and verify that userId is not being specified by a different user
14036            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14037                throw new SecurityException(
14038                        "Permission Denial: attempt to change component state from pid="
14039                        + Binder.getCallingPid()
14040                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14041            }
14042            if (className == null) {
14043                // We're dealing with an application/package level state change
14044                if (pkgSetting.getEnabled(userId) == newState) {
14045                    // Nothing to do
14046                    return;
14047                }
14048                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14049                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14050                    // Don't care about who enables an app.
14051                    callingPackage = null;
14052                }
14053                pkgSetting.setEnabled(newState, userId, callingPackage);
14054                // pkgSetting.pkg.mSetEnabled = newState;
14055            } else {
14056                // We're dealing with a component level state change
14057                // First, verify that this is a valid class name.
14058                PackageParser.Package pkg = pkgSetting.pkg;
14059                if (pkg == null || !pkg.hasComponentClassName(className)) {
14060                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14061                        throw new IllegalArgumentException("Component class " + className
14062                                + " does not exist in " + packageName);
14063                    } else {
14064                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14065                                + className + " does not exist in " + packageName);
14066                    }
14067                }
14068                switch (newState) {
14069                case COMPONENT_ENABLED_STATE_ENABLED:
14070                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14071                        return;
14072                    }
14073                    break;
14074                case COMPONENT_ENABLED_STATE_DISABLED:
14075                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14076                        return;
14077                    }
14078                    break;
14079                case COMPONENT_ENABLED_STATE_DEFAULT:
14080                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14081                        return;
14082                    }
14083                    break;
14084                default:
14085                    Slog.e(TAG, "Invalid new component state: " + newState);
14086                    return;
14087                }
14088            }
14089            scheduleWritePackageRestrictionsLocked(userId);
14090            components = mPendingBroadcasts.get(userId, packageName);
14091            final boolean newPackage = components == null;
14092            if (newPackage) {
14093                components = new ArrayList<String>();
14094            }
14095            if (!components.contains(componentName)) {
14096                components.add(componentName);
14097            }
14098            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14099                sendNow = true;
14100                // Purge entry from pending broadcast list if another one exists already
14101                // since we are sending one right away.
14102                mPendingBroadcasts.remove(userId, packageName);
14103            } else {
14104                if (newPackage) {
14105                    mPendingBroadcasts.put(userId, packageName, components);
14106                }
14107                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14108                    // Schedule a message
14109                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14110                }
14111            }
14112        }
14113
14114        long callingId = Binder.clearCallingIdentity();
14115        try {
14116            if (sendNow) {
14117                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14118                sendPackageChangedBroadcast(packageName,
14119                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14120            }
14121        } finally {
14122            Binder.restoreCallingIdentity(callingId);
14123        }
14124    }
14125
14126    private void sendPackageChangedBroadcast(String packageName,
14127            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14128        if (DEBUG_INSTALL)
14129            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14130                    + componentNames);
14131        Bundle extras = new Bundle(4);
14132        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14133        String nameList[] = new String[componentNames.size()];
14134        componentNames.toArray(nameList);
14135        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14136        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14137        extras.putInt(Intent.EXTRA_UID, packageUid);
14138        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14139                new int[] {UserHandle.getUserId(packageUid)});
14140    }
14141
14142    @Override
14143    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14144        if (!sUserManager.exists(userId)) return;
14145        final int uid = Binder.getCallingUid();
14146        final int permission = mContext.checkCallingOrSelfPermission(
14147                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14148        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14149        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14150        // writer
14151        synchronized (mPackages) {
14152            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14153                    allowedByPermission, uid, userId)) {
14154                scheduleWritePackageRestrictionsLocked(userId);
14155            }
14156        }
14157    }
14158
14159    @Override
14160    public String getInstallerPackageName(String packageName) {
14161        // reader
14162        synchronized (mPackages) {
14163            return mSettings.getInstallerPackageNameLPr(packageName);
14164        }
14165    }
14166
14167    @Override
14168    public int getApplicationEnabledSetting(String packageName, int userId) {
14169        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14170        int uid = Binder.getCallingUid();
14171        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14172        // reader
14173        synchronized (mPackages) {
14174            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14175        }
14176    }
14177
14178    @Override
14179    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14180        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14181        int uid = Binder.getCallingUid();
14182        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14183        // reader
14184        synchronized (mPackages) {
14185            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14186        }
14187    }
14188
14189    @Override
14190    public void enterSafeMode() {
14191        enforceSystemOrRoot("Only the system can request entering safe mode");
14192
14193        if (!mSystemReady) {
14194            mSafeMode = true;
14195        }
14196    }
14197
14198    @Override
14199    public void systemReady() {
14200        mSystemReady = true;
14201
14202        // Read the compatibilty setting when the system is ready.
14203        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14204                mContext.getContentResolver(),
14205                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14206        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14207        if (DEBUG_SETTINGS) {
14208            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14209        }
14210
14211        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14212
14213        synchronized (mPackages) {
14214            // Verify that all of the preferred activity components actually
14215            // exist.  It is possible for applications to be updated and at
14216            // that point remove a previously declared activity component that
14217            // had been set as a preferred activity.  We try to clean this up
14218            // the next time we encounter that preferred activity, but it is
14219            // possible for the user flow to never be able to return to that
14220            // situation so here we do a sanity check to make sure we haven't
14221            // left any junk around.
14222            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14223            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14224                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14225                removed.clear();
14226                for (PreferredActivity pa : pir.filterSet()) {
14227                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14228                        removed.add(pa);
14229                    }
14230                }
14231                if (removed.size() > 0) {
14232                    for (int r=0; r<removed.size(); r++) {
14233                        PreferredActivity pa = removed.get(r);
14234                        Slog.w(TAG, "Removing dangling preferred activity: "
14235                                + pa.mPref.mComponent);
14236                        pir.removeFilter(pa);
14237                    }
14238                    mSettings.writePackageRestrictionsLPr(
14239                            mSettings.mPreferredActivities.keyAt(i));
14240                }
14241            }
14242
14243            for (int userId : UserManagerService.getInstance().getUserIds()) {
14244                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14245                    grantPermissionsUserIds = ArrayUtils.appendInt(
14246                            grantPermissionsUserIds, userId);
14247                }
14248            }
14249        }
14250        sUserManager.systemReady();
14251
14252        // If we upgraded grant all default permissions before kicking off.
14253        for (int userId : grantPermissionsUserIds) {
14254            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14255        }
14256
14257        // Kick off any messages waiting for system ready
14258        if (mPostSystemReadyMessages != null) {
14259            for (Message msg : mPostSystemReadyMessages) {
14260                msg.sendToTarget();
14261            }
14262            mPostSystemReadyMessages = null;
14263        }
14264
14265        // Watch for external volumes that come and go over time
14266        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14267        storage.registerListener(mStorageListener);
14268
14269        mInstallerService.systemReady();
14270        mPackageDexOptimizer.systemReady();
14271    }
14272
14273    @Override
14274    public boolean isSafeMode() {
14275        return mSafeMode;
14276    }
14277
14278    @Override
14279    public boolean hasSystemUidErrors() {
14280        return mHasSystemUidErrors;
14281    }
14282
14283    static String arrayToString(int[] array) {
14284        StringBuffer buf = new StringBuffer(128);
14285        buf.append('[');
14286        if (array != null) {
14287            for (int i=0; i<array.length; i++) {
14288                if (i > 0) buf.append(", ");
14289                buf.append(array[i]);
14290            }
14291        }
14292        buf.append(']');
14293        return buf.toString();
14294    }
14295
14296    static class DumpState {
14297        public static final int DUMP_LIBS = 1 << 0;
14298        public static final int DUMP_FEATURES = 1 << 1;
14299        public static final int DUMP_RESOLVERS = 1 << 2;
14300        public static final int DUMP_PERMISSIONS = 1 << 3;
14301        public static final int DUMP_PACKAGES = 1 << 4;
14302        public static final int DUMP_SHARED_USERS = 1 << 5;
14303        public static final int DUMP_MESSAGES = 1 << 6;
14304        public static final int DUMP_PROVIDERS = 1 << 7;
14305        public static final int DUMP_VERIFIERS = 1 << 8;
14306        public static final int DUMP_PREFERRED = 1 << 9;
14307        public static final int DUMP_PREFERRED_XML = 1 << 10;
14308        public static final int DUMP_KEYSETS = 1 << 11;
14309        public static final int DUMP_VERSION = 1 << 12;
14310        public static final int DUMP_INSTALLS = 1 << 13;
14311        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14312        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14313
14314        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14315
14316        private int mTypes;
14317
14318        private int mOptions;
14319
14320        private boolean mTitlePrinted;
14321
14322        private SharedUserSetting mSharedUser;
14323
14324        public boolean isDumping(int type) {
14325            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14326                return true;
14327            }
14328
14329            return (mTypes & type) != 0;
14330        }
14331
14332        public void setDump(int type) {
14333            mTypes |= type;
14334        }
14335
14336        public boolean isOptionEnabled(int option) {
14337            return (mOptions & option) != 0;
14338        }
14339
14340        public void setOptionEnabled(int option) {
14341            mOptions |= option;
14342        }
14343
14344        public boolean onTitlePrinted() {
14345            final boolean printed = mTitlePrinted;
14346            mTitlePrinted = true;
14347            return printed;
14348        }
14349
14350        public boolean getTitlePrinted() {
14351            return mTitlePrinted;
14352        }
14353
14354        public void setTitlePrinted(boolean enabled) {
14355            mTitlePrinted = enabled;
14356        }
14357
14358        public SharedUserSetting getSharedUser() {
14359            return mSharedUser;
14360        }
14361
14362        public void setSharedUser(SharedUserSetting user) {
14363            mSharedUser = user;
14364        }
14365    }
14366
14367    @Override
14368    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14369        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14370                != PackageManager.PERMISSION_GRANTED) {
14371            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14372                    + Binder.getCallingPid()
14373                    + ", uid=" + Binder.getCallingUid()
14374                    + " without permission "
14375                    + android.Manifest.permission.DUMP);
14376            return;
14377        }
14378
14379        DumpState dumpState = new DumpState();
14380        boolean fullPreferred = false;
14381        boolean checkin = false;
14382
14383        String packageName = null;
14384        ArraySet<String> permissionNames = null;
14385
14386        int opti = 0;
14387        while (opti < args.length) {
14388            String opt = args[opti];
14389            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14390                break;
14391            }
14392            opti++;
14393
14394            if ("-a".equals(opt)) {
14395                // Right now we only know how to print all.
14396            } else if ("-h".equals(opt)) {
14397                pw.println("Package manager dump options:");
14398                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14399                pw.println("    --checkin: dump for a checkin");
14400                pw.println("    -f: print details of intent filters");
14401                pw.println("    -h: print this help");
14402                pw.println("  cmd may be one of:");
14403                pw.println("    l[ibraries]: list known shared libraries");
14404                pw.println("    f[ibraries]: list device features");
14405                pw.println("    k[eysets]: print known keysets");
14406                pw.println("    r[esolvers]: dump intent resolvers");
14407                pw.println("    perm[issions]: dump permissions");
14408                pw.println("    permission [name ...]: dump declaration and use of given permission");
14409                pw.println("    pref[erred]: print preferred package settings");
14410                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14411                pw.println("    prov[iders]: dump content providers");
14412                pw.println("    p[ackages]: dump installed packages");
14413                pw.println("    s[hared-users]: dump shared user IDs");
14414                pw.println("    m[essages]: print collected runtime messages");
14415                pw.println("    v[erifiers]: print package verifier info");
14416                pw.println("    version: print database version info");
14417                pw.println("    write: write current settings now");
14418                pw.println("    <package.name>: info about given package");
14419                pw.println("    installs: details about install sessions");
14420                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14421                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14422                return;
14423            } else if ("--checkin".equals(opt)) {
14424                checkin = true;
14425            } else if ("-f".equals(opt)) {
14426                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14427            } else {
14428                pw.println("Unknown argument: " + opt + "; use -h for help");
14429            }
14430        }
14431
14432        // Is the caller requesting to dump a particular piece of data?
14433        if (opti < args.length) {
14434            String cmd = args[opti];
14435            opti++;
14436            // Is this a package name?
14437            if ("android".equals(cmd) || cmd.contains(".")) {
14438                packageName = cmd;
14439                // When dumping a single package, we always dump all of its
14440                // filter information since the amount of data will be reasonable.
14441                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14442            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14443                dumpState.setDump(DumpState.DUMP_LIBS);
14444            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14445                dumpState.setDump(DumpState.DUMP_FEATURES);
14446            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14447                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14448            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14449                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14450            } else if ("permission".equals(cmd)) {
14451                if (opti >= args.length) {
14452                    pw.println("Error: permission requires permission name");
14453                    return;
14454                }
14455                permissionNames = new ArraySet<>();
14456                while (opti < args.length) {
14457                    permissionNames.add(args[opti]);
14458                    opti++;
14459                }
14460                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14461                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14462            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14463                dumpState.setDump(DumpState.DUMP_PREFERRED);
14464            } else if ("preferred-xml".equals(cmd)) {
14465                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14466                if (opti < args.length && "--full".equals(args[opti])) {
14467                    fullPreferred = true;
14468                    opti++;
14469                }
14470            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14471                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14472            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14473                dumpState.setDump(DumpState.DUMP_PACKAGES);
14474            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14475                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14476            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14477                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14478            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14479                dumpState.setDump(DumpState.DUMP_MESSAGES);
14480            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14481                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14482            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14483                    || "intent-filter-verifiers".equals(cmd)) {
14484                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14485            } else if ("version".equals(cmd)) {
14486                dumpState.setDump(DumpState.DUMP_VERSION);
14487            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14488                dumpState.setDump(DumpState.DUMP_KEYSETS);
14489            } else if ("installs".equals(cmd)) {
14490                dumpState.setDump(DumpState.DUMP_INSTALLS);
14491            } else if ("write".equals(cmd)) {
14492                synchronized (mPackages) {
14493                    mSettings.writeLPr();
14494                    pw.println("Settings written.");
14495                    return;
14496                }
14497            }
14498        }
14499
14500        if (checkin) {
14501            pw.println("vers,1");
14502        }
14503
14504        // reader
14505        synchronized (mPackages) {
14506            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14507                if (!checkin) {
14508                    if (dumpState.onTitlePrinted())
14509                        pw.println();
14510                    pw.println("Database versions:");
14511                    pw.print("  SDK Version:");
14512                    pw.print(" internal=");
14513                    pw.print(mSettings.mInternalSdkPlatform);
14514                    pw.print(" external=");
14515                    pw.println(mSettings.mExternalSdkPlatform);
14516                    pw.print("  DB Version:");
14517                    pw.print(" internal=");
14518                    pw.print(mSettings.mInternalDatabaseVersion);
14519                    pw.print(" external=");
14520                    pw.println(mSettings.mExternalDatabaseVersion);
14521                }
14522            }
14523
14524            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14525                if (!checkin) {
14526                    if (dumpState.onTitlePrinted())
14527                        pw.println();
14528                    pw.println("Verifiers:");
14529                    pw.print("  Required: ");
14530                    pw.print(mRequiredVerifierPackage);
14531                    pw.print(" (uid=");
14532                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14533                    pw.println(")");
14534                } else if (mRequiredVerifierPackage != null) {
14535                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14536                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14537                }
14538            }
14539
14540            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14541                    packageName == null) {
14542                if (mIntentFilterVerifierComponent != null) {
14543                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14544                    if (!checkin) {
14545                        if (dumpState.onTitlePrinted())
14546                            pw.println();
14547                        pw.println("Intent Filter Verifier:");
14548                        pw.print("  Using: ");
14549                        pw.print(verifierPackageName);
14550                        pw.print(" (uid=");
14551                        pw.print(getPackageUid(verifierPackageName, 0));
14552                        pw.println(")");
14553                    } else if (verifierPackageName != null) {
14554                        pw.print("ifv,"); pw.print(verifierPackageName);
14555                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14556                    }
14557                } else {
14558                    pw.println();
14559                    pw.println("No Intent Filter Verifier available!");
14560                }
14561            }
14562
14563            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14564                boolean printedHeader = false;
14565                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14566                while (it.hasNext()) {
14567                    String name = it.next();
14568                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14569                    if (!checkin) {
14570                        if (!printedHeader) {
14571                            if (dumpState.onTitlePrinted())
14572                                pw.println();
14573                            pw.println("Libraries:");
14574                            printedHeader = true;
14575                        }
14576                        pw.print("  ");
14577                    } else {
14578                        pw.print("lib,");
14579                    }
14580                    pw.print(name);
14581                    if (!checkin) {
14582                        pw.print(" -> ");
14583                    }
14584                    if (ent.path != null) {
14585                        if (!checkin) {
14586                            pw.print("(jar) ");
14587                            pw.print(ent.path);
14588                        } else {
14589                            pw.print(",jar,");
14590                            pw.print(ent.path);
14591                        }
14592                    } else {
14593                        if (!checkin) {
14594                            pw.print("(apk) ");
14595                            pw.print(ent.apk);
14596                        } else {
14597                            pw.print(",apk,");
14598                            pw.print(ent.apk);
14599                        }
14600                    }
14601                    pw.println();
14602                }
14603            }
14604
14605            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14606                if (dumpState.onTitlePrinted())
14607                    pw.println();
14608                if (!checkin) {
14609                    pw.println("Features:");
14610                }
14611                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14612                while (it.hasNext()) {
14613                    String name = it.next();
14614                    if (!checkin) {
14615                        pw.print("  ");
14616                    } else {
14617                        pw.print("feat,");
14618                    }
14619                    pw.println(name);
14620                }
14621            }
14622
14623            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14624                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14625                        : "Activity Resolver Table:", "  ", packageName,
14626                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14627                    dumpState.setTitlePrinted(true);
14628                }
14629                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14630                        : "Receiver Resolver Table:", "  ", packageName,
14631                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14632                    dumpState.setTitlePrinted(true);
14633                }
14634                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14635                        : "Service Resolver Table:", "  ", packageName,
14636                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14637                    dumpState.setTitlePrinted(true);
14638                }
14639                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14640                        : "Provider Resolver Table:", "  ", packageName,
14641                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14642                    dumpState.setTitlePrinted(true);
14643                }
14644            }
14645
14646            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14647                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14648                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14649                    int user = mSettings.mPreferredActivities.keyAt(i);
14650                    if (pir.dump(pw,
14651                            dumpState.getTitlePrinted()
14652                                ? "\nPreferred Activities User " + user + ":"
14653                                : "Preferred Activities User " + user + ":", "  ",
14654                            packageName, true, false)) {
14655                        dumpState.setTitlePrinted(true);
14656                    }
14657                }
14658            }
14659
14660            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14661                pw.flush();
14662                FileOutputStream fout = new FileOutputStream(fd);
14663                BufferedOutputStream str = new BufferedOutputStream(fout);
14664                XmlSerializer serializer = new FastXmlSerializer();
14665                try {
14666                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14667                    serializer.startDocument(null, true);
14668                    serializer.setFeature(
14669                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14670                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14671                    serializer.endDocument();
14672                    serializer.flush();
14673                } catch (IllegalArgumentException e) {
14674                    pw.println("Failed writing: " + e);
14675                } catch (IllegalStateException e) {
14676                    pw.println("Failed writing: " + e);
14677                } catch (IOException e) {
14678                    pw.println("Failed writing: " + e);
14679                }
14680            }
14681
14682            if (!checkin
14683                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14684                    && packageName == null) {
14685                pw.println();
14686                int count = mSettings.mPackages.size();
14687                if (count == 0) {
14688                    pw.println("No domain preferred apps!");
14689                    pw.println();
14690                } else {
14691                    final String prefix = "  ";
14692                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14693                    if (allPackageSettings.size() == 0) {
14694                        pw.println("No domain preferred apps!");
14695                        pw.println();
14696                    } else {
14697                        pw.println("Domain preferred apps status:");
14698                        pw.println();
14699                        count = 0;
14700                        for (PackageSetting ps : allPackageSettings) {
14701                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14702                            if (ivi == null || ivi.getPackageName() == null) continue;
14703                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14704                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14705                            pw.println(prefix + "Status: " + ivi.getStatusString());
14706                            pw.println();
14707                            count++;
14708                        }
14709                        if (count == 0) {
14710                            pw.println(prefix + "No domain preferred app status!");
14711                            pw.println();
14712                        }
14713                        for (int userId : sUserManager.getUserIds()) {
14714                            pw.println("Domain preferred apps for User " + userId + ":");
14715                            pw.println();
14716                            count = 0;
14717                            for (PackageSetting ps : allPackageSettings) {
14718                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14719                                if (ivi == null || ivi.getPackageName() == null) {
14720                                    continue;
14721                                }
14722                                final int status = ps.getDomainVerificationStatusForUser(userId);
14723                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14724                                    continue;
14725                                }
14726                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14727                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14728                                String statusStr = IntentFilterVerificationInfo.
14729                                        getStatusStringFromValue(status);
14730                                pw.println(prefix + "Status: " + statusStr);
14731                                pw.println();
14732                                count++;
14733                            }
14734                            if (count == 0) {
14735                                pw.println(prefix + "No domain preferred apps!");
14736                                pw.println();
14737                            }
14738                        }
14739                    }
14740                }
14741            }
14742
14743            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14744                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14745                if (packageName == null && permissionNames == null) {
14746                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14747                        if (iperm == 0) {
14748                            if (dumpState.onTitlePrinted())
14749                                pw.println();
14750                            pw.println("AppOp Permissions:");
14751                        }
14752                        pw.print("  AppOp Permission ");
14753                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14754                        pw.println(":");
14755                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14756                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14757                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14758                        }
14759                    }
14760                }
14761            }
14762
14763            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14764                boolean printedSomething = false;
14765                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14766                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14767                        continue;
14768                    }
14769                    if (!printedSomething) {
14770                        if (dumpState.onTitlePrinted())
14771                            pw.println();
14772                        pw.println("Registered ContentProviders:");
14773                        printedSomething = true;
14774                    }
14775                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14776                    pw.print("    "); pw.println(p.toString());
14777                }
14778                printedSomething = false;
14779                for (Map.Entry<String, PackageParser.Provider> entry :
14780                        mProvidersByAuthority.entrySet()) {
14781                    PackageParser.Provider p = entry.getValue();
14782                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14783                        continue;
14784                    }
14785                    if (!printedSomething) {
14786                        if (dumpState.onTitlePrinted())
14787                            pw.println();
14788                        pw.println("ContentProvider Authorities:");
14789                        printedSomething = true;
14790                    }
14791                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14792                    pw.print("    "); pw.println(p.toString());
14793                    if (p.info != null && p.info.applicationInfo != null) {
14794                        final String appInfo = p.info.applicationInfo.toString();
14795                        pw.print("      applicationInfo="); pw.println(appInfo);
14796                    }
14797                }
14798            }
14799
14800            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14801                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14802            }
14803
14804            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14805                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
14806            }
14807
14808            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14809                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
14810            }
14811
14812            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14813                // XXX should handle packageName != null by dumping only install data that
14814                // the given package is involved with.
14815                if (dumpState.onTitlePrinted()) pw.println();
14816                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14817            }
14818
14819            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14820                if (dumpState.onTitlePrinted()) pw.println();
14821                mSettings.dumpReadMessagesLPr(pw, dumpState);
14822
14823                pw.println();
14824                pw.println("Package warning messages:");
14825                BufferedReader in = null;
14826                String line = null;
14827                try {
14828                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14829                    while ((line = in.readLine()) != null) {
14830                        if (line.contains("ignored: updated version")) continue;
14831                        pw.println(line);
14832                    }
14833                } catch (IOException ignored) {
14834                } finally {
14835                    IoUtils.closeQuietly(in);
14836                }
14837            }
14838
14839            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14840                BufferedReader in = null;
14841                String line = null;
14842                try {
14843                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14844                    while ((line = in.readLine()) != null) {
14845                        if (line.contains("ignored: updated version")) continue;
14846                        pw.print("msg,");
14847                        pw.println(line);
14848                    }
14849                } catch (IOException ignored) {
14850                } finally {
14851                    IoUtils.closeQuietly(in);
14852                }
14853            }
14854        }
14855    }
14856
14857    // ------- apps on sdcard specific code -------
14858    static final boolean DEBUG_SD_INSTALL = false;
14859
14860    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14861
14862    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14863
14864    private boolean mMediaMounted = false;
14865
14866    static String getEncryptKey() {
14867        try {
14868            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14869                    SD_ENCRYPTION_KEYSTORE_NAME);
14870            if (sdEncKey == null) {
14871                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14872                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14873                if (sdEncKey == null) {
14874                    Slog.e(TAG, "Failed to create encryption keys");
14875                    return null;
14876                }
14877            }
14878            return sdEncKey;
14879        } catch (NoSuchAlgorithmException nsae) {
14880            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14881            return null;
14882        } catch (IOException ioe) {
14883            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14884            return null;
14885        }
14886    }
14887
14888    /*
14889     * Update media status on PackageManager.
14890     */
14891    @Override
14892    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14893        int callingUid = Binder.getCallingUid();
14894        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14895            throw new SecurityException("Media status can only be updated by the system");
14896        }
14897        // reader; this apparently protects mMediaMounted, but should probably
14898        // be a different lock in that case.
14899        synchronized (mPackages) {
14900            Log.i(TAG, "Updating external media status from "
14901                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14902                    + (mediaStatus ? "mounted" : "unmounted"));
14903            if (DEBUG_SD_INSTALL)
14904                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14905                        + ", mMediaMounted=" + mMediaMounted);
14906            if (mediaStatus == mMediaMounted) {
14907                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14908                        : 0, -1);
14909                mHandler.sendMessage(msg);
14910                return;
14911            }
14912            mMediaMounted = mediaStatus;
14913        }
14914        // Queue up an async operation since the package installation may take a
14915        // little while.
14916        mHandler.post(new Runnable() {
14917            public void run() {
14918                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14919            }
14920        });
14921    }
14922
14923    /**
14924     * Called by MountService when the initial ASECs to scan are available.
14925     * Should block until all the ASEC containers are finished being scanned.
14926     */
14927    public void scanAvailableAsecs() {
14928        updateExternalMediaStatusInner(true, false, false);
14929        if (mShouldRestoreconData) {
14930            SELinuxMMAC.setRestoreconDone();
14931            mShouldRestoreconData = false;
14932        }
14933    }
14934
14935    /*
14936     * Collect information of applications on external media, map them against
14937     * existing containers and update information based on current mount status.
14938     * Please note that we always have to report status if reportStatus has been
14939     * set to true especially when unloading packages.
14940     */
14941    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14942            boolean externalStorage) {
14943        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14944        int[] uidArr = EmptyArray.INT;
14945
14946        final String[] list = PackageHelper.getSecureContainerList();
14947        if (ArrayUtils.isEmpty(list)) {
14948            Log.i(TAG, "No secure containers found");
14949        } else {
14950            // Process list of secure containers and categorize them
14951            // as active or stale based on their package internal state.
14952
14953            // reader
14954            synchronized (mPackages) {
14955                for (String cid : list) {
14956                    // Leave stages untouched for now; installer service owns them
14957                    if (PackageInstallerService.isStageName(cid)) continue;
14958
14959                    if (DEBUG_SD_INSTALL)
14960                        Log.i(TAG, "Processing container " + cid);
14961                    String pkgName = getAsecPackageName(cid);
14962                    if (pkgName == null) {
14963                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14964                        continue;
14965                    }
14966                    if (DEBUG_SD_INSTALL)
14967                        Log.i(TAG, "Looking for pkg : " + pkgName);
14968
14969                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14970                    if (ps == null) {
14971                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14972                        continue;
14973                    }
14974
14975                    /*
14976                     * Skip packages that are not external if we're unmounting
14977                     * external storage.
14978                     */
14979                    if (externalStorage && !isMounted && !isExternal(ps)) {
14980                        continue;
14981                    }
14982
14983                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14984                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14985                    // The package status is changed only if the code path
14986                    // matches between settings and the container id.
14987                    if (ps.codePathString != null
14988                            && ps.codePathString.startsWith(args.getCodePath())) {
14989                        if (DEBUG_SD_INSTALL) {
14990                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14991                                    + " at code path: " + ps.codePathString);
14992                        }
14993
14994                        // We do have a valid package installed on sdcard
14995                        processCids.put(args, ps.codePathString);
14996                        final int uid = ps.appId;
14997                        if (uid != -1) {
14998                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14999                        }
15000                    } else {
15001                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15002                                + ps.codePathString);
15003                    }
15004                }
15005            }
15006
15007            Arrays.sort(uidArr);
15008        }
15009
15010        // Process packages with valid entries.
15011        if (isMounted) {
15012            if (DEBUG_SD_INSTALL)
15013                Log.i(TAG, "Loading packages");
15014            loadMediaPackages(processCids, uidArr);
15015            startCleaningPackages();
15016            mInstallerService.onSecureContainersAvailable();
15017        } else {
15018            if (DEBUG_SD_INSTALL)
15019                Log.i(TAG, "Unloading packages");
15020            unloadMediaPackages(processCids, uidArr, reportStatus);
15021        }
15022    }
15023
15024    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15025            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15026        final int size = infos.size();
15027        final String[] packageNames = new String[size];
15028        final int[] packageUids = new int[size];
15029        for (int i = 0; i < size; i++) {
15030            final ApplicationInfo info = infos.get(i);
15031            packageNames[i] = info.packageName;
15032            packageUids[i] = info.uid;
15033        }
15034        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15035                finishedReceiver);
15036    }
15037
15038    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15039            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15040        sendResourcesChangedBroadcast(mediaStatus, replacing,
15041                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15042    }
15043
15044    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15045            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15046        int size = pkgList.length;
15047        if (size > 0) {
15048            // Send broadcasts here
15049            Bundle extras = new Bundle();
15050            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15051            if (uidArr != null) {
15052                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15053            }
15054            if (replacing) {
15055                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15056            }
15057            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15058                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15059            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15060        }
15061    }
15062
15063   /*
15064     * Look at potentially valid container ids from processCids If package
15065     * information doesn't match the one on record or package scanning fails,
15066     * the cid is added to list of removeCids. We currently don't delete stale
15067     * containers.
15068     */
15069    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15070        ArrayList<String> pkgList = new ArrayList<String>();
15071        Set<AsecInstallArgs> keys = processCids.keySet();
15072
15073        for (AsecInstallArgs args : keys) {
15074            String codePath = processCids.get(args);
15075            if (DEBUG_SD_INSTALL)
15076                Log.i(TAG, "Loading container : " + args.cid);
15077            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15078            try {
15079                // Make sure there are no container errors first.
15080                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15081                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15082                            + " when installing from sdcard");
15083                    continue;
15084                }
15085                // Check code path here.
15086                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15087                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15088                            + " does not match one in settings " + codePath);
15089                    continue;
15090                }
15091                // Parse package
15092                int parseFlags = mDefParseFlags;
15093                if (args.isExternalAsec()) {
15094                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15095                }
15096                if (args.isFwdLocked()) {
15097                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15098                }
15099
15100                synchronized (mInstallLock) {
15101                    PackageParser.Package pkg = null;
15102                    try {
15103                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15104                    } catch (PackageManagerException e) {
15105                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15106                    }
15107                    // Scan the package
15108                    if (pkg != null) {
15109                        /*
15110                         * TODO why is the lock being held? doPostInstall is
15111                         * called in other places without the lock. This needs
15112                         * to be straightened out.
15113                         */
15114                        // writer
15115                        synchronized (mPackages) {
15116                            retCode = PackageManager.INSTALL_SUCCEEDED;
15117                            pkgList.add(pkg.packageName);
15118                            // Post process args
15119                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15120                                    pkg.applicationInfo.uid);
15121                        }
15122                    } else {
15123                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15124                    }
15125                }
15126
15127            } finally {
15128                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15129                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15130                }
15131            }
15132        }
15133        // writer
15134        synchronized (mPackages) {
15135            // If the platform SDK has changed since the last time we booted,
15136            // we need to re-grant app permission to catch any new ones that
15137            // appear. This is really a hack, and means that apps can in some
15138            // cases get permissions that the user didn't initially explicitly
15139            // allow... it would be nice to have some better way to handle
15140            // this situation.
15141            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15142            if (regrantPermissions)
15143                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15144                        + mSdkVersion + "; regranting permissions for external storage");
15145            mSettings.mExternalSdkPlatform = mSdkVersion;
15146
15147            // Make sure group IDs have been assigned, and any permission
15148            // changes in other apps are accounted for
15149            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15150                    | (regrantPermissions
15151                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15152                            : 0));
15153
15154            mSettings.updateExternalDatabaseVersion();
15155
15156            // can downgrade to reader
15157            // Persist settings
15158            mSettings.writeLPr();
15159        }
15160        // Send a broadcast to let everyone know we are done processing
15161        if (pkgList.size() > 0) {
15162            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15163        }
15164    }
15165
15166   /*
15167     * Utility method to unload a list of specified containers
15168     */
15169    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15170        // Just unmount all valid containers.
15171        for (AsecInstallArgs arg : cidArgs) {
15172            synchronized (mInstallLock) {
15173                arg.doPostDeleteLI(false);
15174           }
15175       }
15176   }
15177
15178    /*
15179     * Unload packages mounted on external media. This involves deleting package
15180     * data from internal structures, sending broadcasts about diabled packages,
15181     * gc'ing to free up references, unmounting all secure containers
15182     * corresponding to packages on external media, and posting a
15183     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15184     * that we always have to post this message if status has been requested no
15185     * matter what.
15186     */
15187    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15188            final boolean reportStatus) {
15189        if (DEBUG_SD_INSTALL)
15190            Log.i(TAG, "unloading media packages");
15191        ArrayList<String> pkgList = new ArrayList<String>();
15192        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15193        final Set<AsecInstallArgs> keys = processCids.keySet();
15194        for (AsecInstallArgs args : keys) {
15195            String pkgName = args.getPackageName();
15196            if (DEBUG_SD_INSTALL)
15197                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15198            // Delete package internally
15199            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15200            synchronized (mInstallLock) {
15201                boolean res = deletePackageLI(pkgName, null, false, null, null,
15202                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15203                if (res) {
15204                    pkgList.add(pkgName);
15205                } else {
15206                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15207                    failedList.add(args);
15208                }
15209            }
15210        }
15211
15212        // reader
15213        synchronized (mPackages) {
15214            // We didn't update the settings after removing each package;
15215            // write them now for all packages.
15216            mSettings.writeLPr();
15217        }
15218
15219        // We have to absolutely send UPDATED_MEDIA_STATUS only
15220        // after confirming that all the receivers processed the ordered
15221        // broadcast when packages get disabled, force a gc to clean things up.
15222        // and unload all the containers.
15223        if (pkgList.size() > 0) {
15224            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15225                    new IIntentReceiver.Stub() {
15226                public void performReceive(Intent intent, int resultCode, String data,
15227                        Bundle extras, boolean ordered, boolean sticky,
15228                        int sendingUser) throws RemoteException {
15229                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15230                            reportStatus ? 1 : 0, 1, keys);
15231                    mHandler.sendMessage(msg);
15232                }
15233            });
15234        } else {
15235            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15236                    keys);
15237            mHandler.sendMessage(msg);
15238        }
15239    }
15240
15241    private void loadPrivatePackages(VolumeInfo vol) {
15242        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15243        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15244        synchronized (mInstallLock) {
15245        synchronized (mPackages) {
15246            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15247            for (PackageSetting ps : packages) {
15248                final PackageParser.Package pkg;
15249                try {
15250                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15251                    loaded.add(pkg.applicationInfo);
15252                } catch (PackageManagerException e) {
15253                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15254                }
15255            }
15256
15257            // TODO: regrant any permissions that changed based since original install
15258
15259            mSettings.writeLPr();
15260        }
15261        }
15262
15263        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15264        sendResourcesChangedBroadcast(true, false, loaded, null);
15265    }
15266
15267    private void unloadPrivatePackages(VolumeInfo vol) {
15268        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15269        synchronized (mInstallLock) {
15270        synchronized (mPackages) {
15271            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15272            for (PackageSetting ps : packages) {
15273                if (ps.pkg == null) continue;
15274
15275                final ApplicationInfo info = ps.pkg.applicationInfo;
15276                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15277                if (deletePackageLI(ps.name, null, false, null, null,
15278                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15279                    unloaded.add(info);
15280                } else {
15281                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15282                }
15283            }
15284
15285            mSettings.writeLPr();
15286        }
15287        }
15288
15289        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15290        sendResourcesChangedBroadcast(false, false, unloaded, null);
15291    }
15292
15293    /**
15294     * Examine all users present on given mounted volume, and destroy data
15295     * belonging to users that are no longer valid, or whose user ID has been
15296     * recycled.
15297     */
15298    private void reconcileUsers(String volumeUuid) {
15299        final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
15300        if (ArrayUtils.isEmpty(files)) {
15301            Slog.d(TAG, "No users found on " + volumeUuid);
15302            return;
15303        }
15304
15305        for (File file : files) {
15306            if (!file.isDirectory()) continue;
15307
15308            final int userId;
15309            final UserInfo info;
15310            try {
15311                userId = Integer.parseInt(file.getName());
15312                info = sUserManager.getUserInfo(userId);
15313            } catch (NumberFormatException e) {
15314                Slog.w(TAG, "Invalid user directory " + file);
15315                continue;
15316            }
15317
15318            boolean destroyUser = false;
15319            if (info == null) {
15320                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15321                        + " because no matching user was found");
15322                destroyUser = true;
15323            } else {
15324                try {
15325                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15326                } catch (IOException e) {
15327                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15328                            + " because we failed to enforce serial number: " + e);
15329                    destroyUser = true;
15330                }
15331            }
15332
15333            if (destroyUser) {
15334                synchronized (mInstallLock) {
15335                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15336                }
15337            }
15338        }
15339
15340        final UserManager um = mContext.getSystemService(UserManager.class);
15341        for (UserInfo user : um.getUsers()) {
15342            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15343            if (userDir.exists()) continue;
15344
15345            try {
15346                UserManagerService.prepareUserDirectory(userDir);
15347                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15348            } catch (IOException e) {
15349                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15350            }
15351        }
15352    }
15353
15354    /**
15355     * Examine all apps present on given mounted volume, and destroy apps that
15356     * aren't expected, either due to uninstallation or reinstallation on
15357     * another volume.
15358     */
15359    private void reconcileApps(String volumeUuid) {
15360        final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
15361        if (ArrayUtils.isEmpty(files)) {
15362            Slog.d(TAG, "No apps found on " + volumeUuid);
15363            return;
15364        }
15365
15366        for (File file : files) {
15367            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15368                    && !PackageInstallerService.isStageName(file.getName());
15369            if (!isPackage) {
15370                // Ignore entries which are not packages
15371                continue;
15372            }
15373
15374            boolean destroyApp = false;
15375            String packageName = null;
15376            try {
15377                final PackageLite pkg = PackageParser.parsePackageLite(file,
15378                        PackageParser.PARSE_MUST_BE_APK);
15379                packageName = pkg.packageName;
15380
15381                synchronized (mPackages) {
15382                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15383                    if (ps == null) {
15384                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15385                                + volumeUuid + " because we found no install record");
15386                        destroyApp = true;
15387                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15388                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15389                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15390                        destroyApp = true;
15391                    }
15392                }
15393
15394            } catch (PackageParserException e) {
15395                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15396                destroyApp = true;
15397            }
15398
15399            if (destroyApp) {
15400                synchronized (mInstallLock) {
15401                    if (packageName != null) {
15402                        removeDataDirsLI(volumeUuid, packageName);
15403                    }
15404                    if (file.isDirectory()) {
15405                        mInstaller.rmPackageDir(file.getAbsolutePath());
15406                    } else {
15407                        file.delete();
15408                    }
15409                }
15410            }
15411        }
15412    }
15413
15414    private void unfreezePackage(String packageName) {
15415        synchronized (mPackages) {
15416            final PackageSetting ps = mSettings.mPackages.get(packageName);
15417            if (ps != null) {
15418                ps.frozen = false;
15419            }
15420        }
15421    }
15422
15423    @Override
15424    public int movePackage(final String packageName, final String volumeUuid) {
15425        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15426
15427        final int moveId = mNextMoveId.getAndIncrement();
15428        try {
15429            movePackageInternal(packageName, volumeUuid, moveId);
15430        } catch (PackageManagerException e) {
15431            Slog.w(TAG, "Failed to move " + packageName, e);
15432            mMoveCallbacks.notifyStatusChanged(moveId,
15433                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15434        }
15435        return moveId;
15436    }
15437
15438    private void movePackageInternal(final String packageName, final String volumeUuid,
15439            final int moveId) throws PackageManagerException {
15440        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15441        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15442        final PackageManager pm = mContext.getPackageManager();
15443
15444        final boolean currentAsec;
15445        final String currentVolumeUuid;
15446        final File codeFile;
15447        final String installerPackageName;
15448        final String packageAbiOverride;
15449        final int appId;
15450        final String seinfo;
15451        final String label;
15452
15453        // reader
15454        synchronized (mPackages) {
15455            final PackageParser.Package pkg = mPackages.get(packageName);
15456            final PackageSetting ps = mSettings.mPackages.get(packageName);
15457            if (pkg == null || ps == null) {
15458                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15459            }
15460
15461            if (pkg.applicationInfo.isSystemApp()) {
15462                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15463                        "Cannot move system application");
15464            }
15465
15466            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15467                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15468                        "Package already moved to " + volumeUuid);
15469            }
15470
15471            final File probe = new File(pkg.codePath);
15472            final File probeOat = new File(probe, "oat");
15473            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15474                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15475                        "Move only supported for modern cluster style installs");
15476            }
15477
15478            if (ps.frozen) {
15479                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15480                        "Failed to move already frozen package");
15481            }
15482            ps.frozen = true;
15483
15484            currentAsec = pkg.applicationInfo.isForwardLocked()
15485                    || pkg.applicationInfo.isExternalAsec();
15486            currentVolumeUuid = ps.volumeUuid;
15487            codeFile = new File(pkg.codePath);
15488            installerPackageName = ps.installerPackageName;
15489            packageAbiOverride = ps.cpuAbiOverrideString;
15490            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15491            seinfo = pkg.applicationInfo.seinfo;
15492            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15493        }
15494
15495        // Now that we're guarded by frozen state, kill app during move
15496        killApplication(packageName, appId, "move pkg");
15497
15498        final Bundle extras = new Bundle();
15499        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15500        extras.putString(Intent.EXTRA_TITLE, label);
15501        mMoveCallbacks.notifyCreated(moveId, extras);
15502
15503        int installFlags;
15504        final boolean moveCompleteApp;
15505        final File measurePath;
15506
15507        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15508            installFlags = INSTALL_INTERNAL;
15509            moveCompleteApp = !currentAsec;
15510            measurePath = Environment.getDataAppDirectory(volumeUuid);
15511        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15512            installFlags = INSTALL_EXTERNAL;
15513            moveCompleteApp = false;
15514            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15515        } else {
15516            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15517            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15518                    || !volume.isMountedWritable()) {
15519                unfreezePackage(packageName);
15520                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15521                        "Move location not mounted private volume");
15522            }
15523
15524            Preconditions.checkState(!currentAsec);
15525
15526            installFlags = INSTALL_INTERNAL;
15527            moveCompleteApp = true;
15528            measurePath = Environment.getDataAppDirectory(volumeUuid);
15529        }
15530
15531        final PackageStats stats = new PackageStats(null, -1);
15532        synchronized (mInstaller) {
15533            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15534                unfreezePackage(packageName);
15535                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15536                        "Failed to measure package size");
15537            }
15538        }
15539
15540        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15541                + stats.dataSize);
15542
15543        final long startFreeBytes = measurePath.getFreeSpace();
15544        final long sizeBytes;
15545        if (moveCompleteApp) {
15546            sizeBytes = stats.codeSize + stats.dataSize;
15547        } else {
15548            sizeBytes = stats.codeSize;
15549        }
15550
15551        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15552            unfreezePackage(packageName);
15553            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15554                    "Not enough free space to move");
15555        }
15556
15557        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15558
15559        final CountDownLatch installedLatch = new CountDownLatch(1);
15560        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15561            @Override
15562            public void onUserActionRequired(Intent intent) throws RemoteException {
15563                throw new IllegalStateException();
15564            }
15565
15566            @Override
15567            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15568                    Bundle extras) throws RemoteException {
15569                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15570                        + PackageManager.installStatusToString(returnCode, msg));
15571
15572                installedLatch.countDown();
15573
15574                // Regardless of success or failure of the move operation,
15575                // always unfreeze the package
15576                unfreezePackage(packageName);
15577
15578                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15579                switch (status) {
15580                    case PackageInstaller.STATUS_SUCCESS:
15581                        mMoveCallbacks.notifyStatusChanged(moveId,
15582                                PackageManager.MOVE_SUCCEEDED);
15583                        break;
15584                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15585                        mMoveCallbacks.notifyStatusChanged(moveId,
15586                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15587                        break;
15588                    default:
15589                        mMoveCallbacks.notifyStatusChanged(moveId,
15590                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15591                        break;
15592                }
15593            }
15594        };
15595
15596        final MoveInfo move;
15597        if (moveCompleteApp) {
15598            // Kick off a thread to report progress estimates
15599            new Thread() {
15600                @Override
15601                public void run() {
15602                    while (true) {
15603                        try {
15604                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15605                                break;
15606                            }
15607                        } catch (InterruptedException ignored) {
15608                        }
15609
15610                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15611                        final int progress = 10 + (int) MathUtils.constrain(
15612                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15613                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15614                    }
15615                }
15616            }.start();
15617
15618            final String dataAppName = codeFile.getName();
15619            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15620                    dataAppName, appId, seinfo);
15621        } else {
15622            move = null;
15623        }
15624
15625        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15626
15627        final Message msg = mHandler.obtainMessage(INIT_COPY);
15628        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15629        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15630                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15631        mHandler.sendMessage(msg);
15632    }
15633
15634    @Override
15635    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15636        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15637
15638        final int realMoveId = mNextMoveId.getAndIncrement();
15639        final Bundle extras = new Bundle();
15640        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15641        mMoveCallbacks.notifyCreated(realMoveId, extras);
15642
15643        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15644            @Override
15645            public void onCreated(int moveId, Bundle extras) {
15646                // Ignored
15647            }
15648
15649            @Override
15650            public void onStatusChanged(int moveId, int status, long estMillis) {
15651                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15652            }
15653        };
15654
15655        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15656        storage.setPrimaryStorageUuid(volumeUuid, callback);
15657        return realMoveId;
15658    }
15659
15660    @Override
15661    public int getMoveStatus(int moveId) {
15662        mContext.enforceCallingOrSelfPermission(
15663                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15664        return mMoveCallbacks.mLastStatus.get(moveId);
15665    }
15666
15667    @Override
15668    public void registerMoveCallback(IPackageMoveObserver callback) {
15669        mContext.enforceCallingOrSelfPermission(
15670                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15671        mMoveCallbacks.register(callback);
15672    }
15673
15674    @Override
15675    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15676        mContext.enforceCallingOrSelfPermission(
15677                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15678        mMoveCallbacks.unregister(callback);
15679    }
15680
15681    @Override
15682    public boolean setInstallLocation(int loc) {
15683        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15684                null);
15685        if (getInstallLocation() == loc) {
15686            return true;
15687        }
15688        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15689                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15690            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15691                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15692            return true;
15693        }
15694        return false;
15695   }
15696
15697    @Override
15698    public int getInstallLocation() {
15699        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15700                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15701                PackageHelper.APP_INSTALL_AUTO);
15702    }
15703
15704    /** Called by UserManagerService */
15705    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15706        mDirtyUsers.remove(userHandle);
15707        mSettings.removeUserLPw(userHandle);
15708        mPendingBroadcasts.remove(userHandle);
15709        if (mInstaller != null) {
15710            // Technically, we shouldn't be doing this with the package lock
15711            // held.  However, this is very rare, and there is already so much
15712            // other disk I/O going on, that we'll let it slide for now.
15713            final StorageManager storage = mContext.getSystemService(StorageManager.class);
15714            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
15715                final String volumeUuid = vol.getFsUuid();
15716                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15717                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15718            }
15719        }
15720        mUserNeedsBadging.delete(userHandle);
15721        removeUnusedPackagesLILPw(userManager, userHandle);
15722    }
15723
15724    /**
15725     * We're removing userHandle and would like to remove any downloaded packages
15726     * that are no longer in use by any other user.
15727     * @param userHandle the user being removed
15728     */
15729    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15730        final boolean DEBUG_CLEAN_APKS = false;
15731        int [] users = userManager.getUserIdsLPr();
15732        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15733        while (psit.hasNext()) {
15734            PackageSetting ps = psit.next();
15735            if (ps.pkg == null) {
15736                continue;
15737            }
15738            final String packageName = ps.pkg.packageName;
15739            // Skip over if system app
15740            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15741                continue;
15742            }
15743            if (DEBUG_CLEAN_APKS) {
15744                Slog.i(TAG, "Checking package " + packageName);
15745            }
15746            boolean keep = false;
15747            for (int i = 0; i < users.length; i++) {
15748                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15749                    keep = true;
15750                    if (DEBUG_CLEAN_APKS) {
15751                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15752                                + users[i]);
15753                    }
15754                    break;
15755                }
15756            }
15757            if (!keep) {
15758                if (DEBUG_CLEAN_APKS) {
15759                    Slog.i(TAG, "  Removing package " + packageName);
15760                }
15761                mHandler.post(new Runnable() {
15762                    public void run() {
15763                        deletePackageX(packageName, userHandle, 0);
15764                    } //end run
15765                });
15766            }
15767        }
15768    }
15769
15770    /** Called by UserManagerService */
15771    void createNewUserLILPw(int userHandle) {
15772        if (mInstaller != null) {
15773            mInstaller.createUserConfig(userHandle);
15774            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
15775            applyFactoryDefaultBrowserLPw(userHandle);
15776        }
15777    }
15778
15779    void newUserCreatedLILPw(final int userHandle) {
15780        // We cannot grant the default permissions with a lock held as
15781        // we query providers from other components for default handlers
15782        // such as enabled IMEs, etc.
15783        mHandler.post(new Runnable() {
15784            @Override
15785            public void run() {
15786                mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15787            }
15788        });
15789    }
15790
15791    @Override
15792    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15793        mContext.enforceCallingOrSelfPermission(
15794                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15795                "Only package verification agents can read the verifier device identity");
15796
15797        synchronized (mPackages) {
15798            return mSettings.getVerifierDeviceIdentityLPw();
15799        }
15800    }
15801
15802    @Override
15803    public void setPermissionEnforced(String permission, boolean enforced) {
15804        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15805        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15806            synchronized (mPackages) {
15807                if (mSettings.mReadExternalStorageEnforced == null
15808                        || mSettings.mReadExternalStorageEnforced != enforced) {
15809                    mSettings.mReadExternalStorageEnforced = enforced;
15810                    mSettings.writeLPr();
15811                }
15812            }
15813            // kill any non-foreground processes so we restart them and
15814            // grant/revoke the GID.
15815            final IActivityManager am = ActivityManagerNative.getDefault();
15816            if (am != null) {
15817                final long token = Binder.clearCallingIdentity();
15818                try {
15819                    am.killProcessesBelowForeground("setPermissionEnforcement");
15820                } catch (RemoteException e) {
15821                } finally {
15822                    Binder.restoreCallingIdentity(token);
15823                }
15824            }
15825        } else {
15826            throw new IllegalArgumentException("No selective enforcement for " + permission);
15827        }
15828    }
15829
15830    @Override
15831    @Deprecated
15832    public boolean isPermissionEnforced(String permission) {
15833        return true;
15834    }
15835
15836    @Override
15837    public boolean isStorageLow() {
15838        final long token = Binder.clearCallingIdentity();
15839        try {
15840            final DeviceStorageMonitorInternal
15841                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15842            if (dsm != null) {
15843                return dsm.isMemoryLow();
15844            } else {
15845                return false;
15846            }
15847        } finally {
15848            Binder.restoreCallingIdentity(token);
15849        }
15850    }
15851
15852    @Override
15853    public IPackageInstaller getPackageInstaller() {
15854        return mInstallerService;
15855    }
15856
15857    private boolean userNeedsBadging(int userId) {
15858        int index = mUserNeedsBadging.indexOfKey(userId);
15859        if (index < 0) {
15860            final UserInfo userInfo;
15861            final long token = Binder.clearCallingIdentity();
15862            try {
15863                userInfo = sUserManager.getUserInfo(userId);
15864            } finally {
15865                Binder.restoreCallingIdentity(token);
15866            }
15867            final boolean b;
15868            if (userInfo != null && userInfo.isManagedProfile()) {
15869                b = true;
15870            } else {
15871                b = false;
15872            }
15873            mUserNeedsBadging.put(userId, b);
15874            return b;
15875        }
15876        return mUserNeedsBadging.valueAt(index);
15877    }
15878
15879    @Override
15880    public KeySet getKeySetByAlias(String packageName, String alias) {
15881        if (packageName == null || alias == null) {
15882            return null;
15883        }
15884        synchronized(mPackages) {
15885            final PackageParser.Package pkg = mPackages.get(packageName);
15886            if (pkg == null) {
15887                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15888                throw new IllegalArgumentException("Unknown package: " + packageName);
15889            }
15890            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15891            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15892        }
15893    }
15894
15895    @Override
15896    public KeySet getSigningKeySet(String packageName) {
15897        if (packageName == null) {
15898            return null;
15899        }
15900        synchronized(mPackages) {
15901            final PackageParser.Package pkg = mPackages.get(packageName);
15902            if (pkg == null) {
15903                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15904                throw new IllegalArgumentException("Unknown package: " + packageName);
15905            }
15906            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15907                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15908                throw new SecurityException("May not access signing KeySet of other apps.");
15909            }
15910            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15911            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15912        }
15913    }
15914
15915    @Override
15916    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15917        if (packageName == null || ks == null) {
15918            return false;
15919        }
15920        synchronized(mPackages) {
15921            final PackageParser.Package pkg = mPackages.get(packageName);
15922            if (pkg == null) {
15923                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15924                throw new IllegalArgumentException("Unknown package: " + packageName);
15925            }
15926            IBinder ksh = ks.getToken();
15927            if (ksh instanceof KeySetHandle) {
15928                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15929                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15930            }
15931            return false;
15932        }
15933    }
15934
15935    @Override
15936    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15937        if (packageName == null || ks == null) {
15938            return false;
15939        }
15940        synchronized(mPackages) {
15941            final PackageParser.Package pkg = mPackages.get(packageName);
15942            if (pkg == null) {
15943                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15944                throw new IllegalArgumentException("Unknown package: " + packageName);
15945            }
15946            IBinder ksh = ks.getToken();
15947            if (ksh instanceof KeySetHandle) {
15948                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15949                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15950            }
15951            return false;
15952        }
15953    }
15954
15955    public void getUsageStatsIfNoPackageUsageInfo() {
15956        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15957            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15958            if (usm == null) {
15959                throw new IllegalStateException("UsageStatsManager must be initialized");
15960            }
15961            long now = System.currentTimeMillis();
15962            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15963            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15964                String packageName = entry.getKey();
15965                PackageParser.Package pkg = mPackages.get(packageName);
15966                if (pkg == null) {
15967                    continue;
15968                }
15969                UsageStats usage = entry.getValue();
15970                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15971                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15972            }
15973        }
15974    }
15975
15976    /**
15977     * Check and throw if the given before/after packages would be considered a
15978     * downgrade.
15979     */
15980    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15981            throws PackageManagerException {
15982        if (after.versionCode < before.mVersionCode) {
15983            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15984                    "Update version code " + after.versionCode + " is older than current "
15985                    + before.mVersionCode);
15986        } else if (after.versionCode == before.mVersionCode) {
15987            if (after.baseRevisionCode < before.baseRevisionCode) {
15988                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15989                        "Update base revision code " + after.baseRevisionCode
15990                        + " is older than current " + before.baseRevisionCode);
15991            }
15992
15993            if (!ArrayUtils.isEmpty(after.splitNames)) {
15994                for (int i = 0; i < after.splitNames.length; i++) {
15995                    final String splitName = after.splitNames[i];
15996                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15997                    if (j != -1) {
15998                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15999                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16000                                    "Update split " + splitName + " revision code "
16001                                    + after.splitRevisionCodes[i] + " is older than current "
16002                                    + before.splitRevisionCodes[j]);
16003                        }
16004                    }
16005                }
16006            }
16007        }
16008    }
16009
16010    private static class MoveCallbacks extends Handler {
16011        private static final int MSG_CREATED = 1;
16012        private static final int MSG_STATUS_CHANGED = 2;
16013
16014        private final RemoteCallbackList<IPackageMoveObserver>
16015                mCallbacks = new RemoteCallbackList<>();
16016
16017        private final SparseIntArray mLastStatus = new SparseIntArray();
16018
16019        public MoveCallbacks(Looper looper) {
16020            super(looper);
16021        }
16022
16023        public void register(IPackageMoveObserver callback) {
16024            mCallbacks.register(callback);
16025        }
16026
16027        public void unregister(IPackageMoveObserver callback) {
16028            mCallbacks.unregister(callback);
16029        }
16030
16031        @Override
16032        public void handleMessage(Message msg) {
16033            final SomeArgs args = (SomeArgs) msg.obj;
16034            final int n = mCallbacks.beginBroadcast();
16035            for (int i = 0; i < n; i++) {
16036                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16037                try {
16038                    invokeCallback(callback, msg.what, args);
16039                } catch (RemoteException ignored) {
16040                }
16041            }
16042            mCallbacks.finishBroadcast();
16043            args.recycle();
16044        }
16045
16046        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16047                throws RemoteException {
16048            switch (what) {
16049                case MSG_CREATED: {
16050                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16051                    break;
16052                }
16053                case MSG_STATUS_CHANGED: {
16054                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16055                    break;
16056                }
16057            }
16058        }
16059
16060        private void notifyCreated(int moveId, Bundle extras) {
16061            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16062
16063            final SomeArgs args = SomeArgs.obtain();
16064            args.argi1 = moveId;
16065            args.arg2 = extras;
16066            obtainMessage(MSG_CREATED, args).sendToTarget();
16067        }
16068
16069        private void notifyStatusChanged(int moveId, int status) {
16070            notifyStatusChanged(moveId, status, -1);
16071        }
16072
16073        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16074            Slog.v(TAG, "Move " + moveId + " status " + status);
16075
16076            final SomeArgs args = SomeArgs.obtain();
16077            args.argi1 = moveId;
16078            args.argi2 = status;
16079            args.arg3 = estMillis;
16080            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16081
16082            synchronized (mLastStatus) {
16083                mLastStatus.put(moveId, status);
16084            }
16085        }
16086    }
16087
16088    private final class OnPermissionChangeListeners extends Handler {
16089        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16090
16091        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16092                new RemoteCallbackList<>();
16093
16094        public OnPermissionChangeListeners(Looper looper) {
16095            super(looper);
16096        }
16097
16098        @Override
16099        public void handleMessage(Message msg) {
16100            switch (msg.what) {
16101                case MSG_ON_PERMISSIONS_CHANGED: {
16102                    final int uid = msg.arg1;
16103                    handleOnPermissionsChanged(uid);
16104                } break;
16105            }
16106        }
16107
16108        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16109            mPermissionListeners.register(listener);
16110
16111        }
16112
16113        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16114            mPermissionListeners.unregister(listener);
16115        }
16116
16117        public void onPermissionsChanged(int uid) {
16118            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16119                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16120            }
16121        }
16122
16123        private void handleOnPermissionsChanged(int uid) {
16124            final int count = mPermissionListeners.beginBroadcast();
16125            try {
16126                for (int i = 0; i < count; i++) {
16127                    IOnPermissionsChangeListener callback = mPermissionListeners
16128                            .getBroadcastItem(i);
16129                    try {
16130                        callback.onPermissionsChanged(uid);
16131                    } catch (RemoteException e) {
16132                        Log.e(TAG, "Permission listener is dead", e);
16133                    }
16134                }
16135            } finally {
16136                mPermissionListeners.finishBroadcast();
16137            }
16138        }
16139    }
16140
16141    private class PackageManagerInternalImpl extends PackageManagerInternal {
16142        @Override
16143        public void setLocationPackagesProvider(PackagesProvider provider) {
16144            synchronized (mPackages) {
16145                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16146            }
16147        }
16148
16149        @Override
16150        public void setImePackagesProvider(PackagesProvider provider) {
16151            synchronized (mPackages) {
16152                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16153            }
16154        }
16155
16156        @Override
16157        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16158            synchronized (mPackages) {
16159                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16160            }
16161        }
16162
16163        @Override
16164        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16165            synchronized (mPackages) {
16166                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16167            }
16168        }
16169
16170        @Override
16171        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16172            synchronized (mPackages) {
16173                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16174            }
16175        }
16176
16177        @Override
16178        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16179            synchronized (mPackages) {
16180                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider);
16181            }
16182        }
16183
16184        @Override
16185        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16186            synchronized (mPackages) {
16187                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16188                        packageName, userId);
16189            }
16190        }
16191
16192        @Override
16193        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16194            synchronized (mPackages) {
16195                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16196                        packageName, userId);
16197            }
16198        }
16199    }
16200
16201    @Override
16202    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16203        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16204        synchronized (mPackages) {
16205            final long identity = Binder.clearCallingIdentity();
16206            try {
16207                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16208                        packageNames, userId);
16209            } finally {
16210                Binder.restoreCallingIdentity(identity);
16211            }
16212        }
16213    }
16214
16215    private static void enforceSystemOrPhoneCaller(String tag) {
16216        int callingUid = Binder.getCallingUid();
16217        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16218            throw new SecurityException(
16219                    "Cannot call " + tag + " from UID " + callingUid);
16220        }
16221    }
16222}
16223