PackageManagerService.java revision 6038d15cbc7f4648ceaadf5f15d1928c4899f98e
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.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
46import static android.content.pm.PackageManager.INSTALL_INTERNAL;
47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
52import static android.content.pm.PackageManager.MATCH_ALL;
53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
54import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
55import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
56import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
57import static android.content.pm.PackageParser.isApkFile;
58import static android.os.Process.FIRST_APPLICATION_UID;
59import static android.os.Process.PACKAGE_INFO_GID;
60import static android.os.Process.SYSTEM_UID;
61import static android.system.OsConstants.O_CREAT;
62import static android.system.OsConstants.O_RDWR;
63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
65import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
66import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
67import static com.android.internal.util.ArrayUtils.appendInt;
68import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
71import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
72import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
73
74import android.Manifest;
75import android.app.ActivityManager;
76import android.app.ActivityManagerNative;
77import android.app.AppGlobals;
78import android.app.IActivityManager;
79import android.app.admin.IDevicePolicyManager;
80import android.app.backup.IBackupManager;
81import android.app.usage.UsageStats;
82import android.app.usage.UsageStatsManager;
83import android.content.BroadcastReceiver;
84import android.content.ComponentName;
85import android.content.Context;
86import android.content.IIntentReceiver;
87import android.content.Intent;
88import android.content.IntentFilter;
89import android.content.IntentSender;
90import android.content.IntentSender.SendIntentException;
91import android.content.ServiceConnection;
92import android.content.pm.ActivityInfo;
93import android.content.pm.ApplicationInfo;
94import android.content.pm.FeatureInfo;
95import android.content.pm.IOnPermissionsChangeListener;
96import android.content.pm.IPackageDataObserver;
97import android.content.pm.IPackageDeleteObserver;
98import android.content.pm.IPackageDeleteObserver2;
99import android.content.pm.IPackageInstallObserver2;
100import android.content.pm.IPackageInstaller;
101import android.content.pm.IPackageManager;
102import android.content.pm.IPackageMoveObserver;
103import android.content.pm.IPackageStatsObserver;
104import android.content.pm.InstrumentationInfo;
105import android.content.pm.IntentFilterVerificationInfo;
106import android.content.pm.KeySet;
107import android.content.pm.ManifestDigest;
108import android.content.pm.PackageCleanItem;
109import android.content.pm.PackageInfo;
110import android.content.pm.PackageInfoLite;
111import android.content.pm.PackageInstaller;
112import android.content.pm.PackageManager;
113import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
114import android.content.pm.PackageParser;
115import android.content.pm.PackageParser.ActivityIntentInfo;
116import android.content.pm.PackageParser.PackageLite;
117import android.content.pm.PackageParser.PackageParserException;
118import android.content.pm.PackageStats;
119import android.content.pm.PackageUserState;
120import android.content.pm.ParceledListSlice;
121import android.content.pm.PermissionGroupInfo;
122import android.content.pm.PermissionInfo;
123import android.content.pm.ProviderInfo;
124import android.content.pm.ResolveInfo;
125import android.content.pm.ServiceInfo;
126import android.content.pm.Signature;
127import android.content.pm.UserInfo;
128import android.content.pm.VerificationParams;
129import android.content.pm.VerifierDeviceIdentity;
130import android.content.pm.VerifierInfo;
131import android.content.res.Resources;
132import android.hardware.display.DisplayManager;
133import android.net.Uri;
134import android.os.Binder;
135import android.os.Build;
136import android.os.Bundle;
137import android.os.Debug;
138import android.os.Environment;
139import android.os.Environment.UserEnvironment;
140import android.os.FileUtils;
141import android.os.Handler;
142import android.os.IBinder;
143import android.os.Looper;
144import android.os.Message;
145import android.os.Parcel;
146import android.os.ParcelFileDescriptor;
147import android.os.Process;
148import android.os.RemoteCallbackList;
149import android.os.RemoteException;
150import android.os.SELinux;
151import android.os.ServiceManager;
152import android.os.SystemClock;
153import android.os.SystemProperties;
154import android.os.UserHandle;
155import android.os.UserManager;
156import android.os.storage.IMountService;
157import android.os.storage.StorageEventListener;
158import android.os.storage.StorageManager;
159import android.os.storage.VolumeInfo;
160import android.os.storage.VolumeRecord;
161import android.security.KeyStore;
162import android.security.SystemKeyStore;
163import android.system.ErrnoException;
164import android.system.Os;
165import android.system.StructStat;
166import android.text.TextUtils;
167import android.text.format.DateUtils;
168import android.util.ArrayMap;
169import android.util.ArraySet;
170import android.util.AtomicFile;
171import android.util.DisplayMetrics;
172import android.util.EventLog;
173import android.util.ExceptionUtils;
174import android.util.Log;
175import android.util.LogPrinter;
176import android.util.MathUtils;
177import android.util.PrintStreamPrinter;
178import android.util.Slog;
179import android.util.SparseArray;
180import android.util.SparseBooleanArray;
181import android.util.SparseIntArray;
182import android.util.Xml;
183import android.view.Display;
184
185import dalvik.system.DexFile;
186import dalvik.system.VMRuntime;
187
188import libcore.io.IoUtils;
189import libcore.util.EmptyArray;
190
191import com.android.internal.R;
192import com.android.internal.app.IMediaContainerService;
193import com.android.internal.app.ResolverActivity;
194import com.android.internal.content.NativeLibraryHelper;
195import com.android.internal.content.PackageHelper;
196import com.android.internal.os.IParcelFileDescriptorFactory;
197import com.android.internal.os.SomeArgs;
198import com.android.internal.util.ArrayUtils;
199import com.android.internal.util.FastPrintWriter;
200import com.android.internal.util.FastXmlSerializer;
201import com.android.internal.util.IndentingPrintWriter;
202import com.android.internal.util.Preconditions;
203import com.android.server.EventLogTags;
204import com.android.server.FgThread;
205import com.android.server.IntentResolver;
206import com.android.server.LocalServices;
207import com.android.server.ServiceThread;
208import com.android.server.SystemConfig;
209import com.android.server.Watchdog;
210import com.android.server.pm.Settings.DatabaseVersion;
211import com.android.server.pm.PermissionsState.PermissionState;
212import com.android.server.storage.DeviceStorageMonitorInternal;
213
214import org.xmlpull.v1.XmlPullParser;
215import org.xmlpull.v1.XmlPullParserException;
216import org.xmlpull.v1.XmlSerializer;
217
218import java.io.BufferedInputStream;
219import java.io.BufferedOutputStream;
220import java.io.BufferedReader;
221import java.io.ByteArrayInputStream;
222import java.io.ByteArrayOutputStream;
223import java.io.File;
224import java.io.FileDescriptor;
225import java.io.FileNotFoundException;
226import java.io.FileOutputStream;
227import java.io.FileReader;
228import java.io.FilenameFilter;
229import java.io.IOException;
230import java.io.InputStream;
231import java.io.PrintWriter;
232import java.nio.charset.StandardCharsets;
233import java.security.NoSuchAlgorithmException;
234import java.security.PublicKey;
235import java.security.cert.CertificateEncodingException;
236import java.security.cert.CertificateException;
237import java.text.SimpleDateFormat;
238import java.util.ArrayList;
239import java.util.Arrays;
240import java.util.Collection;
241import java.util.Collections;
242import java.util.Comparator;
243import java.util.Date;
244import java.util.Iterator;
245import java.util.List;
246import java.util.Map;
247import java.util.Objects;
248import java.util.Set;
249import java.util.concurrent.CountDownLatch;
250import java.util.concurrent.TimeUnit;
251import java.util.concurrent.atomic.AtomicBoolean;
252import java.util.concurrent.atomic.AtomicInteger;
253import java.util.concurrent.atomic.AtomicLong;
254
255/**
256 * Keep track of all those .apks everywhere.
257 *
258 * This is very central to the platform's security; please run the unit
259 * tests whenever making modifications here:
260 *
261mmm frameworks/base/tests/AndroidTests
262adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
263adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
264 *
265 * {@hide}
266 */
267public class PackageManagerService extends IPackageManager.Stub {
268    static final String TAG = "PackageManager";
269    static final boolean DEBUG_SETTINGS = false;
270    static final boolean DEBUG_PREFERRED = false;
271    static final boolean DEBUG_UPGRADE = false;
272    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
273    private static final boolean DEBUG_BACKUP = true;
274    private static final boolean DEBUG_INSTALL = false;
275    private static final boolean DEBUG_REMOVE = false;
276    private static final boolean DEBUG_BROADCASTS = false;
277    private static final boolean DEBUG_SHOW_INFO = false;
278    private static final boolean DEBUG_PACKAGE_INFO = false;
279    private static final boolean DEBUG_INTENT_MATCHING = false;
280    private static final boolean DEBUG_PACKAGE_SCANNING = false;
281    private static final boolean DEBUG_VERIFY = false;
282    private static final boolean DEBUG_DEXOPT = false;
283    private static final boolean DEBUG_ABI_SELECTION = false;
284
285    private static final int RADIO_UID = Process.PHONE_UID;
286    private static final int LOG_UID = Process.LOG_UID;
287    private static final int NFC_UID = Process.NFC_UID;
288    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
289    private static final int SHELL_UID = Process.SHELL_UID;
290
291    // Cap the size of permission trees that 3rd party apps can define
292    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
293
294    // Suffix used during package installation when copying/moving
295    // package apks to install directory.
296    private static final String INSTALL_PACKAGE_SUFFIX = "-";
297
298    static final int SCAN_NO_DEX = 1<<1;
299    static final int SCAN_FORCE_DEX = 1<<2;
300    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
301    static final int SCAN_NEW_INSTALL = 1<<4;
302    static final int SCAN_NO_PATHS = 1<<5;
303    static final int SCAN_UPDATE_TIME = 1<<6;
304    static final int SCAN_DEFER_DEX = 1<<7;
305    static final int SCAN_BOOTING = 1<<8;
306    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
307    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
308    static final int SCAN_REQUIRE_KNOWN = 1<<12;
309    static final int SCAN_MOVE = 1<<13;
310
311    static final int REMOVE_CHATTY = 1<<16;
312
313    private static final int[] EMPTY_INT_ARRAY = new int[0];
314
315    /**
316     * Timeout (in milliseconds) after which the watchdog should declare that
317     * our handler thread is wedged.  The usual default for such things is one
318     * minute but we sometimes do very lengthy I/O operations on this thread,
319     * such as installing multi-gigabyte applications, so ours needs to be longer.
320     */
321    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
322
323    /**
324     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
325     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
326     * settings entry if available, otherwise we use the hardcoded default.  If it's been
327     * more than this long since the last fstrim, we force one during the boot sequence.
328     *
329     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
330     * one gets run at the next available charging+idle time.  This final mandatory
331     * no-fstrim check kicks in only of the other scheduling criteria is never met.
332     */
333    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
334
335    /**
336     * Whether verification is enabled by default.
337     */
338    private static final boolean DEFAULT_VERIFY_ENABLE = true;
339
340    /**
341     * The default maximum time to wait for the verification agent to return in
342     * milliseconds.
343     */
344    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
345
346    /**
347     * The default response for package verification timeout.
348     *
349     * This can be either PackageManager.VERIFICATION_ALLOW or
350     * PackageManager.VERIFICATION_REJECT.
351     */
352    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
353
354    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
355
356    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
357            DEFAULT_CONTAINER_PACKAGE,
358            "com.android.defcontainer.DefaultContainerService");
359
360    private static final String KILL_APP_REASON_GIDS_CHANGED =
361            "permission grant or revoke changed gids";
362
363    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
364            "permissions revoked";
365
366    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
367
368    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
369
370    /** Permission grant: not grant the permission. */
371    private static final int GRANT_DENIED = 1;
372
373    /** Permission grant: grant the permission as an install permission. */
374    private static final int GRANT_INSTALL = 2;
375
376    /** Permission grant: grant the permission as an install permission for a legacy app. */
377    private static final int GRANT_INSTALL_LEGACY = 3;
378
379    /** Permission grant: grant the permission as a runtime one. */
380    private static final int GRANT_RUNTIME = 4;
381
382    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
383    private static final int GRANT_UPGRADE = 5;
384
385    final ServiceThread mHandlerThread;
386
387    final PackageHandler mHandler;
388
389    /**
390     * Messages for {@link #mHandler} that need to wait for system ready before
391     * being dispatched.
392     */
393    private ArrayList<Message> mPostSystemReadyMessages;
394
395    final int mSdkVersion = Build.VERSION.SDK_INT;
396
397    final Context mContext;
398    final boolean mFactoryTest;
399    final boolean mOnlyCore;
400    final boolean mLazyDexOpt;
401    final long mDexOptLRUThresholdInMills;
402    final DisplayMetrics mMetrics;
403    final int mDefParseFlags;
404    final String[] mSeparateProcesses;
405    final boolean mIsUpgrade;
406
407    // This is where all application persistent data goes.
408    final File mAppDataDir;
409
410    // This is where all application persistent data goes for secondary users.
411    final File mUserAppDataDir;
412
413    /** The location for ASEC container files on internal storage. */
414    final String mAsecInternalPath;
415
416    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
417    // LOCK HELD.  Can be called with mInstallLock held.
418    final Installer mInstaller;
419
420    /** Directory where installed third-party apps stored */
421    final File mAppInstallDir;
422
423    /**
424     * Directory to which applications installed internally have their
425     * 32 bit native libraries copied.
426     */
427    private File mAppLib32InstallDir;
428
429    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
430    // apps.
431    final File mDrmAppPrivateInstallDir;
432
433    // ----------------------------------------------------------------
434
435    // Lock for state used when installing and doing other long running
436    // operations.  Methods that must be called with this lock held have
437    // the suffix "LI".
438    final Object mInstallLock = new Object();
439
440    // ----------------------------------------------------------------
441
442    // Keys are String (package name), values are Package.  This also serves
443    // as the lock for the global state.  Methods that must be called with
444    // this lock held have the prefix "LP".
445    final ArrayMap<String, PackageParser.Package> mPackages =
446            new ArrayMap<String, PackageParser.Package>();
447
448    // Tracks available target package names -> overlay package paths.
449    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
450        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
451
452    final Settings mSettings;
453    boolean mRestoredSettings;
454
455    // System configuration read by SystemConfig.
456    final int[] mGlobalGids;
457    final SparseArray<ArraySet<String>> mSystemPermissions;
458    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
459
460    // If mac_permissions.xml was found for seinfo labeling.
461    boolean mFoundPolicyFile;
462
463    // If a recursive restorecon of /data/data/<pkg> is needed.
464    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
465
466    public static final class SharedLibraryEntry {
467        public final String path;
468        public final String apk;
469
470        SharedLibraryEntry(String _path, String _apk) {
471            path = _path;
472            apk = _apk;
473        }
474    }
475
476    // Currently known shared libraries.
477    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
478            new ArrayMap<String, SharedLibraryEntry>();
479
480    // All available activities, for your resolving pleasure.
481    final ActivityIntentResolver mActivities =
482            new ActivityIntentResolver();
483
484    // All available receivers, for your resolving pleasure.
485    final ActivityIntentResolver mReceivers =
486            new ActivityIntentResolver();
487
488    // All available services, for your resolving pleasure.
489    final ServiceIntentResolver mServices = new ServiceIntentResolver();
490
491    // All available providers, for your resolving pleasure.
492    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
493
494    // Mapping from provider base names (first directory in content URI codePath)
495    // to the provider information.
496    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
497            new ArrayMap<String, PackageParser.Provider>();
498
499    // Mapping from instrumentation class names to info about them.
500    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
501            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
502
503    // Mapping from permission names to info about them.
504    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
505            new ArrayMap<String, PackageParser.PermissionGroup>();
506
507    // Packages whose data we have transfered into another package, thus
508    // should no longer exist.
509    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
510
511    // Broadcast actions that are only available to the system.
512    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
513
514    /** List of packages waiting for verification. */
515    final SparseArray<PackageVerificationState> mPendingVerification
516            = new SparseArray<PackageVerificationState>();
517
518    /** Set of packages associated with each app op permission. */
519    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
520
521    final PackageInstallerService mInstallerService;
522
523    private final PackageDexOptimizer mPackageDexOptimizer;
524
525    private AtomicInteger mNextMoveId = new AtomicInteger();
526    private final MoveCallbacks mMoveCallbacks;
527
528    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
529
530    // Cache of users who need badging.
531    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
532
533    /** Token for keys in mPendingVerification. */
534    private int mPendingVerificationToken = 0;
535
536    volatile boolean mSystemReady;
537    volatile boolean mSafeMode;
538    volatile boolean mHasSystemUidErrors;
539
540    ApplicationInfo mAndroidApplication;
541    final ActivityInfo mResolveActivity = new ActivityInfo();
542    final ResolveInfo mResolveInfo = new ResolveInfo();
543    ComponentName mResolveComponentName;
544    PackageParser.Package mPlatformPackage;
545    ComponentName mCustomResolverComponentName;
546
547    boolean mResolverReplaced = false;
548
549    private final ComponentName mIntentFilterVerifierComponent;
550    private int mIntentFilterVerificationToken = 0;
551
552    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
553            = new SparseArray<IntentFilterVerificationState>();
554
555    private static class IFVerificationParams {
556        PackageParser.Package pkg;
557        boolean replacing;
558        int userId;
559        int verifierUid;
560
561        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
562                int _userId, int _verifierUid) {
563            pkg = _pkg;
564            replacing = _replacing;
565            userId = _userId;
566            replacing = _replacing;
567            verifierUid = _verifierUid;
568        }
569    }
570
571    private interface IntentFilterVerifier<T extends IntentFilter> {
572        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
573                                               T filter, String packageName);
574        void startVerifications(int userId);
575        void receiveVerificationResponse(int verificationId);
576    }
577
578    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
579        private Context mContext;
580        private ComponentName mIntentFilterVerifierComponent;
581        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
582
583        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
584            mContext = context;
585            mIntentFilterVerifierComponent = verifierComponent;
586        }
587
588        private String getDefaultScheme() {
589            return IntentFilter.SCHEME_HTTPS;
590        }
591
592        @Override
593        public void startVerifications(int userId) {
594            // Launch verifications requests
595            int count = mCurrentIntentFilterVerifications.size();
596            for (int n=0; n<count; n++) {
597                int verificationId = mCurrentIntentFilterVerifications.get(n);
598                final IntentFilterVerificationState ivs =
599                        mIntentFilterVerificationStates.get(verificationId);
600
601                String packageName = ivs.getPackageName();
602
603                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
604                final int filterCount = filters.size();
605                ArraySet<String> domainsSet = new ArraySet<>();
606                for (int m=0; m<filterCount; m++) {
607                    PackageParser.ActivityIntentInfo filter = filters.get(m);
608                    domainsSet.addAll(filter.getHostsList());
609                }
610                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
611                synchronized (mPackages) {
612                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
613                            packageName, domainsList) != null) {
614                        scheduleWriteSettingsLocked();
615                    }
616                }
617                sendVerificationRequest(userId, verificationId, ivs);
618            }
619            mCurrentIntentFilterVerifications.clear();
620        }
621
622        private void sendVerificationRequest(int userId, int verificationId,
623                IntentFilterVerificationState ivs) {
624
625            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
626            verificationIntent.putExtra(
627                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
628                    verificationId);
629            verificationIntent.putExtra(
630                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
631                    getDefaultScheme());
632            verificationIntent.putExtra(
633                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
634                    ivs.getHostsString());
635            verificationIntent.putExtra(
636                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
637                    ivs.getPackageName());
638            verificationIntent.setComponent(mIntentFilterVerifierComponent);
639            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
640
641            UserHandle user = new UserHandle(userId);
642            mContext.sendBroadcastAsUser(verificationIntent, user);
643            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
644                    "Sending IntentFilter verification broadcast");
645        }
646
647        public void receiveVerificationResponse(int verificationId) {
648            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
649
650            final boolean verified = ivs.isVerified();
651
652            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
653            final int count = filters.size();
654            if (DEBUG_DOMAIN_VERIFICATION) {
655                Slog.i(TAG, "Received verification response " + verificationId
656                        + " for " + count + " filters, verified=" + verified);
657            }
658            for (int n=0; n<count; n++) {
659                PackageParser.ActivityIntentInfo filter = filters.get(n);
660                filter.setVerified(verified);
661
662                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
663                        + " verified with result:" + verified + " and hosts:"
664                        + ivs.getHostsString());
665            }
666
667            mIntentFilterVerificationStates.remove(verificationId);
668
669            final String packageName = ivs.getPackageName();
670            IntentFilterVerificationInfo ivi = null;
671
672            synchronized (mPackages) {
673                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
674            }
675            if (ivi == null) {
676                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
677                        + verificationId + " packageName:" + packageName);
678                return;
679            }
680            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
681                    "Updating IntentFilterVerificationInfo for verificationId:" + verificationId);
682
683            synchronized (mPackages) {
684                if (verified) {
685                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
686                } else {
687                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
688                }
689                scheduleWriteSettingsLocked();
690
691                final int userId = ivs.getUserId();
692                if (userId != UserHandle.USER_ALL) {
693                    final int userStatus =
694                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
695
696                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
697                    boolean needUpdate = false;
698
699                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
700                    // already been set by the User thru the Disambiguation dialog
701                    switch (userStatus) {
702                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
703                            if (verified) {
704                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
705                            } else {
706                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
707                            }
708                            needUpdate = true;
709                            break;
710
711                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
712                            if (verified) {
713                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
714                                needUpdate = true;
715                            }
716                            break;
717
718                        default:
719                            // Nothing to do
720                    }
721
722                    if (needUpdate) {
723                        mSettings.updateIntentFilterVerificationStatusLPw(
724                                packageName, updatedStatus, userId);
725                        scheduleWritePackageRestrictionsLocked(userId);
726                    }
727                }
728            }
729        }
730
731        @Override
732        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
733                    ActivityIntentInfo filter, String packageName) {
734            if (!hasValidDomains(filter)) {
735                return false;
736            }
737            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
738            if (ivs == null) {
739                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
740                        packageName);
741            }
742            if (DEBUG_DOMAIN_VERIFICATION) {
743                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
744            }
745            ivs.addFilter(filter);
746            return true;
747        }
748
749        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
750                int userId, int verificationId, String packageName) {
751            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
752                    verifierUid, userId, packageName);
753            ivs.setPendingState();
754            synchronized (mPackages) {
755                mIntentFilterVerificationStates.append(verificationId, ivs);
756                mCurrentIntentFilterVerifications.add(verificationId);
757            }
758            return ivs;
759        }
760    }
761
762    private static boolean hasValidDomains(ActivityIntentInfo filter) {
763        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
764                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
765        if (!hasHTTPorHTTPS) {
766            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
767                    "IntentFilter does not contain any HTTP or HTTPS data scheme");
768            return false;
769        }
770        return true;
771    }
772
773    private IntentFilterVerifier mIntentFilterVerifier;
774
775    // Set of pending broadcasts for aggregating enable/disable of components.
776    static class PendingPackageBroadcasts {
777        // for each user id, a map of <package name -> components within that package>
778        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
779
780        public PendingPackageBroadcasts() {
781            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
782        }
783
784        public ArrayList<String> get(int userId, String packageName) {
785            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
786            return packages.get(packageName);
787        }
788
789        public void put(int userId, String packageName, ArrayList<String> components) {
790            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
791            packages.put(packageName, components);
792        }
793
794        public void remove(int userId, String packageName) {
795            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
796            if (packages != null) {
797                packages.remove(packageName);
798            }
799        }
800
801        public void remove(int userId) {
802            mUidMap.remove(userId);
803        }
804
805        public int userIdCount() {
806            return mUidMap.size();
807        }
808
809        public int userIdAt(int n) {
810            return mUidMap.keyAt(n);
811        }
812
813        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
814            return mUidMap.get(userId);
815        }
816
817        public int size() {
818            // total number of pending broadcast entries across all userIds
819            int num = 0;
820            for (int i = 0; i< mUidMap.size(); i++) {
821                num += mUidMap.valueAt(i).size();
822            }
823            return num;
824        }
825
826        public void clear() {
827            mUidMap.clear();
828        }
829
830        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
831            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
832            if (map == null) {
833                map = new ArrayMap<String, ArrayList<String>>();
834                mUidMap.put(userId, map);
835            }
836            return map;
837        }
838    }
839    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
840
841    // Service Connection to remote media container service to copy
842    // package uri's from external media onto secure containers
843    // or internal storage.
844    private IMediaContainerService mContainerService = null;
845
846    static final int SEND_PENDING_BROADCAST = 1;
847    static final int MCS_BOUND = 3;
848    static final int END_COPY = 4;
849    static final int INIT_COPY = 5;
850    static final int MCS_UNBIND = 6;
851    static final int START_CLEANING_PACKAGE = 7;
852    static final int FIND_INSTALL_LOC = 8;
853    static final int POST_INSTALL = 9;
854    static final int MCS_RECONNECT = 10;
855    static final int MCS_GIVE_UP = 11;
856    static final int UPDATED_MEDIA_STATUS = 12;
857    static final int WRITE_SETTINGS = 13;
858    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
859    static final int PACKAGE_VERIFIED = 15;
860    static final int CHECK_PENDING_VERIFICATION = 16;
861    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
862    static final int INTENT_FILTER_VERIFIED = 18;
863
864    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
865
866    // Delay time in millisecs
867    static final int BROADCAST_DELAY = 10 * 1000;
868
869    static UserManagerService sUserManager;
870
871    // Stores a list of users whose package restrictions file needs to be updated
872    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
873
874    final private DefaultContainerConnection mDefContainerConn =
875            new DefaultContainerConnection();
876    class DefaultContainerConnection implements ServiceConnection {
877        public void onServiceConnected(ComponentName name, IBinder service) {
878            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
879            IMediaContainerService imcs =
880                IMediaContainerService.Stub.asInterface(service);
881            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
882        }
883
884        public void onServiceDisconnected(ComponentName name) {
885            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
886        }
887    };
888
889    // Recordkeeping of restore-after-install operations that are currently in flight
890    // between the Package Manager and the Backup Manager
891    class PostInstallData {
892        public InstallArgs args;
893        public PackageInstalledInfo res;
894
895        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
896            args = _a;
897            res = _r;
898        }
899    };
900    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
901    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
902
903    // XML tags for backup/restore of various bits of state
904    private static final String TAG_PREFERRED_BACKUP = "pa";
905    private static final String TAG_DEFAULT_APPS = "da";
906    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
907
908    private final String mRequiredVerifierPackage;
909
910    private final PackageUsage mPackageUsage = new PackageUsage();
911
912    private class PackageUsage {
913        private static final int WRITE_INTERVAL
914            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
915
916        private final Object mFileLock = new Object();
917        private final AtomicLong mLastWritten = new AtomicLong(0);
918        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
919
920        private boolean mIsHistoricalPackageUsageAvailable = true;
921
922        boolean isHistoricalPackageUsageAvailable() {
923            return mIsHistoricalPackageUsageAvailable;
924        }
925
926        void write(boolean force) {
927            if (force) {
928                writeInternal();
929                return;
930            }
931            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
932                && !DEBUG_DEXOPT) {
933                return;
934            }
935            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
936                new Thread("PackageUsage_DiskWriter") {
937                    @Override
938                    public void run() {
939                        try {
940                            writeInternal();
941                        } finally {
942                            mBackgroundWriteRunning.set(false);
943                        }
944                    }
945                }.start();
946            }
947        }
948
949        private void writeInternal() {
950            synchronized (mPackages) {
951                synchronized (mFileLock) {
952                    AtomicFile file = getFile();
953                    FileOutputStream f = null;
954                    try {
955                        f = file.startWrite();
956                        BufferedOutputStream out = new BufferedOutputStream(f);
957                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
958                        StringBuilder sb = new StringBuilder();
959                        for (PackageParser.Package pkg : mPackages.values()) {
960                            if (pkg.mLastPackageUsageTimeInMills == 0) {
961                                continue;
962                            }
963                            sb.setLength(0);
964                            sb.append(pkg.packageName);
965                            sb.append(' ');
966                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
967                            sb.append('\n');
968                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
969                        }
970                        out.flush();
971                        file.finishWrite(f);
972                    } catch (IOException e) {
973                        if (f != null) {
974                            file.failWrite(f);
975                        }
976                        Log.e(TAG, "Failed to write package usage times", e);
977                    }
978                }
979            }
980            mLastWritten.set(SystemClock.elapsedRealtime());
981        }
982
983        void readLP() {
984            synchronized (mFileLock) {
985                AtomicFile file = getFile();
986                BufferedInputStream in = null;
987                try {
988                    in = new BufferedInputStream(file.openRead());
989                    StringBuffer sb = new StringBuffer();
990                    while (true) {
991                        String packageName = readToken(in, sb, ' ');
992                        if (packageName == null) {
993                            break;
994                        }
995                        String timeInMillisString = readToken(in, sb, '\n');
996                        if (timeInMillisString == null) {
997                            throw new IOException("Failed to find last usage time for package "
998                                                  + packageName);
999                        }
1000                        PackageParser.Package pkg = mPackages.get(packageName);
1001                        if (pkg == null) {
1002                            continue;
1003                        }
1004                        long timeInMillis;
1005                        try {
1006                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1007                        } catch (NumberFormatException e) {
1008                            throw new IOException("Failed to parse " + timeInMillisString
1009                                                  + " as a long.", e);
1010                        }
1011                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1012                    }
1013                } catch (FileNotFoundException expected) {
1014                    mIsHistoricalPackageUsageAvailable = false;
1015                } catch (IOException e) {
1016                    Log.w(TAG, "Failed to read package usage times", e);
1017                } finally {
1018                    IoUtils.closeQuietly(in);
1019                }
1020            }
1021            mLastWritten.set(SystemClock.elapsedRealtime());
1022        }
1023
1024        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1025                throws IOException {
1026            sb.setLength(0);
1027            while (true) {
1028                int ch = in.read();
1029                if (ch == -1) {
1030                    if (sb.length() == 0) {
1031                        return null;
1032                    }
1033                    throw new IOException("Unexpected EOF");
1034                }
1035                if (ch == endOfToken) {
1036                    return sb.toString();
1037                }
1038                sb.append((char)ch);
1039            }
1040        }
1041
1042        private AtomicFile getFile() {
1043            File dataDir = Environment.getDataDirectory();
1044            File systemDir = new File(dataDir, "system");
1045            File fname = new File(systemDir, "package-usage.list");
1046            return new AtomicFile(fname);
1047        }
1048    }
1049
1050    class PackageHandler extends Handler {
1051        private boolean mBound = false;
1052        final ArrayList<HandlerParams> mPendingInstalls =
1053            new ArrayList<HandlerParams>();
1054
1055        private boolean connectToService() {
1056            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1057                    " DefaultContainerService");
1058            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1059            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1060            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1061                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1062                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1063                mBound = true;
1064                return true;
1065            }
1066            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1067            return false;
1068        }
1069
1070        private void disconnectService() {
1071            mContainerService = null;
1072            mBound = false;
1073            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1074            mContext.unbindService(mDefContainerConn);
1075            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1076        }
1077
1078        PackageHandler(Looper looper) {
1079            super(looper);
1080        }
1081
1082        public void handleMessage(Message msg) {
1083            try {
1084                doHandleMessage(msg);
1085            } finally {
1086                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1087            }
1088        }
1089
1090        void doHandleMessage(Message msg) {
1091            switch (msg.what) {
1092                case INIT_COPY: {
1093                    HandlerParams params = (HandlerParams) msg.obj;
1094                    int idx = mPendingInstalls.size();
1095                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1096                    // If a bind was already initiated we dont really
1097                    // need to do anything. The pending install
1098                    // will be processed later on.
1099                    if (!mBound) {
1100                        // If this is the only one pending we might
1101                        // have to bind to the service again.
1102                        if (!connectToService()) {
1103                            Slog.e(TAG, "Failed to bind to media container service");
1104                            params.serviceError();
1105                            return;
1106                        } else {
1107                            // Once we bind to the service, the first
1108                            // pending request will be processed.
1109                            mPendingInstalls.add(idx, params);
1110                        }
1111                    } else {
1112                        mPendingInstalls.add(idx, params);
1113                        // Already bound to the service. Just make
1114                        // sure we trigger off processing the first request.
1115                        if (idx == 0) {
1116                            mHandler.sendEmptyMessage(MCS_BOUND);
1117                        }
1118                    }
1119                    break;
1120                }
1121                case MCS_BOUND: {
1122                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1123                    if (msg.obj != null) {
1124                        mContainerService = (IMediaContainerService) msg.obj;
1125                    }
1126                    if (mContainerService == null) {
1127                        // Something seriously wrong. Bail out
1128                        Slog.e(TAG, "Cannot bind to media container service");
1129                        for (HandlerParams params : mPendingInstalls) {
1130                            // Indicate service bind error
1131                            params.serviceError();
1132                        }
1133                        mPendingInstalls.clear();
1134                    } else if (mPendingInstalls.size() > 0) {
1135                        HandlerParams params = mPendingInstalls.get(0);
1136                        if (params != null) {
1137                            if (params.startCopy()) {
1138                                // We are done...  look for more work or to
1139                                // go idle.
1140                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1141                                        "Checking for more work or unbind...");
1142                                // Delete pending install
1143                                if (mPendingInstalls.size() > 0) {
1144                                    mPendingInstalls.remove(0);
1145                                }
1146                                if (mPendingInstalls.size() == 0) {
1147                                    if (mBound) {
1148                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1149                                                "Posting delayed MCS_UNBIND");
1150                                        removeMessages(MCS_UNBIND);
1151                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1152                                        // Unbind after a little delay, to avoid
1153                                        // continual thrashing.
1154                                        sendMessageDelayed(ubmsg, 10000);
1155                                    }
1156                                } else {
1157                                    // There are more pending requests in queue.
1158                                    // Just post MCS_BOUND message to trigger processing
1159                                    // of next pending install.
1160                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1161                                            "Posting MCS_BOUND for next work");
1162                                    mHandler.sendEmptyMessage(MCS_BOUND);
1163                                }
1164                            }
1165                        }
1166                    } else {
1167                        // Should never happen ideally.
1168                        Slog.w(TAG, "Empty queue");
1169                    }
1170                    break;
1171                }
1172                case MCS_RECONNECT: {
1173                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1174                    if (mPendingInstalls.size() > 0) {
1175                        if (mBound) {
1176                            disconnectService();
1177                        }
1178                        if (!connectToService()) {
1179                            Slog.e(TAG, "Failed to bind to media container service");
1180                            for (HandlerParams params : mPendingInstalls) {
1181                                // Indicate service bind error
1182                                params.serviceError();
1183                            }
1184                            mPendingInstalls.clear();
1185                        }
1186                    }
1187                    break;
1188                }
1189                case MCS_UNBIND: {
1190                    // If there is no actual work left, then time to unbind.
1191                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1192
1193                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1194                        if (mBound) {
1195                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1196
1197                            disconnectService();
1198                        }
1199                    } else if (mPendingInstalls.size() > 0) {
1200                        // There are more pending requests in queue.
1201                        // Just post MCS_BOUND message to trigger processing
1202                        // of next pending install.
1203                        mHandler.sendEmptyMessage(MCS_BOUND);
1204                    }
1205
1206                    break;
1207                }
1208                case MCS_GIVE_UP: {
1209                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1210                    mPendingInstalls.remove(0);
1211                    break;
1212                }
1213                case SEND_PENDING_BROADCAST: {
1214                    String packages[];
1215                    ArrayList<String> components[];
1216                    int size = 0;
1217                    int uids[];
1218                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1219                    synchronized (mPackages) {
1220                        if (mPendingBroadcasts == null) {
1221                            return;
1222                        }
1223                        size = mPendingBroadcasts.size();
1224                        if (size <= 0) {
1225                            // Nothing to be done. Just return
1226                            return;
1227                        }
1228                        packages = new String[size];
1229                        components = new ArrayList[size];
1230                        uids = new int[size];
1231                        int i = 0;  // filling out the above arrays
1232
1233                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1234                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1235                            Iterator<Map.Entry<String, ArrayList<String>>> it
1236                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1237                                            .entrySet().iterator();
1238                            while (it.hasNext() && i < size) {
1239                                Map.Entry<String, ArrayList<String>> ent = it.next();
1240                                packages[i] = ent.getKey();
1241                                components[i] = ent.getValue();
1242                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1243                                uids[i] = (ps != null)
1244                                        ? UserHandle.getUid(packageUserId, ps.appId)
1245                                        : -1;
1246                                i++;
1247                            }
1248                        }
1249                        size = i;
1250                        mPendingBroadcasts.clear();
1251                    }
1252                    // Send broadcasts
1253                    for (int i = 0; i < size; i++) {
1254                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1255                    }
1256                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1257                    break;
1258                }
1259                case START_CLEANING_PACKAGE: {
1260                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1261                    final String packageName = (String)msg.obj;
1262                    final int userId = msg.arg1;
1263                    final boolean andCode = msg.arg2 != 0;
1264                    synchronized (mPackages) {
1265                        if (userId == UserHandle.USER_ALL) {
1266                            int[] users = sUserManager.getUserIds();
1267                            for (int user : users) {
1268                                mSettings.addPackageToCleanLPw(
1269                                        new PackageCleanItem(user, packageName, andCode));
1270                            }
1271                        } else {
1272                            mSettings.addPackageToCleanLPw(
1273                                    new PackageCleanItem(userId, packageName, andCode));
1274                        }
1275                    }
1276                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1277                    startCleaningPackages();
1278                } break;
1279                case POST_INSTALL: {
1280                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1281                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1282                    mRunningInstalls.delete(msg.arg1);
1283                    boolean deleteOld = false;
1284
1285                    if (data != null) {
1286                        InstallArgs args = data.args;
1287                        PackageInstalledInfo res = data.res;
1288
1289                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1290                            res.removedInfo.sendBroadcast(false, true, false);
1291                            Bundle extras = new Bundle(1);
1292                            extras.putInt(Intent.EXTRA_UID, res.uid);
1293
1294                            // Now that we successfully installed the package, grant runtime
1295                            // permissions if requested before broadcasting the install.
1296                            if ((args.installFlags
1297                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1298                                grantRequestedRuntimePermissions(res.pkg,
1299                                        args.user.getIdentifier());
1300                            }
1301
1302                            // Determine the set of users who are adding this
1303                            // package for the first time vs. those who are seeing
1304                            // an update.
1305                            int[] firstUsers;
1306                            int[] updateUsers = new int[0];
1307                            if (res.origUsers == null || res.origUsers.length == 0) {
1308                                firstUsers = res.newUsers;
1309                            } else {
1310                                firstUsers = new int[0];
1311                                for (int i=0; i<res.newUsers.length; i++) {
1312                                    int user = res.newUsers[i];
1313                                    boolean isNew = true;
1314                                    for (int j=0; j<res.origUsers.length; j++) {
1315                                        if (res.origUsers[j] == user) {
1316                                            isNew = false;
1317                                            break;
1318                                        }
1319                                    }
1320                                    if (isNew) {
1321                                        int[] newFirst = new int[firstUsers.length+1];
1322                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1323                                                firstUsers.length);
1324                                        newFirst[firstUsers.length] = user;
1325                                        firstUsers = newFirst;
1326                                    } else {
1327                                        int[] newUpdate = new int[updateUsers.length+1];
1328                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1329                                                updateUsers.length);
1330                                        newUpdate[updateUsers.length] = user;
1331                                        updateUsers = newUpdate;
1332                                    }
1333                                }
1334                            }
1335                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1336                                    res.pkg.applicationInfo.packageName,
1337                                    extras, null, null, firstUsers);
1338                            final boolean update = res.removedInfo.removedPackage != null;
1339                            if (update) {
1340                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1341                            }
1342                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1343                                    res.pkg.applicationInfo.packageName,
1344                                    extras, null, null, updateUsers);
1345                            if (update) {
1346                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1347                                        res.pkg.applicationInfo.packageName,
1348                                        extras, null, null, updateUsers);
1349                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1350                                        null, null,
1351                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1352
1353                                // treat asec-hosted packages like removable media on upgrade
1354                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1355                                    if (DEBUG_INSTALL) {
1356                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1357                                                + " is ASEC-hosted -> AVAILABLE");
1358                                    }
1359                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1360                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1361                                    pkgList.add(res.pkg.applicationInfo.packageName);
1362                                    sendResourcesChangedBroadcast(true, true,
1363                                            pkgList,uidArray, null);
1364                                }
1365                            }
1366                            if (res.removedInfo.args != null) {
1367                                // Remove the replaced package's older resources safely now
1368                                deleteOld = true;
1369                            }
1370
1371                            // Log current value of "unknown sources" setting
1372                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1373                                getUnknownSourcesSettings());
1374                        }
1375                        // Force a gc to clear up things
1376                        Runtime.getRuntime().gc();
1377                        // We delete after a gc for applications  on sdcard.
1378                        if (deleteOld) {
1379                            synchronized (mInstallLock) {
1380                                res.removedInfo.args.doPostDeleteLI(true);
1381                            }
1382                        }
1383                        if (args.observer != null) {
1384                            try {
1385                                Bundle extras = extrasForInstallResult(res);
1386                                args.observer.onPackageInstalled(res.name, res.returnCode,
1387                                        res.returnMsg, extras);
1388                            } catch (RemoteException e) {
1389                                Slog.i(TAG, "Observer no longer exists.");
1390                            }
1391                        }
1392                    } else {
1393                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1394                    }
1395                } break;
1396                case UPDATED_MEDIA_STATUS: {
1397                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1398                    boolean reportStatus = msg.arg1 == 1;
1399                    boolean doGc = msg.arg2 == 1;
1400                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1401                    if (doGc) {
1402                        // Force a gc to clear up stale containers.
1403                        Runtime.getRuntime().gc();
1404                    }
1405                    if (msg.obj != null) {
1406                        @SuppressWarnings("unchecked")
1407                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1408                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1409                        // Unload containers
1410                        unloadAllContainers(args);
1411                    }
1412                    if (reportStatus) {
1413                        try {
1414                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1415                            PackageHelper.getMountService().finishMediaUpdate();
1416                        } catch (RemoteException e) {
1417                            Log.e(TAG, "MountService not running?");
1418                        }
1419                    }
1420                } break;
1421                case WRITE_SETTINGS: {
1422                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1423                    synchronized (mPackages) {
1424                        removeMessages(WRITE_SETTINGS);
1425                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1426                        mSettings.writeLPr();
1427                        mDirtyUsers.clear();
1428                    }
1429                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1430                } break;
1431                case WRITE_PACKAGE_RESTRICTIONS: {
1432                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1433                    synchronized (mPackages) {
1434                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1435                        for (int userId : mDirtyUsers) {
1436                            mSettings.writePackageRestrictionsLPr(userId);
1437                        }
1438                        mDirtyUsers.clear();
1439                    }
1440                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1441                } break;
1442                case CHECK_PENDING_VERIFICATION: {
1443                    final int verificationId = msg.arg1;
1444                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1445
1446                    if ((state != null) && !state.timeoutExtended()) {
1447                        final InstallArgs args = state.getInstallArgs();
1448                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1449
1450                        Slog.i(TAG, "Verification timed out for " + originUri);
1451                        mPendingVerification.remove(verificationId);
1452
1453                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1454
1455                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1456                            Slog.i(TAG, "Continuing with installation of " + originUri);
1457                            state.setVerifierResponse(Binder.getCallingUid(),
1458                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1459                            broadcastPackageVerified(verificationId, originUri,
1460                                    PackageManager.VERIFICATION_ALLOW,
1461                                    state.getInstallArgs().getUser());
1462                            try {
1463                                ret = args.copyApk(mContainerService, true);
1464                            } catch (RemoteException e) {
1465                                Slog.e(TAG, "Could not contact the ContainerService");
1466                            }
1467                        } else {
1468                            broadcastPackageVerified(verificationId, originUri,
1469                                    PackageManager.VERIFICATION_REJECT,
1470                                    state.getInstallArgs().getUser());
1471                        }
1472
1473                        processPendingInstall(args, ret);
1474                        mHandler.sendEmptyMessage(MCS_UNBIND);
1475                    }
1476                    break;
1477                }
1478                case PACKAGE_VERIFIED: {
1479                    final int verificationId = msg.arg1;
1480
1481                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1482                    if (state == null) {
1483                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1484                        break;
1485                    }
1486
1487                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1488
1489                    state.setVerifierResponse(response.callerUid, response.code);
1490
1491                    if (state.isVerificationComplete()) {
1492                        mPendingVerification.remove(verificationId);
1493
1494                        final InstallArgs args = state.getInstallArgs();
1495                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1496
1497                        int ret;
1498                        if (state.isInstallAllowed()) {
1499                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1500                            broadcastPackageVerified(verificationId, originUri,
1501                                    response.code, state.getInstallArgs().getUser());
1502                            try {
1503                                ret = args.copyApk(mContainerService, true);
1504                            } catch (RemoteException e) {
1505                                Slog.e(TAG, "Could not contact the ContainerService");
1506                            }
1507                        } else {
1508                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1509                        }
1510
1511                        processPendingInstall(args, ret);
1512
1513                        mHandler.sendEmptyMessage(MCS_UNBIND);
1514                    }
1515
1516                    break;
1517                }
1518                case START_INTENT_FILTER_VERIFICATIONS: {
1519                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1520                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1521                            params.replacing, params.pkg);
1522                    break;
1523                }
1524                case INTENT_FILTER_VERIFIED: {
1525                    final int verificationId = msg.arg1;
1526
1527                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1528                            verificationId);
1529                    if (state == null) {
1530                        Slog.w(TAG, "Invalid IntentFilter verification token "
1531                                + verificationId + " received");
1532                        break;
1533                    }
1534
1535                    final int userId = state.getUserId();
1536
1537                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1538                            "Processing IntentFilter verification with token:"
1539                            + verificationId + " and userId:" + userId);
1540
1541                    final IntentFilterVerificationResponse response =
1542                            (IntentFilterVerificationResponse) msg.obj;
1543
1544                    state.setVerifierResponse(response.callerUid, response.code);
1545
1546                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1547                            "IntentFilter verification with token:" + verificationId
1548                            + " and userId:" + userId
1549                            + " is settings verifier response with response code:"
1550                            + response.code);
1551
1552                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1553                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1554                                + response.getFailedDomainsString());
1555                    }
1556
1557                    if (state.isVerificationComplete()) {
1558                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1559                    } else {
1560                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1561                                "IntentFilter verification with token:" + verificationId
1562                                + " was not said to be complete");
1563                    }
1564
1565                    break;
1566                }
1567            }
1568        }
1569    }
1570
1571    private StorageEventListener mStorageListener = new StorageEventListener() {
1572        @Override
1573        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1574            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1575                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1576                    // TODO: ensure that private directories exist for all active users
1577                    // TODO: remove user data whose serial number doesn't match
1578                    loadPrivatePackages(vol);
1579                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1580                    unloadPrivatePackages(vol);
1581                }
1582            }
1583
1584            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1585                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1586                    updateExternalMediaStatus(true, false);
1587                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1588                    updateExternalMediaStatus(false, false);
1589                }
1590            }
1591        }
1592
1593        @Override
1594        public void onVolumeForgotten(String fsUuid) {
1595            // TODO: remove all packages hosted on this uuid
1596        }
1597    };
1598
1599    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1600        if (userId >= UserHandle.USER_OWNER) {
1601            grantRequestedRuntimePermissionsForUser(pkg, userId);
1602        } else if (userId == UserHandle.USER_ALL) {
1603            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1604                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1605            }
1606        }
1607
1608        // We could have touched GID membership, so flush out packages.list
1609        synchronized (mPackages) {
1610            mSettings.writePackageListLPr();
1611        }
1612    }
1613
1614    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1615        SettingBase sb = (SettingBase) pkg.mExtras;
1616        if (sb == null) {
1617            return;
1618        }
1619
1620        PermissionsState permissionsState = sb.getPermissionsState();
1621
1622        for (String permission : pkg.requestedPermissions) {
1623            BasePermission bp = mSettings.mPermissions.get(permission);
1624            if (bp != null && bp.isRuntime()) {
1625                permissionsState.grantRuntimePermission(bp, userId);
1626            }
1627        }
1628    }
1629
1630    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1631        Bundle extras = null;
1632        switch (res.returnCode) {
1633            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1634                extras = new Bundle();
1635                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1636                        res.origPermission);
1637                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1638                        res.origPackage);
1639                break;
1640            }
1641            case PackageManager.INSTALL_SUCCEEDED: {
1642                extras = new Bundle();
1643                extras.putBoolean(Intent.EXTRA_REPLACING,
1644                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1645                break;
1646            }
1647        }
1648        return extras;
1649    }
1650
1651    void scheduleWriteSettingsLocked() {
1652        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1653            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1654        }
1655    }
1656
1657    void scheduleWritePackageRestrictionsLocked(int userId) {
1658        if (!sUserManager.exists(userId)) return;
1659        mDirtyUsers.add(userId);
1660        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1661            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1662        }
1663    }
1664
1665    public static PackageManagerService main(Context context, Installer installer,
1666            boolean factoryTest, boolean onlyCore) {
1667        PackageManagerService m = new PackageManagerService(context, installer,
1668                factoryTest, onlyCore);
1669        ServiceManager.addService("package", m);
1670        return m;
1671    }
1672
1673    static String[] splitString(String str, char sep) {
1674        int count = 1;
1675        int i = 0;
1676        while ((i=str.indexOf(sep, i)) >= 0) {
1677            count++;
1678            i++;
1679        }
1680
1681        String[] res = new String[count];
1682        i=0;
1683        count = 0;
1684        int lastI=0;
1685        while ((i=str.indexOf(sep, i)) >= 0) {
1686            res[count] = str.substring(lastI, i);
1687            count++;
1688            i++;
1689            lastI = i;
1690        }
1691        res[count] = str.substring(lastI, str.length());
1692        return res;
1693    }
1694
1695    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1696        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1697                Context.DISPLAY_SERVICE);
1698        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1699    }
1700
1701    public PackageManagerService(Context context, Installer installer,
1702            boolean factoryTest, boolean onlyCore) {
1703        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1704                SystemClock.uptimeMillis());
1705
1706        if (mSdkVersion <= 0) {
1707            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1708        }
1709
1710        mContext = context;
1711        mFactoryTest = factoryTest;
1712        mOnlyCore = onlyCore;
1713        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1714        mMetrics = new DisplayMetrics();
1715        mSettings = new Settings(mPackages);
1716        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1717                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1718        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1719                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1720        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1721                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1722        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1723                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1724        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1725                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1726        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1727                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1728
1729        // TODO: add a property to control this?
1730        long dexOptLRUThresholdInMinutes;
1731        if (mLazyDexOpt) {
1732            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1733        } else {
1734            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1735        }
1736        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1737
1738        String separateProcesses = SystemProperties.get("debug.separate_processes");
1739        if (separateProcesses != null && separateProcesses.length() > 0) {
1740            if ("*".equals(separateProcesses)) {
1741                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1742                mSeparateProcesses = null;
1743                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1744            } else {
1745                mDefParseFlags = 0;
1746                mSeparateProcesses = separateProcesses.split(",");
1747                Slog.w(TAG, "Running with debug.separate_processes: "
1748                        + separateProcesses);
1749            }
1750        } else {
1751            mDefParseFlags = 0;
1752            mSeparateProcesses = null;
1753        }
1754
1755        mInstaller = installer;
1756        mPackageDexOptimizer = new PackageDexOptimizer(this);
1757        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1758
1759        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1760                FgThread.get().getLooper());
1761
1762        getDefaultDisplayMetrics(context, mMetrics);
1763
1764        SystemConfig systemConfig = SystemConfig.getInstance();
1765        mGlobalGids = systemConfig.getGlobalGids();
1766        mSystemPermissions = systemConfig.getSystemPermissions();
1767        mAvailableFeatures = systemConfig.getAvailableFeatures();
1768
1769        synchronized (mInstallLock) {
1770        // writer
1771        synchronized (mPackages) {
1772            mHandlerThread = new ServiceThread(TAG,
1773                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1774            mHandlerThread.start();
1775            mHandler = new PackageHandler(mHandlerThread.getLooper());
1776            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1777
1778            File dataDir = Environment.getDataDirectory();
1779            mAppDataDir = new File(dataDir, "data");
1780            mAppInstallDir = new File(dataDir, "app");
1781            mAppLib32InstallDir = new File(dataDir, "app-lib");
1782            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1783            mUserAppDataDir = new File(dataDir, "user");
1784            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1785
1786            sUserManager = new UserManagerService(context, this,
1787                    mInstallLock, mPackages);
1788
1789            // Propagate permission configuration in to package manager.
1790            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1791                    = systemConfig.getPermissions();
1792            for (int i=0; i<permConfig.size(); i++) {
1793                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1794                BasePermission bp = mSettings.mPermissions.get(perm.name);
1795                if (bp == null) {
1796                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1797                    mSettings.mPermissions.put(perm.name, bp);
1798                }
1799                if (perm.gids != null) {
1800                    bp.setGids(perm.gids, perm.perUser);
1801                }
1802            }
1803
1804            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1805            for (int i=0; i<libConfig.size(); i++) {
1806                mSharedLibraries.put(libConfig.keyAt(i),
1807                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1808            }
1809
1810            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1811
1812            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1813                    mSdkVersion, mOnlyCore);
1814
1815            String customResolverActivity = Resources.getSystem().getString(
1816                    R.string.config_customResolverActivity);
1817            if (TextUtils.isEmpty(customResolverActivity)) {
1818                customResolverActivity = null;
1819            } else {
1820                mCustomResolverComponentName = ComponentName.unflattenFromString(
1821                        customResolverActivity);
1822            }
1823
1824            long startTime = SystemClock.uptimeMillis();
1825
1826            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1827                    startTime);
1828
1829            // Set flag to monitor and not change apk file paths when
1830            // scanning install directories.
1831            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1832
1833            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1834
1835            /**
1836             * Add everything in the in the boot class path to the
1837             * list of process files because dexopt will have been run
1838             * if necessary during zygote startup.
1839             */
1840            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1841            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1842
1843            if (bootClassPath != null) {
1844                String[] bootClassPathElements = splitString(bootClassPath, ':');
1845                for (String element : bootClassPathElements) {
1846                    alreadyDexOpted.add(element);
1847                }
1848            } else {
1849                Slog.w(TAG, "No BOOTCLASSPATH found!");
1850            }
1851
1852            if (systemServerClassPath != null) {
1853                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1854                for (String element : systemServerClassPathElements) {
1855                    alreadyDexOpted.add(element);
1856                }
1857            } else {
1858                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1859            }
1860
1861            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1862            final String[] dexCodeInstructionSets =
1863                    getDexCodeInstructionSets(
1864                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1865
1866            /**
1867             * Ensure all external libraries have had dexopt run on them.
1868             */
1869            if (mSharedLibraries.size() > 0) {
1870                // NOTE: For now, we're compiling these system "shared libraries"
1871                // (and framework jars) into all available architectures. It's possible
1872                // to compile them only when we come across an app that uses them (there's
1873                // already logic for that in scanPackageLI) but that adds some complexity.
1874                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1875                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1876                        final String lib = libEntry.path;
1877                        if (lib == null) {
1878                            continue;
1879                        }
1880
1881                        try {
1882                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1883                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1884                                alreadyDexOpted.add(lib);
1885                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1886                            }
1887                        } catch (FileNotFoundException e) {
1888                            Slog.w(TAG, "Library not found: " + lib);
1889                        } catch (IOException e) {
1890                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1891                                    + e.getMessage());
1892                        }
1893                    }
1894                }
1895            }
1896
1897            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1898
1899            // Gross hack for now: we know this file doesn't contain any
1900            // code, so don't dexopt it to avoid the resulting log spew.
1901            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1902
1903            // Gross hack for now: we know this file is only part of
1904            // the boot class path for art, so don't dexopt it to
1905            // avoid the resulting log spew.
1906            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1907
1908            /**
1909             * There are a number of commands implemented in Java, which
1910             * we currently need to do the dexopt on so that they can be
1911             * run from a non-root shell.
1912             */
1913            String[] frameworkFiles = frameworkDir.list();
1914            if (frameworkFiles != null) {
1915                // TODO: We could compile these only for the most preferred ABI. We should
1916                // first double check that the dex files for these commands are not referenced
1917                // by other system apps.
1918                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1919                    for (int i=0; i<frameworkFiles.length; i++) {
1920                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1921                        String path = libPath.getPath();
1922                        // Skip the file if we already did it.
1923                        if (alreadyDexOpted.contains(path)) {
1924                            continue;
1925                        }
1926                        // Skip the file if it is not a type we want to dexopt.
1927                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1928                            continue;
1929                        }
1930                        try {
1931                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1932                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1933                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1934                            }
1935                        } catch (FileNotFoundException e) {
1936                            Slog.w(TAG, "Jar not found: " + path);
1937                        } catch (IOException e) {
1938                            Slog.w(TAG, "Exception reading jar: " + path, e);
1939                        }
1940                    }
1941                }
1942            }
1943
1944            // Collect vendor overlay packages.
1945            // (Do this before scanning any apps.)
1946            // For security and version matching reason, only consider
1947            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1948            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1949            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1950                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1951
1952            // Find base frameworks (resource packages without code).
1953            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1954                    | PackageParser.PARSE_IS_SYSTEM_DIR
1955                    | PackageParser.PARSE_IS_PRIVILEGED,
1956                    scanFlags | SCAN_NO_DEX, 0);
1957
1958            // Collected privileged system packages.
1959            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1960            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1961                    | PackageParser.PARSE_IS_SYSTEM_DIR
1962                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1963
1964            // Collect ordinary system packages.
1965            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1966            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1967                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1968
1969            // Collect all vendor packages.
1970            File vendorAppDir = new File("/vendor/app");
1971            try {
1972                vendorAppDir = vendorAppDir.getCanonicalFile();
1973            } catch (IOException e) {
1974                // failed to look up canonical path, continue with original one
1975            }
1976            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1977                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1978
1979            // Collect all OEM packages.
1980            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1981            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1982                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1983
1984            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1985            mInstaller.moveFiles();
1986
1987            // Prune any system packages that no longer exist.
1988            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1989            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1990            if (!mOnlyCore) {
1991                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1992                while (psit.hasNext()) {
1993                    PackageSetting ps = psit.next();
1994
1995                    /*
1996                     * If this is not a system app, it can't be a
1997                     * disable system app.
1998                     */
1999                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2000                        continue;
2001                    }
2002
2003                    /*
2004                     * If the package is scanned, it's not erased.
2005                     */
2006                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2007                    if (scannedPkg != null) {
2008                        /*
2009                         * If the system app is both scanned and in the
2010                         * disabled packages list, then it must have been
2011                         * added via OTA. Remove it from the currently
2012                         * scanned package so the previously user-installed
2013                         * application can be scanned.
2014                         */
2015                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2016                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2017                                    + ps.name + "; removing system app.  Last known codePath="
2018                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2019                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2020                                    + scannedPkg.mVersionCode);
2021                            removePackageLI(ps, true);
2022                            expectingBetter.put(ps.name, ps.codePath);
2023                        }
2024
2025                        continue;
2026                    }
2027
2028                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2029                        psit.remove();
2030                        logCriticalInfo(Log.WARN, "System package " + ps.name
2031                                + " no longer exists; wiping its data");
2032                        removeDataDirsLI(null, ps.name);
2033                    } else {
2034                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2035                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2036                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2037                        }
2038                    }
2039                }
2040            }
2041
2042            //look for any incomplete package installations
2043            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2044            //clean up list
2045            for(int i = 0; i < deletePkgsList.size(); i++) {
2046                //clean up here
2047                cleanupInstallFailedPackage(deletePkgsList.get(i));
2048            }
2049            //delete tmp files
2050            deleteTempPackageFiles();
2051
2052            // Remove any shared userIDs that have no associated packages
2053            mSettings.pruneSharedUsersLPw();
2054
2055            if (!mOnlyCore) {
2056                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2057                        SystemClock.uptimeMillis());
2058                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2059
2060                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2061                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2062
2063                /**
2064                 * Remove disable package settings for any updated system
2065                 * apps that were removed via an OTA. If they're not a
2066                 * previously-updated app, remove them completely.
2067                 * Otherwise, just revoke their system-level permissions.
2068                 */
2069                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2070                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2071                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2072
2073                    String msg;
2074                    if (deletedPkg == null) {
2075                        msg = "Updated system package " + deletedAppName
2076                                + " no longer exists; wiping its data";
2077                        removeDataDirsLI(null, deletedAppName);
2078                    } else {
2079                        msg = "Updated system app + " + deletedAppName
2080                                + " no longer present; removing system privileges for "
2081                                + deletedAppName;
2082
2083                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2084
2085                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2086                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2087                    }
2088                    logCriticalInfo(Log.WARN, msg);
2089                }
2090
2091                /**
2092                 * Make sure all system apps that we expected to appear on
2093                 * the userdata partition actually showed up. If they never
2094                 * appeared, crawl back and revive the system version.
2095                 */
2096                for (int i = 0; i < expectingBetter.size(); i++) {
2097                    final String packageName = expectingBetter.keyAt(i);
2098                    if (!mPackages.containsKey(packageName)) {
2099                        final File scanFile = expectingBetter.valueAt(i);
2100
2101                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2102                                + " but never showed up; reverting to system");
2103
2104                        final int reparseFlags;
2105                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2106                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2107                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2108                                    | PackageParser.PARSE_IS_PRIVILEGED;
2109                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2110                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2111                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2112                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2113                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2114                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2115                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2116                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2117                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2118                        } else {
2119                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2120                            continue;
2121                        }
2122
2123                        mSettings.enableSystemPackageLPw(packageName);
2124
2125                        try {
2126                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2127                        } catch (PackageManagerException e) {
2128                            Slog.e(TAG, "Failed to parse original system package: "
2129                                    + e.getMessage());
2130                        }
2131                    }
2132                }
2133            }
2134
2135            // Now that we know all of the shared libraries, update all clients to have
2136            // the correct library paths.
2137            updateAllSharedLibrariesLPw();
2138
2139            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2140                // NOTE: We ignore potential failures here during a system scan (like
2141                // the rest of the commands above) because there's precious little we
2142                // can do about it. A settings error is reported, though.
2143                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2144                        false /* force dexopt */, false /* defer dexopt */);
2145            }
2146
2147            // Now that we know all the packages we are keeping,
2148            // read and update their last usage times.
2149            mPackageUsage.readLP();
2150
2151            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2152                    SystemClock.uptimeMillis());
2153            Slog.i(TAG, "Time to scan packages: "
2154                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2155                    + " seconds");
2156
2157            // If the platform SDK has changed since the last time we booted,
2158            // we need to re-grant app permission to catch any new ones that
2159            // appear.  This is really a hack, and means that apps can in some
2160            // cases get permissions that the user didn't initially explicitly
2161            // allow...  it would be nice to have some better way to handle
2162            // this situation.
2163            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2164                    != mSdkVersion;
2165            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2166                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2167                    + "; regranting permissions for internal storage");
2168            mSettings.mInternalSdkPlatform = mSdkVersion;
2169
2170            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2171                    | (regrantPermissions
2172                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2173                            : 0));
2174
2175            // If this is the first boot, and it is a normal boot, then
2176            // we need to initialize the default preferred apps.
2177            if (!mRestoredSettings && !onlyCore) {
2178                mSettings.readDefaultPreferredAppsLPw(this, 0);
2179            }
2180
2181            // If this is first boot after an OTA, and a normal boot, then
2182            // we need to clear code cache directories.
2183            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2184            if (mIsUpgrade && !onlyCore) {
2185                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2186                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2187                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2188                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2189                }
2190                mSettings.mFingerprint = Build.FINGERPRINT;
2191            }
2192
2193            primeDomainVerificationsLPw();
2194            checkDefaultBrowser();
2195
2196            // All the changes are done during package scanning.
2197            mSettings.updateInternalDatabaseVersion();
2198
2199            // can downgrade to reader
2200            mSettings.writeLPr();
2201
2202            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2203                    SystemClock.uptimeMillis());
2204
2205            mRequiredVerifierPackage = getRequiredVerifierLPr();
2206
2207            mInstallerService = new PackageInstallerService(context, this);
2208
2209            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2210            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2211                    mIntentFilterVerifierComponent);
2212
2213        } // synchronized (mPackages)
2214        } // synchronized (mInstallLock)
2215
2216        // Now after opening every single application zip, make sure they
2217        // are all flushed.  Not really needed, but keeps things nice and
2218        // tidy.
2219        Runtime.getRuntime().gc();
2220    }
2221
2222    @Override
2223    public boolean isFirstBoot() {
2224        return !mRestoredSettings;
2225    }
2226
2227    @Override
2228    public boolean isOnlyCoreApps() {
2229        return mOnlyCore;
2230    }
2231
2232    @Override
2233    public boolean isUpgrade() {
2234        return mIsUpgrade;
2235    }
2236
2237    private String getRequiredVerifierLPr() {
2238        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2239        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2240                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2241
2242        String requiredVerifier = null;
2243
2244        final int N = receivers.size();
2245        for (int i = 0; i < N; i++) {
2246            final ResolveInfo info = receivers.get(i);
2247
2248            if (info.activityInfo == null) {
2249                continue;
2250            }
2251
2252            final String packageName = info.activityInfo.packageName;
2253
2254            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2255                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2256                continue;
2257            }
2258
2259            if (requiredVerifier != null) {
2260                throw new RuntimeException("There can be only one required verifier");
2261            }
2262
2263            requiredVerifier = packageName;
2264        }
2265
2266        return requiredVerifier;
2267    }
2268
2269    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2270        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2271        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2272                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2273
2274        ComponentName verifierComponentName = null;
2275
2276        int priority = -1000;
2277        final int N = receivers.size();
2278        for (int i = 0; i < N; i++) {
2279            final ResolveInfo info = receivers.get(i);
2280
2281            if (info.activityInfo == null) {
2282                continue;
2283            }
2284
2285            final String packageName = info.activityInfo.packageName;
2286
2287            final PackageSetting ps = mSettings.mPackages.get(packageName);
2288            if (ps == null) {
2289                continue;
2290            }
2291
2292            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2293                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2294                continue;
2295            }
2296
2297            // Select the IntentFilterVerifier with the highest priority
2298            if (priority < info.priority) {
2299                priority = info.priority;
2300                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2301                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2302                        + verifierComponentName + " with priority: " + info.priority);
2303            }
2304        }
2305
2306        return verifierComponentName;
2307    }
2308
2309    private void primeDomainVerificationsLPw() {
2310        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2311        boolean updated = false;
2312        ArraySet<String> allHostsSet = new ArraySet<>();
2313        for (PackageParser.Package pkg : mPackages.values()) {
2314            final String packageName = pkg.packageName;
2315            if (!hasDomainURLs(pkg)) {
2316                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2317                            "package with no domain URLs: " + packageName);
2318                continue;
2319            }
2320            if (!pkg.isSystemApp()) {
2321                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2322                        "No priming domain verifications for a non system package : " +
2323                                packageName);
2324                continue;
2325            }
2326            for (PackageParser.Activity a : pkg.activities) {
2327                for (ActivityIntentInfo filter : a.intents) {
2328                    if (hasValidDomains(filter)) {
2329                        allHostsSet.addAll(filter.getHostsList());
2330                    }
2331                }
2332            }
2333            if (allHostsSet.size() == 0) {
2334                allHostsSet.add("*");
2335            }
2336            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2337            IntentFilterVerificationInfo ivi =
2338                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2339            if (ivi != null) {
2340                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2341                        "Priming domain verifications for package: " + packageName +
2342                        " with hosts:" + ivi.getDomainsString());
2343                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2344                updated = true;
2345            }
2346            else {
2347                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2348                        "No priming domain verifications for package: " + packageName);
2349            }
2350            allHostsSet.clear();
2351        }
2352        if (updated) {
2353            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2354                    "Will need to write primed domain verifications");
2355        }
2356        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2357    }
2358
2359    private void checkDefaultBrowser() {
2360        final int myUserId = UserHandle.myUserId();
2361        final String packageName = getDefaultBrowserPackageName(myUserId);
2362        PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2363        if (info == null) {
2364            Slog.w(TAG, "Default browser no longer installed: " + packageName);
2365            setDefaultBrowserPackageName(null, myUserId);
2366        }
2367    }
2368
2369    @Override
2370    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2371            throws RemoteException {
2372        try {
2373            return super.onTransact(code, data, reply, flags);
2374        } catch (RuntimeException e) {
2375            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2376                Slog.wtf(TAG, "Package Manager Crash", e);
2377            }
2378            throw e;
2379        }
2380    }
2381
2382    void cleanupInstallFailedPackage(PackageSetting ps) {
2383        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2384
2385        removeDataDirsLI(ps.volumeUuid, ps.name);
2386        if (ps.codePath != null) {
2387            if (ps.codePath.isDirectory()) {
2388                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2389            } else {
2390                ps.codePath.delete();
2391            }
2392        }
2393        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2394            if (ps.resourcePath.isDirectory()) {
2395                FileUtils.deleteContents(ps.resourcePath);
2396            }
2397            ps.resourcePath.delete();
2398        }
2399        mSettings.removePackageLPw(ps.name);
2400    }
2401
2402    static int[] appendInts(int[] cur, int[] add) {
2403        if (add == null) return cur;
2404        if (cur == null) return add;
2405        final int N = add.length;
2406        for (int i=0; i<N; i++) {
2407            cur = appendInt(cur, add[i]);
2408        }
2409        return cur;
2410    }
2411
2412    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2413        if (!sUserManager.exists(userId)) return null;
2414        final PackageSetting ps = (PackageSetting) p.mExtras;
2415        if (ps == null) {
2416            return null;
2417        }
2418
2419        final PermissionsState permissionsState = ps.getPermissionsState();
2420
2421        final int[] gids = permissionsState.computeGids(userId);
2422        final Set<String> permissions = permissionsState.getPermissions(userId);
2423        final PackageUserState state = ps.readUserState(userId);
2424
2425        return PackageParser.generatePackageInfo(p, gids, flags,
2426                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2427    }
2428
2429    @Override
2430    public boolean isPackageFrozen(String packageName) {
2431        synchronized (mPackages) {
2432            final PackageSetting ps = mSettings.mPackages.get(packageName);
2433            if (ps != null) {
2434                return ps.frozen;
2435            }
2436        }
2437        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2438        return true;
2439    }
2440
2441    @Override
2442    public boolean isPackageAvailable(String packageName, int userId) {
2443        if (!sUserManager.exists(userId)) return false;
2444        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2445        synchronized (mPackages) {
2446            PackageParser.Package p = mPackages.get(packageName);
2447            if (p != null) {
2448                final PackageSetting ps = (PackageSetting) p.mExtras;
2449                if (ps != null) {
2450                    final PackageUserState state = ps.readUserState(userId);
2451                    if (state != null) {
2452                        return PackageParser.isAvailable(state);
2453                    }
2454                }
2455            }
2456        }
2457        return false;
2458    }
2459
2460    @Override
2461    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2462        if (!sUserManager.exists(userId)) return null;
2463        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2464        // reader
2465        synchronized (mPackages) {
2466            PackageParser.Package p = mPackages.get(packageName);
2467            if (DEBUG_PACKAGE_INFO)
2468                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2469            if (p != null) {
2470                return generatePackageInfo(p, flags, userId);
2471            }
2472            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2473                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2474            }
2475        }
2476        return null;
2477    }
2478
2479    @Override
2480    public String[] currentToCanonicalPackageNames(String[] names) {
2481        String[] out = new String[names.length];
2482        // reader
2483        synchronized (mPackages) {
2484            for (int i=names.length-1; i>=0; i--) {
2485                PackageSetting ps = mSettings.mPackages.get(names[i]);
2486                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2487            }
2488        }
2489        return out;
2490    }
2491
2492    @Override
2493    public String[] canonicalToCurrentPackageNames(String[] names) {
2494        String[] out = new String[names.length];
2495        // reader
2496        synchronized (mPackages) {
2497            for (int i=names.length-1; i>=0; i--) {
2498                String cur = mSettings.mRenamedPackages.get(names[i]);
2499                out[i] = cur != null ? cur : names[i];
2500            }
2501        }
2502        return out;
2503    }
2504
2505    @Override
2506    public int getPackageUid(String packageName, int userId) {
2507        if (!sUserManager.exists(userId)) return -1;
2508        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2509
2510        // reader
2511        synchronized (mPackages) {
2512            PackageParser.Package p = mPackages.get(packageName);
2513            if(p != null) {
2514                return UserHandle.getUid(userId, p.applicationInfo.uid);
2515            }
2516            PackageSetting ps = mSettings.mPackages.get(packageName);
2517            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2518                return -1;
2519            }
2520            p = ps.pkg;
2521            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2522        }
2523    }
2524
2525    @Override
2526    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2527        if (!sUserManager.exists(userId)) {
2528            return null;
2529        }
2530
2531        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2532                "getPackageGids");
2533
2534        // reader
2535        synchronized (mPackages) {
2536            PackageParser.Package p = mPackages.get(packageName);
2537            if (DEBUG_PACKAGE_INFO) {
2538                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2539            }
2540            if (p != null) {
2541                PackageSetting ps = (PackageSetting) p.mExtras;
2542                return ps.getPermissionsState().computeGids(userId);
2543            }
2544        }
2545
2546        return null;
2547    }
2548
2549    static PermissionInfo generatePermissionInfo(
2550            BasePermission bp, int flags) {
2551        if (bp.perm != null) {
2552            return PackageParser.generatePermissionInfo(bp.perm, flags);
2553        }
2554        PermissionInfo pi = new PermissionInfo();
2555        pi.name = bp.name;
2556        pi.packageName = bp.sourcePackage;
2557        pi.nonLocalizedLabel = bp.name;
2558        pi.protectionLevel = bp.protectionLevel;
2559        return pi;
2560    }
2561
2562    @Override
2563    public PermissionInfo getPermissionInfo(String name, int flags) {
2564        // reader
2565        synchronized (mPackages) {
2566            final BasePermission p = mSettings.mPermissions.get(name);
2567            if (p != null) {
2568                return generatePermissionInfo(p, flags);
2569            }
2570            return null;
2571        }
2572    }
2573
2574    @Override
2575    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2576        // reader
2577        synchronized (mPackages) {
2578            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2579            for (BasePermission p : mSettings.mPermissions.values()) {
2580                if (group == null) {
2581                    if (p.perm == null || p.perm.info.group == null) {
2582                        out.add(generatePermissionInfo(p, flags));
2583                    }
2584                } else {
2585                    if (p.perm != null && group.equals(p.perm.info.group)) {
2586                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2587                    }
2588                }
2589            }
2590
2591            if (out.size() > 0) {
2592                return out;
2593            }
2594            return mPermissionGroups.containsKey(group) ? out : null;
2595        }
2596    }
2597
2598    @Override
2599    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2600        // reader
2601        synchronized (mPackages) {
2602            return PackageParser.generatePermissionGroupInfo(
2603                    mPermissionGroups.get(name), flags);
2604        }
2605    }
2606
2607    @Override
2608    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2609        // reader
2610        synchronized (mPackages) {
2611            final int N = mPermissionGroups.size();
2612            ArrayList<PermissionGroupInfo> out
2613                    = new ArrayList<PermissionGroupInfo>(N);
2614            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2615                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2616            }
2617            return out;
2618        }
2619    }
2620
2621    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2622            int userId) {
2623        if (!sUserManager.exists(userId)) return null;
2624        PackageSetting ps = mSettings.mPackages.get(packageName);
2625        if (ps != null) {
2626            if (ps.pkg == null) {
2627                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2628                        flags, userId);
2629                if (pInfo != null) {
2630                    return pInfo.applicationInfo;
2631                }
2632                return null;
2633            }
2634            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2635                    ps.readUserState(userId), userId);
2636        }
2637        return null;
2638    }
2639
2640    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2641            int userId) {
2642        if (!sUserManager.exists(userId)) return null;
2643        PackageSetting ps = mSettings.mPackages.get(packageName);
2644        if (ps != null) {
2645            PackageParser.Package pkg = ps.pkg;
2646            if (pkg == null) {
2647                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2648                    return null;
2649                }
2650                // Only data remains, so we aren't worried about code paths
2651                pkg = new PackageParser.Package(packageName);
2652                pkg.applicationInfo.packageName = packageName;
2653                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2654                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2655                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2656                        packageName, userId).getAbsolutePath();
2657                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2658                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2659            }
2660            return generatePackageInfo(pkg, flags, userId);
2661        }
2662        return null;
2663    }
2664
2665    @Override
2666    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2667        if (!sUserManager.exists(userId)) return null;
2668        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2669        // writer
2670        synchronized (mPackages) {
2671            PackageParser.Package p = mPackages.get(packageName);
2672            if (DEBUG_PACKAGE_INFO) Log.v(
2673                    TAG, "getApplicationInfo " + packageName
2674                    + ": " + p);
2675            if (p != null) {
2676                PackageSetting ps = mSettings.mPackages.get(packageName);
2677                if (ps == null) return null;
2678                // Note: isEnabledLP() does not apply here - always return info
2679                return PackageParser.generateApplicationInfo(
2680                        p, flags, ps.readUserState(userId), userId);
2681            }
2682            if ("android".equals(packageName)||"system".equals(packageName)) {
2683                return mAndroidApplication;
2684            }
2685            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2686                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2687            }
2688        }
2689        return null;
2690    }
2691
2692    @Override
2693    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2694            final IPackageDataObserver observer) {
2695        mContext.enforceCallingOrSelfPermission(
2696                android.Manifest.permission.CLEAR_APP_CACHE, null);
2697        // Queue up an async operation since clearing cache may take a little while.
2698        mHandler.post(new Runnable() {
2699            public void run() {
2700                mHandler.removeCallbacks(this);
2701                int retCode = -1;
2702                synchronized (mInstallLock) {
2703                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2704                    if (retCode < 0) {
2705                        Slog.w(TAG, "Couldn't clear application caches");
2706                    }
2707                }
2708                if (observer != null) {
2709                    try {
2710                        observer.onRemoveCompleted(null, (retCode >= 0));
2711                    } catch (RemoteException e) {
2712                        Slog.w(TAG, "RemoveException when invoking call back");
2713                    }
2714                }
2715            }
2716        });
2717    }
2718
2719    @Override
2720    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2721            final IntentSender pi) {
2722        mContext.enforceCallingOrSelfPermission(
2723                android.Manifest.permission.CLEAR_APP_CACHE, null);
2724        // Queue up an async operation since clearing cache may take a little while.
2725        mHandler.post(new Runnable() {
2726            public void run() {
2727                mHandler.removeCallbacks(this);
2728                int retCode = -1;
2729                synchronized (mInstallLock) {
2730                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2731                    if (retCode < 0) {
2732                        Slog.w(TAG, "Couldn't clear application caches");
2733                    }
2734                }
2735                if(pi != null) {
2736                    try {
2737                        // Callback via pending intent
2738                        int code = (retCode >= 0) ? 1 : 0;
2739                        pi.sendIntent(null, code, null,
2740                                null, null);
2741                    } catch (SendIntentException e1) {
2742                        Slog.i(TAG, "Failed to send pending intent");
2743                    }
2744                }
2745            }
2746        });
2747    }
2748
2749    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2750        synchronized (mInstallLock) {
2751            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2752                throw new IOException("Failed to free enough space");
2753            }
2754        }
2755    }
2756
2757    @Override
2758    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2759        if (!sUserManager.exists(userId)) return null;
2760        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2761        synchronized (mPackages) {
2762            PackageParser.Activity a = mActivities.mActivities.get(component);
2763
2764            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2765            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2766                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2767                if (ps == null) return null;
2768                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2769                        userId);
2770            }
2771            if (mResolveComponentName.equals(component)) {
2772                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2773                        new PackageUserState(), userId);
2774            }
2775        }
2776        return null;
2777    }
2778
2779    @Override
2780    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2781            String resolvedType) {
2782        synchronized (mPackages) {
2783            PackageParser.Activity a = mActivities.mActivities.get(component);
2784            if (a == null) {
2785                return false;
2786            }
2787            for (int i=0; i<a.intents.size(); i++) {
2788                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2789                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2790                    return true;
2791                }
2792            }
2793            return false;
2794        }
2795    }
2796
2797    @Override
2798    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2799        if (!sUserManager.exists(userId)) return null;
2800        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2801        synchronized (mPackages) {
2802            PackageParser.Activity a = mReceivers.mActivities.get(component);
2803            if (DEBUG_PACKAGE_INFO) Log.v(
2804                TAG, "getReceiverInfo " + component + ": " + a);
2805            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2806                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2807                if (ps == null) return null;
2808                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2809                        userId);
2810            }
2811        }
2812        return null;
2813    }
2814
2815    @Override
2816    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2817        if (!sUserManager.exists(userId)) return null;
2818        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2819        synchronized (mPackages) {
2820            PackageParser.Service s = mServices.mServices.get(component);
2821            if (DEBUG_PACKAGE_INFO) Log.v(
2822                TAG, "getServiceInfo " + component + ": " + s);
2823            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2824                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2825                if (ps == null) return null;
2826                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2827                        userId);
2828            }
2829        }
2830        return null;
2831    }
2832
2833    @Override
2834    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2835        if (!sUserManager.exists(userId)) return null;
2836        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2837        synchronized (mPackages) {
2838            PackageParser.Provider p = mProviders.mProviders.get(component);
2839            if (DEBUG_PACKAGE_INFO) Log.v(
2840                TAG, "getProviderInfo " + component + ": " + p);
2841            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2842                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2843                if (ps == null) return null;
2844                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2845                        userId);
2846            }
2847        }
2848        return null;
2849    }
2850
2851    @Override
2852    public String[] getSystemSharedLibraryNames() {
2853        Set<String> libSet;
2854        synchronized (mPackages) {
2855            libSet = mSharedLibraries.keySet();
2856            int size = libSet.size();
2857            if (size > 0) {
2858                String[] libs = new String[size];
2859                libSet.toArray(libs);
2860                return libs;
2861            }
2862        }
2863        return null;
2864    }
2865
2866    /**
2867     * @hide
2868     */
2869    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2870        synchronized (mPackages) {
2871            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2872            if (lib != null && lib.apk != null) {
2873                return mPackages.get(lib.apk);
2874            }
2875        }
2876        return null;
2877    }
2878
2879    @Override
2880    public FeatureInfo[] getSystemAvailableFeatures() {
2881        Collection<FeatureInfo> featSet;
2882        synchronized (mPackages) {
2883            featSet = mAvailableFeatures.values();
2884            int size = featSet.size();
2885            if (size > 0) {
2886                FeatureInfo[] features = new FeatureInfo[size+1];
2887                featSet.toArray(features);
2888                FeatureInfo fi = new FeatureInfo();
2889                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2890                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2891                features[size] = fi;
2892                return features;
2893            }
2894        }
2895        return null;
2896    }
2897
2898    @Override
2899    public boolean hasSystemFeature(String name) {
2900        synchronized (mPackages) {
2901            return mAvailableFeatures.containsKey(name);
2902        }
2903    }
2904
2905    private void checkValidCaller(int uid, int userId) {
2906        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2907            return;
2908
2909        throw new SecurityException("Caller uid=" + uid
2910                + " is not privileged to communicate with user=" + userId);
2911    }
2912
2913    @Override
2914    public int checkPermission(String permName, String pkgName, int userId) {
2915        if (!sUserManager.exists(userId)) {
2916            return PackageManager.PERMISSION_DENIED;
2917        }
2918
2919        synchronized (mPackages) {
2920            final PackageParser.Package p = mPackages.get(pkgName);
2921            if (p != null && p.mExtras != null) {
2922                final PackageSetting ps = (PackageSetting) p.mExtras;
2923                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2924                    return PackageManager.PERMISSION_GRANTED;
2925                }
2926            }
2927        }
2928
2929        return PackageManager.PERMISSION_DENIED;
2930    }
2931
2932    @Override
2933    public int checkUidPermission(String permName, int uid) {
2934        final int userId = UserHandle.getUserId(uid);
2935
2936        if (!sUserManager.exists(userId)) {
2937            return PackageManager.PERMISSION_DENIED;
2938        }
2939
2940        synchronized (mPackages) {
2941            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2942            if (obj != null) {
2943                final SettingBase ps = (SettingBase) obj;
2944                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2945                    return PackageManager.PERMISSION_GRANTED;
2946                }
2947            } else {
2948                ArraySet<String> perms = mSystemPermissions.get(uid);
2949                if (perms != null && perms.contains(permName)) {
2950                    return PackageManager.PERMISSION_GRANTED;
2951                }
2952            }
2953        }
2954
2955        return PackageManager.PERMISSION_DENIED;
2956    }
2957
2958    /**
2959     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2960     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2961     * @param checkShell TODO(yamasani):
2962     * @param message the message to log on security exception
2963     */
2964    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2965            boolean checkShell, String message) {
2966        if (userId < 0) {
2967            throw new IllegalArgumentException("Invalid userId " + userId);
2968        }
2969        if (checkShell) {
2970            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2971        }
2972        if (userId == UserHandle.getUserId(callingUid)) return;
2973        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2974            if (requireFullPermission) {
2975                mContext.enforceCallingOrSelfPermission(
2976                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2977            } else {
2978                try {
2979                    mContext.enforceCallingOrSelfPermission(
2980                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2981                } catch (SecurityException se) {
2982                    mContext.enforceCallingOrSelfPermission(
2983                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2984                }
2985            }
2986        }
2987    }
2988
2989    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2990        if (callingUid == Process.SHELL_UID) {
2991            if (userHandle >= 0
2992                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2993                throw new SecurityException("Shell does not have permission to access user "
2994                        + userHandle);
2995            } else if (userHandle < 0) {
2996                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2997                        + Debug.getCallers(3));
2998            }
2999        }
3000    }
3001
3002    private BasePermission findPermissionTreeLP(String permName) {
3003        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3004            if (permName.startsWith(bp.name) &&
3005                    permName.length() > bp.name.length() &&
3006                    permName.charAt(bp.name.length()) == '.') {
3007                return bp;
3008            }
3009        }
3010        return null;
3011    }
3012
3013    private BasePermission checkPermissionTreeLP(String permName) {
3014        if (permName != null) {
3015            BasePermission bp = findPermissionTreeLP(permName);
3016            if (bp != null) {
3017                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3018                    return bp;
3019                }
3020                throw new SecurityException("Calling uid "
3021                        + Binder.getCallingUid()
3022                        + " is not allowed to add to permission tree "
3023                        + bp.name + " owned by uid " + bp.uid);
3024            }
3025        }
3026        throw new SecurityException("No permission tree found for " + permName);
3027    }
3028
3029    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3030        if (s1 == null) {
3031            return s2 == null;
3032        }
3033        if (s2 == null) {
3034            return false;
3035        }
3036        if (s1.getClass() != s2.getClass()) {
3037            return false;
3038        }
3039        return s1.equals(s2);
3040    }
3041
3042    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3043        if (pi1.icon != pi2.icon) return false;
3044        if (pi1.logo != pi2.logo) return false;
3045        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3046        if (!compareStrings(pi1.name, pi2.name)) return false;
3047        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3048        // We'll take care of setting this one.
3049        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3050        // These are not currently stored in settings.
3051        //if (!compareStrings(pi1.group, pi2.group)) return false;
3052        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3053        //if (pi1.labelRes != pi2.labelRes) return false;
3054        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3055        return true;
3056    }
3057
3058    int permissionInfoFootprint(PermissionInfo info) {
3059        int size = info.name.length();
3060        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3061        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3062        return size;
3063    }
3064
3065    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3066        int size = 0;
3067        for (BasePermission perm : mSettings.mPermissions.values()) {
3068            if (perm.uid == tree.uid) {
3069                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3070            }
3071        }
3072        return size;
3073    }
3074
3075    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3076        // We calculate the max size of permissions defined by this uid and throw
3077        // if that plus the size of 'info' would exceed our stated maximum.
3078        if (tree.uid != Process.SYSTEM_UID) {
3079            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3080            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3081                throw new SecurityException("Permission tree size cap exceeded");
3082            }
3083        }
3084    }
3085
3086    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3087        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3088            throw new SecurityException("Label must be specified in permission");
3089        }
3090        BasePermission tree = checkPermissionTreeLP(info.name);
3091        BasePermission bp = mSettings.mPermissions.get(info.name);
3092        boolean added = bp == null;
3093        boolean changed = true;
3094        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3095        if (added) {
3096            enforcePermissionCapLocked(info, tree);
3097            bp = new BasePermission(info.name, tree.sourcePackage,
3098                    BasePermission.TYPE_DYNAMIC);
3099        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3100            throw new SecurityException(
3101                    "Not allowed to modify non-dynamic permission "
3102                    + info.name);
3103        } else {
3104            if (bp.protectionLevel == fixedLevel
3105                    && bp.perm.owner.equals(tree.perm.owner)
3106                    && bp.uid == tree.uid
3107                    && comparePermissionInfos(bp.perm.info, info)) {
3108                changed = false;
3109            }
3110        }
3111        bp.protectionLevel = fixedLevel;
3112        info = new PermissionInfo(info);
3113        info.protectionLevel = fixedLevel;
3114        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3115        bp.perm.info.packageName = tree.perm.info.packageName;
3116        bp.uid = tree.uid;
3117        if (added) {
3118            mSettings.mPermissions.put(info.name, bp);
3119        }
3120        if (changed) {
3121            if (!async) {
3122                mSettings.writeLPr();
3123            } else {
3124                scheduleWriteSettingsLocked();
3125            }
3126        }
3127        return added;
3128    }
3129
3130    @Override
3131    public boolean addPermission(PermissionInfo info) {
3132        synchronized (mPackages) {
3133            return addPermissionLocked(info, false);
3134        }
3135    }
3136
3137    @Override
3138    public boolean addPermissionAsync(PermissionInfo info) {
3139        synchronized (mPackages) {
3140            return addPermissionLocked(info, true);
3141        }
3142    }
3143
3144    @Override
3145    public void removePermission(String name) {
3146        synchronized (mPackages) {
3147            checkPermissionTreeLP(name);
3148            BasePermission bp = mSettings.mPermissions.get(name);
3149            if (bp != null) {
3150                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3151                    throw new SecurityException(
3152                            "Not allowed to modify non-dynamic permission "
3153                            + name);
3154                }
3155                mSettings.mPermissions.remove(name);
3156                mSettings.writeLPr();
3157            }
3158        }
3159    }
3160
3161    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3162            BasePermission bp) {
3163        int index = pkg.requestedPermissions.indexOf(bp.name);
3164        if (index == -1) {
3165            throw new SecurityException("Package " + pkg.packageName
3166                    + " has not requested permission " + bp.name);
3167        }
3168        if (!bp.isRuntime()) {
3169            throw new SecurityException("Permission " + bp.name
3170                    + " is not a changeable permission type");
3171        }
3172    }
3173
3174    @Override
3175    public void grantRuntimePermission(String packageName, String name, int userId) {
3176        if (!sUserManager.exists(userId)) {
3177            Log.e(TAG, "No such user:" + userId);
3178            return;
3179        }
3180
3181        mContext.enforceCallingOrSelfPermission(
3182                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3183                "grantRuntimePermission");
3184
3185        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3186                "grantRuntimePermission");
3187
3188        boolean gidsChanged = false;
3189        final SettingBase sb;
3190
3191        synchronized (mPackages) {
3192            final PackageParser.Package pkg = mPackages.get(packageName);
3193            if (pkg == null) {
3194                throw new IllegalArgumentException("Unknown package: " + packageName);
3195            }
3196
3197            final BasePermission bp = mSettings.mPermissions.get(name);
3198            if (bp == null) {
3199                throw new IllegalArgumentException("Unknown permission: " + name);
3200            }
3201
3202            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3203
3204            sb = (SettingBase) pkg.mExtras;
3205            if (sb == null) {
3206                throw new IllegalArgumentException("Unknown package: " + packageName);
3207            }
3208
3209            final PermissionsState permissionsState = sb.getPermissionsState();
3210
3211            final int flags = permissionsState.getPermissionFlags(name, userId);
3212            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3213                throw new SecurityException("Cannot grant system fixed permission: "
3214                        + name + " for package: " + packageName);
3215            }
3216
3217            final int result = permissionsState.grantRuntimePermission(bp, userId);
3218            switch (result) {
3219                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3220                    return;
3221                }
3222
3223                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3224                    gidsChanged = true;
3225                } break;
3226            }
3227
3228            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3229
3230            // Not critical if that is lost - app has to request again.
3231            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3232        }
3233
3234        if (gidsChanged) {
3235            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3236        }
3237    }
3238
3239    @Override
3240    public void revokeRuntimePermission(String packageName, String name, int userId) {
3241        if (!sUserManager.exists(userId)) {
3242            Log.e(TAG, "No such user:" + userId);
3243            return;
3244        }
3245
3246        mContext.enforceCallingOrSelfPermission(
3247                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3248                "revokeRuntimePermission");
3249
3250        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3251                "revokeRuntimePermission");
3252
3253        final SettingBase sb;
3254
3255        synchronized (mPackages) {
3256            final PackageParser.Package pkg = mPackages.get(packageName);
3257            if (pkg == null) {
3258                throw new IllegalArgumentException("Unknown package: " + packageName);
3259            }
3260
3261            final BasePermission bp = mSettings.mPermissions.get(name);
3262            if (bp == null) {
3263                throw new IllegalArgumentException("Unknown permission: " + name);
3264            }
3265
3266            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3267
3268            sb = (SettingBase) pkg.mExtras;
3269            if (sb == null) {
3270                throw new IllegalArgumentException("Unknown package: " + packageName);
3271            }
3272
3273            final PermissionsState permissionsState = sb.getPermissionsState();
3274
3275            final int flags = permissionsState.getPermissionFlags(name, userId);
3276            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3277                throw new SecurityException("Cannot revoke system fixed permission: "
3278                        + name + " for package: " + packageName);
3279            }
3280
3281            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3282                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3283                return;
3284            }
3285
3286            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3287
3288            // Critical, after this call app should never have the permission.
3289            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3290        }
3291
3292        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3293    }
3294
3295    @Override
3296    public int getPermissionFlags(String name, String packageName, int userId) {
3297        if (!sUserManager.exists(userId)) {
3298            return 0;
3299        }
3300
3301        mContext.enforceCallingOrSelfPermission(
3302                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3303                "getPermissionFlags");
3304
3305        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3306                "getPermissionFlags");
3307
3308        synchronized (mPackages) {
3309            final PackageParser.Package pkg = mPackages.get(packageName);
3310            if (pkg == null) {
3311                throw new IllegalArgumentException("Unknown package: " + packageName);
3312            }
3313
3314            final BasePermission bp = mSettings.mPermissions.get(name);
3315            if (bp == null) {
3316                throw new IllegalArgumentException("Unknown permission: " + name);
3317            }
3318
3319            SettingBase sb = (SettingBase) pkg.mExtras;
3320            if (sb == null) {
3321                throw new IllegalArgumentException("Unknown package: " + packageName);
3322            }
3323
3324            PermissionsState permissionsState = sb.getPermissionsState();
3325            return permissionsState.getPermissionFlags(name, userId);
3326        }
3327    }
3328
3329    @Override
3330    public void updatePermissionFlags(String name, String packageName, int flagMask,
3331            int flagValues, int userId) {
3332        if (!sUserManager.exists(userId)) {
3333            return;
3334        }
3335
3336        mContext.enforceCallingOrSelfPermission(
3337                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3338                "updatePermissionFlags");
3339
3340        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3341                "updatePermissionFlags");
3342
3343        // Only the system can change policy flags.
3344        if (getCallingUid() != Process.SYSTEM_UID) {
3345            flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3346            flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3347        }
3348
3349        // Only the package manager can change system flags.
3350        flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3351        flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3352
3353        synchronized (mPackages) {
3354            final PackageParser.Package pkg = mPackages.get(packageName);
3355            if (pkg == null) {
3356                throw new IllegalArgumentException("Unknown package: " + packageName);
3357            }
3358
3359            final BasePermission bp = mSettings.mPermissions.get(name);
3360            if (bp == null) {
3361                throw new IllegalArgumentException("Unknown permission: " + name);
3362            }
3363
3364            SettingBase sb = (SettingBase) pkg.mExtras;
3365            if (sb == null) {
3366                throw new IllegalArgumentException("Unknown package: " + packageName);
3367            }
3368
3369            PermissionsState permissionsState = sb.getPermissionsState();
3370
3371            // Only the package manager can change flags for system component permissions.
3372            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3373            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3374                return;
3375            }
3376
3377            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3378                // Install and runtime permissions are stored in different places,
3379                // so figure out what permission changed and persist the change.
3380                if (permissionsState.getInstallPermissionState(name) != null) {
3381                    scheduleWriteSettingsLocked();
3382                } else if (permissionsState.getRuntimePermissionState(name, userId) != null) {
3383                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3384                }
3385            }
3386        }
3387    }
3388
3389    @Override
3390    public boolean shouldShowRequestPermissionRationale(String permissionName,
3391            String packageName, int userId) {
3392        if (UserHandle.getCallingUserId() != userId) {
3393            mContext.enforceCallingPermission(
3394                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3395                    "canShowRequestPermissionRationale for user " + userId);
3396        }
3397
3398        final int uid = getPackageUid(packageName, userId);
3399        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3400            return false;
3401        }
3402
3403        if (checkPermission(permissionName, packageName, userId)
3404                == PackageManager.PERMISSION_GRANTED) {
3405            return false;
3406        }
3407
3408        final int flags;
3409
3410        final long identity = Binder.clearCallingIdentity();
3411        try {
3412            flags = getPermissionFlags(permissionName,
3413                    packageName, userId);
3414        } finally {
3415            Binder.restoreCallingIdentity(identity);
3416        }
3417
3418        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3419                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3420                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3421
3422        if ((flags & fixedFlags) != 0) {
3423            return false;
3424        }
3425
3426        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3427    }
3428
3429    @Override
3430    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3431        mContext.enforceCallingOrSelfPermission(
3432                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3433                "addOnPermissionsChangeListener");
3434
3435        synchronized (mPackages) {
3436            mOnPermissionChangeListeners.addListenerLocked(listener);
3437        }
3438    }
3439
3440    @Override
3441    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3442        synchronized (mPackages) {
3443            mOnPermissionChangeListeners.removeListenerLocked(listener);
3444        }
3445    }
3446
3447    @Override
3448    public boolean isProtectedBroadcast(String actionName) {
3449        synchronized (mPackages) {
3450            return mProtectedBroadcasts.contains(actionName);
3451        }
3452    }
3453
3454    @Override
3455    public int checkSignatures(String pkg1, String pkg2) {
3456        synchronized (mPackages) {
3457            final PackageParser.Package p1 = mPackages.get(pkg1);
3458            final PackageParser.Package p2 = mPackages.get(pkg2);
3459            if (p1 == null || p1.mExtras == null
3460                    || p2 == null || p2.mExtras == null) {
3461                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3462            }
3463            return compareSignatures(p1.mSignatures, p2.mSignatures);
3464        }
3465    }
3466
3467    @Override
3468    public int checkUidSignatures(int uid1, int uid2) {
3469        // Map to base uids.
3470        uid1 = UserHandle.getAppId(uid1);
3471        uid2 = UserHandle.getAppId(uid2);
3472        // reader
3473        synchronized (mPackages) {
3474            Signature[] s1;
3475            Signature[] s2;
3476            Object obj = mSettings.getUserIdLPr(uid1);
3477            if (obj != null) {
3478                if (obj instanceof SharedUserSetting) {
3479                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3480                } else if (obj instanceof PackageSetting) {
3481                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3482                } else {
3483                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3484                }
3485            } else {
3486                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3487            }
3488            obj = mSettings.getUserIdLPr(uid2);
3489            if (obj != null) {
3490                if (obj instanceof SharedUserSetting) {
3491                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3492                } else if (obj instanceof PackageSetting) {
3493                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3494                } else {
3495                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3496                }
3497            } else {
3498                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3499            }
3500            return compareSignatures(s1, s2);
3501        }
3502    }
3503
3504    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3505        final long identity = Binder.clearCallingIdentity();
3506        try {
3507            if (sb instanceof SharedUserSetting) {
3508                SharedUserSetting sus = (SharedUserSetting) sb;
3509                final int packageCount = sus.packages.size();
3510                for (int i = 0; i < packageCount; i++) {
3511                    PackageSetting susPs = sus.packages.valueAt(i);
3512                    if (userId == UserHandle.USER_ALL) {
3513                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3514                    } else {
3515                        final int uid = UserHandle.getUid(userId, susPs.appId);
3516                        killUid(uid, reason);
3517                    }
3518                }
3519            } else if (sb instanceof PackageSetting) {
3520                PackageSetting ps = (PackageSetting) sb;
3521                if (userId == UserHandle.USER_ALL) {
3522                    killApplication(ps.pkg.packageName, ps.appId, reason);
3523                } else {
3524                    final int uid = UserHandle.getUid(userId, ps.appId);
3525                    killUid(uid, reason);
3526                }
3527            }
3528        } finally {
3529            Binder.restoreCallingIdentity(identity);
3530        }
3531    }
3532
3533    private static void killUid(int uid, String reason) {
3534        IActivityManager am = ActivityManagerNative.getDefault();
3535        if (am != null) {
3536            try {
3537                am.killUid(uid, reason);
3538            } catch (RemoteException e) {
3539                /* ignore - same process */
3540            }
3541        }
3542    }
3543
3544    /**
3545     * Compares two sets of signatures. Returns:
3546     * <br />
3547     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3548     * <br />
3549     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3550     * <br />
3551     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3552     * <br />
3553     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3554     * <br />
3555     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3556     */
3557    static int compareSignatures(Signature[] s1, Signature[] s2) {
3558        if (s1 == null) {
3559            return s2 == null
3560                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3561                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3562        }
3563
3564        if (s2 == null) {
3565            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3566        }
3567
3568        if (s1.length != s2.length) {
3569            return PackageManager.SIGNATURE_NO_MATCH;
3570        }
3571
3572        // Since both signature sets are of size 1, we can compare without HashSets.
3573        if (s1.length == 1) {
3574            return s1[0].equals(s2[0]) ?
3575                    PackageManager.SIGNATURE_MATCH :
3576                    PackageManager.SIGNATURE_NO_MATCH;
3577        }
3578
3579        ArraySet<Signature> set1 = new ArraySet<Signature>();
3580        for (Signature sig : s1) {
3581            set1.add(sig);
3582        }
3583        ArraySet<Signature> set2 = new ArraySet<Signature>();
3584        for (Signature sig : s2) {
3585            set2.add(sig);
3586        }
3587        // Make sure s2 contains all signatures in s1.
3588        if (set1.equals(set2)) {
3589            return PackageManager.SIGNATURE_MATCH;
3590        }
3591        return PackageManager.SIGNATURE_NO_MATCH;
3592    }
3593
3594    /**
3595     * If the database version for this type of package (internal storage or
3596     * external storage) is less than the version where package signatures
3597     * were updated, return true.
3598     */
3599    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3600        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3601                DatabaseVersion.SIGNATURE_END_ENTITY))
3602                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3603                        DatabaseVersion.SIGNATURE_END_ENTITY));
3604    }
3605
3606    /**
3607     * Used for backward compatibility to make sure any packages with
3608     * certificate chains get upgraded to the new style. {@code existingSigs}
3609     * will be in the old format (since they were stored on disk from before the
3610     * system upgrade) and {@code scannedSigs} will be in the newer format.
3611     */
3612    private int compareSignaturesCompat(PackageSignatures existingSigs,
3613            PackageParser.Package scannedPkg) {
3614        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3615            return PackageManager.SIGNATURE_NO_MATCH;
3616        }
3617
3618        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3619        for (Signature sig : existingSigs.mSignatures) {
3620            existingSet.add(sig);
3621        }
3622        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3623        for (Signature sig : scannedPkg.mSignatures) {
3624            try {
3625                Signature[] chainSignatures = sig.getChainSignatures();
3626                for (Signature chainSig : chainSignatures) {
3627                    scannedCompatSet.add(chainSig);
3628                }
3629            } catch (CertificateEncodingException e) {
3630                scannedCompatSet.add(sig);
3631            }
3632        }
3633        /*
3634         * Make sure the expanded scanned set contains all signatures in the
3635         * existing one.
3636         */
3637        if (scannedCompatSet.equals(existingSet)) {
3638            // Migrate the old signatures to the new scheme.
3639            existingSigs.assignSignatures(scannedPkg.mSignatures);
3640            // The new KeySets will be re-added later in the scanning process.
3641            synchronized (mPackages) {
3642                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3643            }
3644            return PackageManager.SIGNATURE_MATCH;
3645        }
3646        return PackageManager.SIGNATURE_NO_MATCH;
3647    }
3648
3649    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3650        if (isExternal(scannedPkg)) {
3651            return mSettings.isExternalDatabaseVersionOlderThan(
3652                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3653        } else {
3654            return mSettings.isInternalDatabaseVersionOlderThan(
3655                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3656        }
3657    }
3658
3659    private int compareSignaturesRecover(PackageSignatures existingSigs,
3660            PackageParser.Package scannedPkg) {
3661        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3662            return PackageManager.SIGNATURE_NO_MATCH;
3663        }
3664
3665        String msg = null;
3666        try {
3667            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3668                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3669                        + scannedPkg.packageName);
3670                return PackageManager.SIGNATURE_MATCH;
3671            }
3672        } catch (CertificateException e) {
3673            msg = e.getMessage();
3674        }
3675
3676        logCriticalInfo(Log.INFO,
3677                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3678        return PackageManager.SIGNATURE_NO_MATCH;
3679    }
3680
3681    @Override
3682    public String[] getPackagesForUid(int uid) {
3683        uid = UserHandle.getAppId(uid);
3684        // reader
3685        synchronized (mPackages) {
3686            Object obj = mSettings.getUserIdLPr(uid);
3687            if (obj instanceof SharedUserSetting) {
3688                final SharedUserSetting sus = (SharedUserSetting) obj;
3689                final int N = sus.packages.size();
3690                final String[] res = new String[N];
3691                final Iterator<PackageSetting> it = sus.packages.iterator();
3692                int i = 0;
3693                while (it.hasNext()) {
3694                    res[i++] = it.next().name;
3695                }
3696                return res;
3697            } else if (obj instanceof PackageSetting) {
3698                final PackageSetting ps = (PackageSetting) obj;
3699                return new String[] { ps.name };
3700            }
3701        }
3702        return null;
3703    }
3704
3705    @Override
3706    public String getNameForUid(int uid) {
3707        // reader
3708        synchronized (mPackages) {
3709            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3710            if (obj instanceof SharedUserSetting) {
3711                final SharedUserSetting sus = (SharedUserSetting) obj;
3712                return sus.name + ":" + sus.userId;
3713            } else if (obj instanceof PackageSetting) {
3714                final PackageSetting ps = (PackageSetting) obj;
3715                return ps.name;
3716            }
3717        }
3718        return null;
3719    }
3720
3721    @Override
3722    public int getUidForSharedUser(String sharedUserName) {
3723        if(sharedUserName == null) {
3724            return -1;
3725        }
3726        // reader
3727        synchronized (mPackages) {
3728            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3729            if (suid == null) {
3730                return -1;
3731            }
3732            return suid.userId;
3733        }
3734    }
3735
3736    @Override
3737    public int getFlagsForUid(int uid) {
3738        synchronized (mPackages) {
3739            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3740            if (obj instanceof SharedUserSetting) {
3741                final SharedUserSetting sus = (SharedUserSetting) obj;
3742                return sus.pkgFlags;
3743            } else if (obj instanceof PackageSetting) {
3744                final PackageSetting ps = (PackageSetting) obj;
3745                return ps.pkgFlags;
3746            }
3747        }
3748        return 0;
3749    }
3750
3751    @Override
3752    public int getPrivateFlagsForUid(int uid) {
3753        synchronized (mPackages) {
3754            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3755            if (obj instanceof SharedUserSetting) {
3756                final SharedUserSetting sus = (SharedUserSetting) obj;
3757                return sus.pkgPrivateFlags;
3758            } else if (obj instanceof PackageSetting) {
3759                final PackageSetting ps = (PackageSetting) obj;
3760                return ps.pkgPrivateFlags;
3761            }
3762        }
3763        return 0;
3764    }
3765
3766    @Override
3767    public boolean isUidPrivileged(int uid) {
3768        uid = UserHandle.getAppId(uid);
3769        // reader
3770        synchronized (mPackages) {
3771            Object obj = mSettings.getUserIdLPr(uid);
3772            if (obj instanceof SharedUserSetting) {
3773                final SharedUserSetting sus = (SharedUserSetting) obj;
3774                final Iterator<PackageSetting> it = sus.packages.iterator();
3775                while (it.hasNext()) {
3776                    if (it.next().isPrivileged()) {
3777                        return true;
3778                    }
3779                }
3780            } else if (obj instanceof PackageSetting) {
3781                final PackageSetting ps = (PackageSetting) obj;
3782                return ps.isPrivileged();
3783            }
3784        }
3785        return false;
3786    }
3787
3788    @Override
3789    public String[] getAppOpPermissionPackages(String permissionName) {
3790        synchronized (mPackages) {
3791            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3792            if (pkgs == null) {
3793                return null;
3794            }
3795            return pkgs.toArray(new String[pkgs.size()]);
3796        }
3797    }
3798
3799    @Override
3800    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3801            int flags, int userId) {
3802        if (!sUserManager.exists(userId)) return null;
3803        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3804        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3805        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3806    }
3807
3808    @Override
3809    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3810            IntentFilter filter, int match, ComponentName activity) {
3811        final int userId = UserHandle.getCallingUserId();
3812        if (DEBUG_PREFERRED) {
3813            Log.v(TAG, "setLastChosenActivity intent=" + intent
3814                + " resolvedType=" + resolvedType
3815                + " flags=" + flags
3816                + " filter=" + filter
3817                + " match=" + match
3818                + " activity=" + activity);
3819            filter.dump(new PrintStreamPrinter(System.out), "    ");
3820        }
3821        intent.setComponent(null);
3822        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3823        // Find any earlier preferred or last chosen entries and nuke them
3824        findPreferredActivity(intent, resolvedType,
3825                flags, query, 0, false, true, false, userId);
3826        // Add the new activity as the last chosen for this filter
3827        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3828                "Setting last chosen");
3829    }
3830
3831    @Override
3832    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3833        final int userId = UserHandle.getCallingUserId();
3834        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3835        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3836        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3837                false, false, false, userId);
3838    }
3839
3840    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3841            int flags, List<ResolveInfo> query, int userId) {
3842        if (query != null) {
3843            final int N = query.size();
3844            if (N == 1) {
3845                return query.get(0);
3846            } else if (N > 1) {
3847                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3848                // If there is more than one activity with the same priority,
3849                // then let the user decide between them.
3850                ResolveInfo r0 = query.get(0);
3851                ResolveInfo r1 = query.get(1);
3852                if (DEBUG_INTENT_MATCHING || debug) {
3853                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3854                            + r1.activityInfo.name + "=" + r1.priority);
3855                }
3856                // If the first activity has a higher priority, or a different
3857                // default, then it is always desireable to pick it.
3858                if (r0.priority != r1.priority
3859                        || r0.preferredOrder != r1.preferredOrder
3860                        || r0.isDefault != r1.isDefault) {
3861                    return query.get(0);
3862                }
3863                // If we have saved a preference for a preferred activity for
3864                // this Intent, use that.
3865                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3866                        flags, query, r0.priority, true, false, debug, userId);
3867                if (ri != null) {
3868                    return ri;
3869                }
3870                if (userId != 0) {
3871                    ri = new ResolveInfo(mResolveInfo);
3872                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3873                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3874                            ri.activityInfo.applicationInfo);
3875                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3876                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3877                    return ri;
3878                }
3879                return mResolveInfo;
3880            }
3881        }
3882        return null;
3883    }
3884
3885    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3886            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3887        final int N = query.size();
3888        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3889                .get(userId);
3890        // Get the list of persistent preferred activities that handle the intent
3891        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3892        List<PersistentPreferredActivity> pprefs = ppir != null
3893                ? ppir.queryIntent(intent, resolvedType,
3894                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3895                : null;
3896        if (pprefs != null && pprefs.size() > 0) {
3897            final int M = pprefs.size();
3898            for (int i=0; i<M; i++) {
3899                final PersistentPreferredActivity ppa = pprefs.get(i);
3900                if (DEBUG_PREFERRED || debug) {
3901                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3902                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3903                            + "\n  component=" + ppa.mComponent);
3904                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3905                }
3906                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3907                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3908                if (DEBUG_PREFERRED || debug) {
3909                    Slog.v(TAG, "Found persistent preferred activity:");
3910                    if (ai != null) {
3911                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3912                    } else {
3913                        Slog.v(TAG, "  null");
3914                    }
3915                }
3916                if (ai == null) {
3917                    // This previously registered persistent preferred activity
3918                    // component is no longer known. Ignore it and do NOT remove it.
3919                    continue;
3920                }
3921                for (int j=0; j<N; j++) {
3922                    final ResolveInfo ri = query.get(j);
3923                    if (!ri.activityInfo.applicationInfo.packageName
3924                            .equals(ai.applicationInfo.packageName)) {
3925                        continue;
3926                    }
3927                    if (!ri.activityInfo.name.equals(ai.name)) {
3928                        continue;
3929                    }
3930                    //  Found a persistent preference that can handle the intent.
3931                    if (DEBUG_PREFERRED || debug) {
3932                        Slog.v(TAG, "Returning persistent preferred activity: " +
3933                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3934                    }
3935                    return ri;
3936                }
3937            }
3938        }
3939        return null;
3940    }
3941
3942    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3943            List<ResolveInfo> query, int priority, boolean always,
3944            boolean removeMatches, boolean debug, int userId) {
3945        if (!sUserManager.exists(userId)) return null;
3946        // writer
3947        synchronized (mPackages) {
3948            if (intent.getSelector() != null) {
3949                intent = intent.getSelector();
3950            }
3951            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3952
3953            // Try to find a matching persistent preferred activity.
3954            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3955                    debug, userId);
3956
3957            // If a persistent preferred activity matched, use it.
3958            if (pri != null) {
3959                return pri;
3960            }
3961
3962            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3963            // Get the list of preferred activities that handle the intent
3964            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3965            List<PreferredActivity> prefs = pir != null
3966                    ? pir.queryIntent(intent, resolvedType,
3967                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3968                    : null;
3969            if (prefs != null && prefs.size() > 0) {
3970                boolean changed = false;
3971                try {
3972                    // First figure out how good the original match set is.
3973                    // We will only allow preferred activities that came
3974                    // from the same match quality.
3975                    int match = 0;
3976
3977                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3978
3979                    final int N = query.size();
3980                    for (int j=0; j<N; j++) {
3981                        final ResolveInfo ri = query.get(j);
3982                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3983                                + ": 0x" + Integer.toHexString(match));
3984                        if (ri.match > match) {
3985                            match = ri.match;
3986                        }
3987                    }
3988
3989                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3990                            + Integer.toHexString(match));
3991
3992                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3993                    final int M = prefs.size();
3994                    for (int i=0; i<M; i++) {
3995                        final PreferredActivity pa = prefs.get(i);
3996                        if (DEBUG_PREFERRED || debug) {
3997                            Slog.v(TAG, "Checking PreferredActivity ds="
3998                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3999                                    + "\n  component=" + pa.mPref.mComponent);
4000                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4001                        }
4002                        if (pa.mPref.mMatch != match) {
4003                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4004                                    + Integer.toHexString(pa.mPref.mMatch));
4005                            continue;
4006                        }
4007                        // If it's not an "always" type preferred activity and that's what we're
4008                        // looking for, skip it.
4009                        if (always && !pa.mPref.mAlways) {
4010                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4011                            continue;
4012                        }
4013                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4014                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4015                        if (DEBUG_PREFERRED || debug) {
4016                            Slog.v(TAG, "Found preferred activity:");
4017                            if (ai != null) {
4018                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4019                            } else {
4020                                Slog.v(TAG, "  null");
4021                            }
4022                        }
4023                        if (ai == null) {
4024                            // This previously registered preferred activity
4025                            // component is no longer known.  Most likely an update
4026                            // to the app was installed and in the new version this
4027                            // component no longer exists.  Clean it up by removing
4028                            // it from the preferred activities list, and skip it.
4029                            Slog.w(TAG, "Removing dangling preferred activity: "
4030                                    + pa.mPref.mComponent);
4031                            pir.removeFilter(pa);
4032                            changed = true;
4033                            continue;
4034                        }
4035                        for (int j=0; j<N; j++) {
4036                            final ResolveInfo ri = query.get(j);
4037                            if (!ri.activityInfo.applicationInfo.packageName
4038                                    .equals(ai.applicationInfo.packageName)) {
4039                                continue;
4040                            }
4041                            if (!ri.activityInfo.name.equals(ai.name)) {
4042                                continue;
4043                            }
4044
4045                            if (removeMatches) {
4046                                pir.removeFilter(pa);
4047                                changed = true;
4048                                if (DEBUG_PREFERRED) {
4049                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4050                                }
4051                                break;
4052                            }
4053
4054                            // Okay we found a previously set preferred or last chosen app.
4055                            // If the result set is different from when this
4056                            // was created, we need to clear it and re-ask the
4057                            // user their preference, if we're looking for an "always" type entry.
4058                            if (always && !pa.mPref.sameSet(query)) {
4059                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4060                                        + intent + " type " + resolvedType);
4061                                if (DEBUG_PREFERRED) {
4062                                    Slog.v(TAG, "Removing preferred activity since set changed "
4063                                            + pa.mPref.mComponent);
4064                                }
4065                                pir.removeFilter(pa);
4066                                // Re-add the filter as a "last chosen" entry (!always)
4067                                PreferredActivity lastChosen = new PreferredActivity(
4068                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4069                                pir.addFilter(lastChosen);
4070                                changed = true;
4071                                return null;
4072                            }
4073
4074                            // Yay! Either the set matched or we're looking for the last chosen
4075                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4076                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4077                            return ri;
4078                        }
4079                    }
4080                } finally {
4081                    if (changed) {
4082                        if (DEBUG_PREFERRED) {
4083                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4084                        }
4085                        scheduleWritePackageRestrictionsLocked(userId);
4086                    }
4087                }
4088            }
4089        }
4090        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4091        return null;
4092    }
4093
4094    /*
4095     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4096     */
4097    @Override
4098    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4099            int targetUserId) {
4100        mContext.enforceCallingOrSelfPermission(
4101                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4102        List<CrossProfileIntentFilter> matches =
4103                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4104        if (matches != null) {
4105            int size = matches.size();
4106            for (int i = 0; i < size; i++) {
4107                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4108            }
4109        }
4110        return false;
4111    }
4112
4113    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4114            String resolvedType, int userId) {
4115        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4116        if (resolver != null) {
4117            return resolver.queryIntent(intent, resolvedType, false, userId);
4118        }
4119        return null;
4120    }
4121
4122    @Override
4123    public List<ResolveInfo> queryIntentActivities(Intent intent,
4124            String resolvedType, int flags, int userId) {
4125        if (!sUserManager.exists(userId)) return Collections.emptyList();
4126        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4127        ComponentName comp = intent.getComponent();
4128        if (comp == null) {
4129            if (intent.getSelector() != null) {
4130                intent = intent.getSelector();
4131                comp = intent.getComponent();
4132            }
4133        }
4134
4135        if (comp != null) {
4136            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4137            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4138            if (ai != null) {
4139                final ResolveInfo ri = new ResolveInfo();
4140                ri.activityInfo = ai;
4141                list.add(ri);
4142            }
4143            return list;
4144        }
4145
4146        // reader
4147        synchronized (mPackages) {
4148            final String pkgName = intent.getPackage();
4149            if (pkgName == null) {
4150                List<CrossProfileIntentFilter> matchingFilters =
4151                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4152                // Check for results that need to skip the current profile.
4153                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4154                        resolvedType, flags, userId);
4155                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
4156                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4157                    result.add(resolveInfo);
4158                    return filterIfNotPrimaryUser(result, userId);
4159                }
4160
4161                // Check for results in the current profile.
4162                List<ResolveInfo> result = mActivities.queryIntent(
4163                        intent, resolvedType, flags, userId);
4164
4165                // Check for cross profile results.
4166                resolveInfo = queryCrossProfileIntents(
4167                        matchingFilters, intent, resolvedType, flags, userId);
4168                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
4169                    result.add(resolveInfo);
4170                    Collections.sort(result, mResolvePrioritySorter);
4171                }
4172                result = filterIfNotPrimaryUser(result, userId);
4173                if (result.size() > 1 && hasWebURI(intent)) {
4174                    return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result);
4175                }
4176                return result;
4177            }
4178            final PackageParser.Package pkg = mPackages.get(pkgName);
4179            if (pkg != null) {
4180                return filterIfNotPrimaryUser(
4181                        mActivities.queryIntentForPackage(
4182                                intent, resolvedType, flags, pkg.activities, userId),
4183                        userId);
4184            }
4185            return new ArrayList<ResolveInfo>();
4186        }
4187    }
4188
4189    private boolean isUserEnabled(int userId) {
4190        long callingId = Binder.clearCallingIdentity();
4191        try {
4192            UserInfo userInfo = sUserManager.getUserInfo(userId);
4193            return userInfo != null && userInfo.isEnabled();
4194        } finally {
4195            Binder.restoreCallingIdentity(callingId);
4196        }
4197    }
4198
4199    /**
4200     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4201     *
4202     * @return filtered list
4203     */
4204    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4205        if (userId == UserHandle.USER_OWNER) {
4206            return resolveInfos;
4207        }
4208        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4209            ResolveInfo info = resolveInfos.get(i);
4210            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4211                resolveInfos.remove(i);
4212            }
4213        }
4214        return resolveInfos;
4215    }
4216
4217    private static boolean hasWebURI(Intent intent) {
4218        if (intent.getData() == null) {
4219            return false;
4220        }
4221        final String scheme = intent.getScheme();
4222        if (TextUtils.isEmpty(scheme)) {
4223            return false;
4224        }
4225        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4226    }
4227
4228    private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr(
4229            int flags, List<ResolveInfo> candidates) {
4230        if (DEBUG_PREFERRED) {
4231            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4232                    candidates.size());
4233        }
4234
4235        final int userId = UserHandle.getCallingUserId();
4236        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4237        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4238        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4239        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4240        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4241
4242        synchronized (mPackages) {
4243            final int count = candidates.size();
4244            // First, try to use the domain prefered App. Partition the candidates into four lists:
4245            // one for the final results, one for the "do not use ever", one for "undefined status"
4246            // and finally one for "Browser App type".
4247            for (int n=0; n<count; n++) {
4248                ResolveInfo info = candidates.get(n);
4249                String packageName = info.activityInfo.packageName;
4250                PackageSetting ps = mSettings.mPackages.get(packageName);
4251                if (ps != null) {
4252                    // Add to the special match all list (Browser use case)
4253                    if (info.handleAllWebDataURI) {
4254                        matchAllList.add(info);
4255                        continue;
4256                    }
4257                    // Try to get the status from User settings first
4258                    int status = getDomainVerificationStatusLPr(ps, userId);
4259                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4260                        alwaysList.add(info);
4261                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4262                        neverList.add(info);
4263                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4264                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4265                        undefinedList.add(info);
4266                    }
4267                }
4268            }
4269            // First try to add the "always" if there is any
4270            if (alwaysList.size() > 0) {
4271                result.addAll(alwaysList);
4272            } else {
4273                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4274                result.addAll(undefinedList);
4275                // Also add Browsers (all of them or only the default one)
4276                if ((flags & MATCH_ALL) != 0) {
4277                    result.addAll(matchAllList);
4278                } else {
4279                    // Try to add the Default Browser if we can
4280                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4281                            UserHandle.myUserId());
4282                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4283                        boolean defaultBrowserFound = false;
4284                        final int browserCount = matchAllList.size();
4285                        for (int n=0; n<browserCount; n++) {
4286                            ResolveInfo browser = matchAllList.get(n);
4287                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4288                                result.add(browser);
4289                                defaultBrowserFound = true;
4290                                break;
4291                            }
4292                        }
4293                        if (!defaultBrowserFound) {
4294                            result.addAll(matchAllList);
4295                        }
4296                    } else {
4297                        result.addAll(matchAllList);
4298                    }
4299                }
4300
4301                // If there is nothing selected, add all candidates and remove the ones that the User
4302                // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4303                if (result.size() == 0) {
4304                    result.addAll(candidates);
4305                    result.removeAll(neverList);
4306                }
4307            }
4308        }
4309        if (DEBUG_PREFERRED) {
4310            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4311                    result.size());
4312        }
4313        return result;
4314    }
4315
4316    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4317        int status = ps.getDomainVerificationStatusForUser(userId);
4318        // if none available, get the master status
4319        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4320            if (ps.getIntentFilterVerificationInfo() != null) {
4321                status = ps.getIntentFilterVerificationInfo().getStatus();
4322            }
4323        }
4324        return status;
4325    }
4326
4327    private ResolveInfo querySkipCurrentProfileIntents(
4328            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4329            int flags, int sourceUserId) {
4330        if (matchingFilters != null) {
4331            int size = matchingFilters.size();
4332            for (int i = 0; i < size; i ++) {
4333                CrossProfileIntentFilter filter = matchingFilters.get(i);
4334                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4335                    // Checking if there are activities in the target user that can handle the
4336                    // intent.
4337                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4338                            flags, sourceUserId);
4339                    if (resolveInfo != null) {
4340                        return resolveInfo;
4341                    }
4342                }
4343            }
4344        }
4345        return null;
4346    }
4347
4348    // Return matching ResolveInfo if any for skip current profile intent filters.
4349    private ResolveInfo queryCrossProfileIntents(
4350            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4351            int flags, int sourceUserId) {
4352        if (matchingFilters != null) {
4353            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4354            // match the same intent. For performance reasons, it is better not to
4355            // run queryIntent twice for the same userId
4356            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4357            int size = matchingFilters.size();
4358            for (int i = 0; i < size; i++) {
4359                CrossProfileIntentFilter filter = matchingFilters.get(i);
4360                int targetUserId = filter.getTargetUserId();
4361                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4362                        && !alreadyTriedUserIds.get(targetUserId)) {
4363                    // Checking if there are activities in the target user that can handle the
4364                    // intent.
4365                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4366                            flags, sourceUserId);
4367                    if (resolveInfo != null) return resolveInfo;
4368                    alreadyTriedUserIds.put(targetUserId, true);
4369                }
4370            }
4371        }
4372        return null;
4373    }
4374
4375    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4376            String resolvedType, int flags, int sourceUserId) {
4377        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4378                resolvedType, flags, filter.getTargetUserId());
4379        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4380            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4381        }
4382        return null;
4383    }
4384
4385    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4386            int sourceUserId, int targetUserId) {
4387        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4388        String className;
4389        if (targetUserId == UserHandle.USER_OWNER) {
4390            className = FORWARD_INTENT_TO_USER_OWNER;
4391        } else {
4392            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4393        }
4394        ComponentName forwardingActivityComponentName = new ComponentName(
4395                mAndroidApplication.packageName, className);
4396        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4397                sourceUserId);
4398        if (targetUserId == UserHandle.USER_OWNER) {
4399            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4400            forwardingResolveInfo.noResourceId = true;
4401        }
4402        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4403        forwardingResolveInfo.priority = 0;
4404        forwardingResolveInfo.preferredOrder = 0;
4405        forwardingResolveInfo.match = 0;
4406        forwardingResolveInfo.isDefault = true;
4407        forwardingResolveInfo.filter = filter;
4408        forwardingResolveInfo.targetUserId = targetUserId;
4409        return forwardingResolveInfo;
4410    }
4411
4412    @Override
4413    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4414            Intent[] specifics, String[] specificTypes, Intent intent,
4415            String resolvedType, int flags, int userId) {
4416        if (!sUserManager.exists(userId)) return Collections.emptyList();
4417        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4418                false, "query intent activity options");
4419        final String resultsAction = intent.getAction();
4420
4421        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4422                | PackageManager.GET_RESOLVED_FILTER, userId);
4423
4424        if (DEBUG_INTENT_MATCHING) {
4425            Log.v(TAG, "Query " + intent + ": " + results);
4426        }
4427
4428        int specificsPos = 0;
4429        int N;
4430
4431        // todo: note that the algorithm used here is O(N^2).  This
4432        // isn't a problem in our current environment, but if we start running
4433        // into situations where we have more than 5 or 10 matches then this
4434        // should probably be changed to something smarter...
4435
4436        // First we go through and resolve each of the specific items
4437        // that were supplied, taking care of removing any corresponding
4438        // duplicate items in the generic resolve list.
4439        if (specifics != null) {
4440            for (int i=0; i<specifics.length; i++) {
4441                final Intent sintent = specifics[i];
4442                if (sintent == null) {
4443                    continue;
4444                }
4445
4446                if (DEBUG_INTENT_MATCHING) {
4447                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4448                }
4449
4450                String action = sintent.getAction();
4451                if (resultsAction != null && resultsAction.equals(action)) {
4452                    // If this action was explicitly requested, then don't
4453                    // remove things that have it.
4454                    action = null;
4455                }
4456
4457                ResolveInfo ri = null;
4458                ActivityInfo ai = null;
4459
4460                ComponentName comp = sintent.getComponent();
4461                if (comp == null) {
4462                    ri = resolveIntent(
4463                        sintent,
4464                        specificTypes != null ? specificTypes[i] : null,
4465                            flags, userId);
4466                    if (ri == null) {
4467                        continue;
4468                    }
4469                    if (ri == mResolveInfo) {
4470                        // ACK!  Must do something better with this.
4471                    }
4472                    ai = ri.activityInfo;
4473                    comp = new ComponentName(ai.applicationInfo.packageName,
4474                            ai.name);
4475                } else {
4476                    ai = getActivityInfo(comp, flags, userId);
4477                    if (ai == null) {
4478                        continue;
4479                    }
4480                }
4481
4482                // Look for any generic query activities that are duplicates
4483                // of this specific one, and remove them from the results.
4484                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4485                N = results.size();
4486                int j;
4487                for (j=specificsPos; j<N; j++) {
4488                    ResolveInfo sri = results.get(j);
4489                    if ((sri.activityInfo.name.equals(comp.getClassName())
4490                            && sri.activityInfo.applicationInfo.packageName.equals(
4491                                    comp.getPackageName()))
4492                        || (action != null && sri.filter.matchAction(action))) {
4493                        results.remove(j);
4494                        if (DEBUG_INTENT_MATCHING) Log.v(
4495                            TAG, "Removing duplicate item from " + j
4496                            + " due to specific " + specificsPos);
4497                        if (ri == null) {
4498                            ri = sri;
4499                        }
4500                        j--;
4501                        N--;
4502                    }
4503                }
4504
4505                // Add this specific item to its proper place.
4506                if (ri == null) {
4507                    ri = new ResolveInfo();
4508                    ri.activityInfo = ai;
4509                }
4510                results.add(specificsPos, ri);
4511                ri.specificIndex = i;
4512                specificsPos++;
4513            }
4514        }
4515
4516        // Now we go through the remaining generic results and remove any
4517        // duplicate actions that are found here.
4518        N = results.size();
4519        for (int i=specificsPos; i<N-1; i++) {
4520            final ResolveInfo rii = results.get(i);
4521            if (rii.filter == null) {
4522                continue;
4523            }
4524
4525            // Iterate over all of the actions of this result's intent
4526            // filter...  typically this should be just one.
4527            final Iterator<String> it = rii.filter.actionsIterator();
4528            if (it == null) {
4529                continue;
4530            }
4531            while (it.hasNext()) {
4532                final String action = it.next();
4533                if (resultsAction != null && resultsAction.equals(action)) {
4534                    // If this action was explicitly requested, then don't
4535                    // remove things that have it.
4536                    continue;
4537                }
4538                for (int j=i+1; j<N; j++) {
4539                    final ResolveInfo rij = results.get(j);
4540                    if (rij.filter != null && rij.filter.hasAction(action)) {
4541                        results.remove(j);
4542                        if (DEBUG_INTENT_MATCHING) Log.v(
4543                            TAG, "Removing duplicate item from " + j
4544                            + " due to action " + action + " at " + i);
4545                        j--;
4546                        N--;
4547                    }
4548                }
4549            }
4550
4551            // If the caller didn't request filter information, drop it now
4552            // so we don't have to marshall/unmarshall it.
4553            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4554                rii.filter = null;
4555            }
4556        }
4557
4558        // Filter out the caller activity if so requested.
4559        if (caller != null) {
4560            N = results.size();
4561            for (int i=0; i<N; i++) {
4562                ActivityInfo ainfo = results.get(i).activityInfo;
4563                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4564                        && caller.getClassName().equals(ainfo.name)) {
4565                    results.remove(i);
4566                    break;
4567                }
4568            }
4569        }
4570
4571        // If the caller didn't request filter information,
4572        // drop them now so we don't have to
4573        // marshall/unmarshall it.
4574        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4575            N = results.size();
4576            for (int i=0; i<N; i++) {
4577                results.get(i).filter = null;
4578            }
4579        }
4580
4581        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4582        return results;
4583    }
4584
4585    @Override
4586    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4587            int userId) {
4588        if (!sUserManager.exists(userId)) return Collections.emptyList();
4589        ComponentName comp = intent.getComponent();
4590        if (comp == null) {
4591            if (intent.getSelector() != null) {
4592                intent = intent.getSelector();
4593                comp = intent.getComponent();
4594            }
4595        }
4596        if (comp != null) {
4597            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4598            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4599            if (ai != null) {
4600                ResolveInfo ri = new ResolveInfo();
4601                ri.activityInfo = ai;
4602                list.add(ri);
4603            }
4604            return list;
4605        }
4606
4607        // reader
4608        synchronized (mPackages) {
4609            String pkgName = intent.getPackage();
4610            if (pkgName == null) {
4611                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4612            }
4613            final PackageParser.Package pkg = mPackages.get(pkgName);
4614            if (pkg != null) {
4615                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4616                        userId);
4617            }
4618            return null;
4619        }
4620    }
4621
4622    @Override
4623    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4624        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4625        if (!sUserManager.exists(userId)) return null;
4626        if (query != null) {
4627            if (query.size() >= 1) {
4628                // If there is more than one service with the same priority,
4629                // just arbitrarily pick the first one.
4630                return query.get(0);
4631            }
4632        }
4633        return null;
4634    }
4635
4636    @Override
4637    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4638            int userId) {
4639        if (!sUserManager.exists(userId)) return Collections.emptyList();
4640        ComponentName comp = intent.getComponent();
4641        if (comp == null) {
4642            if (intent.getSelector() != null) {
4643                intent = intent.getSelector();
4644                comp = intent.getComponent();
4645            }
4646        }
4647        if (comp != null) {
4648            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4649            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4650            if (si != null) {
4651                final ResolveInfo ri = new ResolveInfo();
4652                ri.serviceInfo = si;
4653                list.add(ri);
4654            }
4655            return list;
4656        }
4657
4658        // reader
4659        synchronized (mPackages) {
4660            String pkgName = intent.getPackage();
4661            if (pkgName == null) {
4662                return mServices.queryIntent(intent, resolvedType, flags, userId);
4663            }
4664            final PackageParser.Package pkg = mPackages.get(pkgName);
4665            if (pkg != null) {
4666                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4667                        userId);
4668            }
4669            return null;
4670        }
4671    }
4672
4673    @Override
4674    public List<ResolveInfo> queryIntentContentProviders(
4675            Intent intent, String resolvedType, int flags, int userId) {
4676        if (!sUserManager.exists(userId)) return Collections.emptyList();
4677        ComponentName comp = intent.getComponent();
4678        if (comp == null) {
4679            if (intent.getSelector() != null) {
4680                intent = intent.getSelector();
4681                comp = intent.getComponent();
4682            }
4683        }
4684        if (comp != null) {
4685            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4686            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4687            if (pi != null) {
4688                final ResolveInfo ri = new ResolveInfo();
4689                ri.providerInfo = pi;
4690                list.add(ri);
4691            }
4692            return list;
4693        }
4694
4695        // reader
4696        synchronized (mPackages) {
4697            String pkgName = intent.getPackage();
4698            if (pkgName == null) {
4699                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4700            }
4701            final PackageParser.Package pkg = mPackages.get(pkgName);
4702            if (pkg != null) {
4703                return mProviders.queryIntentForPackage(
4704                        intent, resolvedType, flags, pkg.providers, userId);
4705            }
4706            return null;
4707        }
4708    }
4709
4710    @Override
4711    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4712        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4713
4714        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4715
4716        // writer
4717        synchronized (mPackages) {
4718            ArrayList<PackageInfo> list;
4719            if (listUninstalled) {
4720                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4721                for (PackageSetting ps : mSettings.mPackages.values()) {
4722                    PackageInfo pi;
4723                    if (ps.pkg != null) {
4724                        pi = generatePackageInfo(ps.pkg, flags, userId);
4725                    } else {
4726                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4727                    }
4728                    if (pi != null) {
4729                        list.add(pi);
4730                    }
4731                }
4732            } else {
4733                list = new ArrayList<PackageInfo>(mPackages.size());
4734                for (PackageParser.Package p : mPackages.values()) {
4735                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4736                    if (pi != null) {
4737                        list.add(pi);
4738                    }
4739                }
4740            }
4741
4742            return new ParceledListSlice<PackageInfo>(list);
4743        }
4744    }
4745
4746    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4747            String[] permissions, boolean[] tmp, int flags, int userId) {
4748        int numMatch = 0;
4749        final PermissionsState permissionsState = ps.getPermissionsState();
4750        for (int i=0; i<permissions.length; i++) {
4751            final String permission = permissions[i];
4752            if (permissionsState.hasPermission(permission, userId)) {
4753                tmp[i] = true;
4754                numMatch++;
4755            } else {
4756                tmp[i] = false;
4757            }
4758        }
4759        if (numMatch == 0) {
4760            return;
4761        }
4762        PackageInfo pi;
4763        if (ps.pkg != null) {
4764            pi = generatePackageInfo(ps.pkg, flags, userId);
4765        } else {
4766            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4767        }
4768        // The above might return null in cases of uninstalled apps or install-state
4769        // skew across users/profiles.
4770        if (pi != null) {
4771            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4772                if (numMatch == permissions.length) {
4773                    pi.requestedPermissions = permissions;
4774                } else {
4775                    pi.requestedPermissions = new String[numMatch];
4776                    numMatch = 0;
4777                    for (int i=0; i<permissions.length; i++) {
4778                        if (tmp[i]) {
4779                            pi.requestedPermissions[numMatch] = permissions[i];
4780                            numMatch++;
4781                        }
4782                    }
4783                }
4784            }
4785            list.add(pi);
4786        }
4787    }
4788
4789    @Override
4790    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4791            String[] permissions, int flags, int userId) {
4792        if (!sUserManager.exists(userId)) return null;
4793        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4794
4795        // writer
4796        synchronized (mPackages) {
4797            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4798            boolean[] tmpBools = new boolean[permissions.length];
4799            if (listUninstalled) {
4800                for (PackageSetting ps : mSettings.mPackages.values()) {
4801                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4802                }
4803            } else {
4804                for (PackageParser.Package pkg : mPackages.values()) {
4805                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4806                    if (ps != null) {
4807                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4808                                userId);
4809                    }
4810                }
4811            }
4812
4813            return new ParceledListSlice<PackageInfo>(list);
4814        }
4815    }
4816
4817    @Override
4818    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4819        if (!sUserManager.exists(userId)) return null;
4820        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4821
4822        // writer
4823        synchronized (mPackages) {
4824            ArrayList<ApplicationInfo> list;
4825            if (listUninstalled) {
4826                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4827                for (PackageSetting ps : mSettings.mPackages.values()) {
4828                    ApplicationInfo ai;
4829                    if (ps.pkg != null) {
4830                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4831                                ps.readUserState(userId), userId);
4832                    } else {
4833                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4834                    }
4835                    if (ai != null) {
4836                        list.add(ai);
4837                    }
4838                }
4839            } else {
4840                list = new ArrayList<ApplicationInfo>(mPackages.size());
4841                for (PackageParser.Package p : mPackages.values()) {
4842                    if (p.mExtras != null) {
4843                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4844                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4845                        if (ai != null) {
4846                            list.add(ai);
4847                        }
4848                    }
4849                }
4850            }
4851
4852            return new ParceledListSlice<ApplicationInfo>(list);
4853        }
4854    }
4855
4856    public List<ApplicationInfo> getPersistentApplications(int flags) {
4857        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4858
4859        // reader
4860        synchronized (mPackages) {
4861            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4862            final int userId = UserHandle.getCallingUserId();
4863            while (i.hasNext()) {
4864                final PackageParser.Package p = i.next();
4865                if (p.applicationInfo != null
4866                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4867                        && (!mSafeMode || isSystemApp(p))) {
4868                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4869                    if (ps != null) {
4870                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4871                                ps.readUserState(userId), userId);
4872                        if (ai != null) {
4873                            finalList.add(ai);
4874                        }
4875                    }
4876                }
4877            }
4878        }
4879
4880        return finalList;
4881    }
4882
4883    @Override
4884    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4885        if (!sUserManager.exists(userId)) return null;
4886        // reader
4887        synchronized (mPackages) {
4888            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4889            PackageSetting ps = provider != null
4890                    ? mSettings.mPackages.get(provider.owner.packageName)
4891                    : null;
4892            return ps != null
4893                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4894                    && (!mSafeMode || (provider.info.applicationInfo.flags
4895                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4896                    ? PackageParser.generateProviderInfo(provider, flags,
4897                            ps.readUserState(userId), userId)
4898                    : null;
4899        }
4900    }
4901
4902    /**
4903     * @deprecated
4904     */
4905    @Deprecated
4906    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4907        // reader
4908        synchronized (mPackages) {
4909            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4910                    .entrySet().iterator();
4911            final int userId = UserHandle.getCallingUserId();
4912            while (i.hasNext()) {
4913                Map.Entry<String, PackageParser.Provider> entry = i.next();
4914                PackageParser.Provider p = entry.getValue();
4915                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4916
4917                if (ps != null && p.syncable
4918                        && (!mSafeMode || (p.info.applicationInfo.flags
4919                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4920                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4921                            ps.readUserState(userId), userId);
4922                    if (info != null) {
4923                        outNames.add(entry.getKey());
4924                        outInfo.add(info);
4925                    }
4926                }
4927            }
4928        }
4929    }
4930
4931    @Override
4932    public List<ProviderInfo> queryContentProviders(String processName,
4933            int uid, int flags) {
4934        ArrayList<ProviderInfo> finalList = null;
4935        // reader
4936        synchronized (mPackages) {
4937            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4938            final int userId = processName != null ?
4939                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4940            while (i.hasNext()) {
4941                final PackageParser.Provider p = i.next();
4942                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4943                if (ps != null && p.info.authority != null
4944                        && (processName == null
4945                                || (p.info.processName.equals(processName)
4946                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4947                        && mSettings.isEnabledLPr(p.info, flags, userId)
4948                        && (!mSafeMode
4949                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4950                    if (finalList == null) {
4951                        finalList = new ArrayList<ProviderInfo>(3);
4952                    }
4953                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4954                            ps.readUserState(userId), userId);
4955                    if (info != null) {
4956                        finalList.add(info);
4957                    }
4958                }
4959            }
4960        }
4961
4962        if (finalList != null) {
4963            Collections.sort(finalList, mProviderInitOrderSorter);
4964        }
4965
4966        return finalList;
4967    }
4968
4969    @Override
4970    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4971            int flags) {
4972        // reader
4973        synchronized (mPackages) {
4974            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4975            return PackageParser.generateInstrumentationInfo(i, flags);
4976        }
4977    }
4978
4979    @Override
4980    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4981            int flags) {
4982        ArrayList<InstrumentationInfo> finalList =
4983            new ArrayList<InstrumentationInfo>();
4984
4985        // reader
4986        synchronized (mPackages) {
4987            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4988            while (i.hasNext()) {
4989                final PackageParser.Instrumentation p = i.next();
4990                if (targetPackage == null
4991                        || targetPackage.equals(p.info.targetPackage)) {
4992                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4993                            flags);
4994                    if (ii != null) {
4995                        finalList.add(ii);
4996                    }
4997                }
4998            }
4999        }
5000
5001        return finalList;
5002    }
5003
5004    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5005        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5006        if (overlays == null) {
5007            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5008            return;
5009        }
5010        for (PackageParser.Package opkg : overlays.values()) {
5011            // Not much to do if idmap fails: we already logged the error
5012            // and we certainly don't want to abort installation of pkg simply
5013            // because an overlay didn't fit properly. For these reasons,
5014            // ignore the return value of createIdmapForPackagePairLI.
5015            createIdmapForPackagePairLI(pkg, opkg);
5016        }
5017    }
5018
5019    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5020            PackageParser.Package opkg) {
5021        if (!opkg.mTrustedOverlay) {
5022            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5023                    opkg.baseCodePath + ": overlay not trusted");
5024            return false;
5025        }
5026        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5027        if (overlaySet == null) {
5028            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5029                    opkg.baseCodePath + " but target package has no known overlays");
5030            return false;
5031        }
5032        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5033        // TODO: generate idmap for split APKs
5034        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5035            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5036                    + opkg.baseCodePath);
5037            return false;
5038        }
5039        PackageParser.Package[] overlayArray =
5040            overlaySet.values().toArray(new PackageParser.Package[0]);
5041        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5042            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5043                return p1.mOverlayPriority - p2.mOverlayPriority;
5044            }
5045        };
5046        Arrays.sort(overlayArray, cmp);
5047
5048        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5049        int i = 0;
5050        for (PackageParser.Package p : overlayArray) {
5051            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5052        }
5053        return true;
5054    }
5055
5056    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5057        final File[] files = dir.listFiles();
5058        if (ArrayUtils.isEmpty(files)) {
5059            Log.d(TAG, "No files in app dir " + dir);
5060            return;
5061        }
5062
5063        if (DEBUG_PACKAGE_SCANNING) {
5064            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5065                    + " flags=0x" + Integer.toHexString(parseFlags));
5066        }
5067
5068        for (File file : files) {
5069            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5070                    && !PackageInstallerService.isStageName(file.getName());
5071            if (!isPackage) {
5072                // Ignore entries which are not packages
5073                continue;
5074            }
5075            try {
5076                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5077                        scanFlags, currentTime, null);
5078            } catch (PackageManagerException e) {
5079                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5080
5081                // Delete invalid userdata apps
5082                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5083                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5084                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5085                    if (file.isDirectory()) {
5086                        mInstaller.rmPackageDir(file.getAbsolutePath());
5087                    } else {
5088                        file.delete();
5089                    }
5090                }
5091            }
5092        }
5093    }
5094
5095    private static File getSettingsProblemFile() {
5096        File dataDir = Environment.getDataDirectory();
5097        File systemDir = new File(dataDir, "system");
5098        File fname = new File(systemDir, "uiderrors.txt");
5099        return fname;
5100    }
5101
5102    static void reportSettingsProblem(int priority, String msg) {
5103        logCriticalInfo(priority, msg);
5104    }
5105
5106    static void logCriticalInfo(int priority, String msg) {
5107        Slog.println(priority, TAG, msg);
5108        EventLogTags.writePmCriticalInfo(msg);
5109        try {
5110            File fname = getSettingsProblemFile();
5111            FileOutputStream out = new FileOutputStream(fname, true);
5112            PrintWriter pw = new FastPrintWriter(out);
5113            SimpleDateFormat formatter = new SimpleDateFormat();
5114            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5115            pw.println(dateString + ": " + msg);
5116            pw.close();
5117            FileUtils.setPermissions(
5118                    fname.toString(),
5119                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5120                    -1, -1);
5121        } catch (java.io.IOException e) {
5122        }
5123    }
5124
5125    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5126            PackageParser.Package pkg, File srcFile, int parseFlags)
5127            throws PackageManagerException {
5128        if (ps != null
5129                && ps.codePath.equals(srcFile)
5130                && ps.timeStamp == srcFile.lastModified()
5131                && !isCompatSignatureUpdateNeeded(pkg)
5132                && !isRecoverSignatureUpdateNeeded(pkg)) {
5133            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5134            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5135            ArraySet<PublicKey> signingKs;
5136            synchronized (mPackages) {
5137                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5138            }
5139            if (ps.signatures.mSignatures != null
5140                    && ps.signatures.mSignatures.length != 0
5141                    && signingKs != null) {
5142                // Optimization: reuse the existing cached certificates
5143                // if the package appears to be unchanged.
5144                pkg.mSignatures = ps.signatures.mSignatures;
5145                pkg.mSigningKeys = signingKs;
5146                return;
5147            }
5148
5149            Slog.w(TAG, "PackageSetting for " + ps.name
5150                    + " is missing signatures.  Collecting certs again to recover them.");
5151        } else {
5152            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5153        }
5154
5155        try {
5156            pp.collectCertificates(pkg, parseFlags);
5157            pp.collectManifestDigest(pkg);
5158        } catch (PackageParserException e) {
5159            throw PackageManagerException.from(e);
5160        }
5161    }
5162
5163    /*
5164     *  Scan a package and return the newly parsed package.
5165     *  Returns null in case of errors and the error code is stored in mLastScanError
5166     */
5167    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5168            long currentTime, UserHandle user) throws PackageManagerException {
5169        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5170        parseFlags |= mDefParseFlags;
5171        PackageParser pp = new PackageParser();
5172        pp.setSeparateProcesses(mSeparateProcesses);
5173        pp.setOnlyCoreApps(mOnlyCore);
5174        pp.setDisplayMetrics(mMetrics);
5175
5176        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5177            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5178        }
5179
5180        final PackageParser.Package pkg;
5181        try {
5182            pkg = pp.parsePackage(scanFile, parseFlags);
5183        } catch (PackageParserException e) {
5184            throw PackageManagerException.from(e);
5185        }
5186
5187        PackageSetting ps = null;
5188        PackageSetting updatedPkg;
5189        // reader
5190        synchronized (mPackages) {
5191            // Look to see if we already know about this package.
5192            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5193            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5194                // This package has been renamed to its original name.  Let's
5195                // use that.
5196                ps = mSettings.peekPackageLPr(oldName);
5197            }
5198            // If there was no original package, see one for the real package name.
5199            if (ps == null) {
5200                ps = mSettings.peekPackageLPr(pkg.packageName);
5201            }
5202            // Check to see if this package could be hiding/updating a system
5203            // package.  Must look for it either under the original or real
5204            // package name depending on our state.
5205            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5206            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5207        }
5208        boolean updatedPkgBetter = false;
5209        // First check if this is a system package that may involve an update
5210        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5211            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5212            // it needs to drop FLAG_PRIVILEGED.
5213            if (locationIsPrivileged(scanFile)) {
5214                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5215            } else {
5216                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5217            }
5218
5219            if (ps != null && !ps.codePath.equals(scanFile)) {
5220                // The path has changed from what was last scanned...  check the
5221                // version of the new path against what we have stored to determine
5222                // what to do.
5223                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5224                if (pkg.mVersionCode <= ps.versionCode) {
5225                    // The system package has been updated and the code path does not match
5226                    // Ignore entry. Skip it.
5227                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5228                            + " ignored: updated version " + ps.versionCode
5229                            + " better than this " + pkg.mVersionCode);
5230                    if (!updatedPkg.codePath.equals(scanFile)) {
5231                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5232                                + ps.name + " changing from " + updatedPkg.codePathString
5233                                + " to " + scanFile);
5234                        updatedPkg.codePath = scanFile;
5235                        updatedPkg.codePathString = scanFile.toString();
5236                        updatedPkg.resourcePath = scanFile;
5237                        updatedPkg.resourcePathString = scanFile.toString();
5238                    }
5239                    updatedPkg.pkg = pkg;
5240                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5241                } else {
5242                    // The current app on the system partition is better than
5243                    // what we have updated to on the data partition; switch
5244                    // back to the system partition version.
5245                    // At this point, its safely assumed that package installation for
5246                    // apps in system partition will go through. If not there won't be a working
5247                    // version of the app
5248                    // writer
5249                    synchronized (mPackages) {
5250                        // Just remove the loaded entries from package lists.
5251                        mPackages.remove(ps.name);
5252                    }
5253
5254                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5255                            + " reverting from " + ps.codePathString
5256                            + ": new version " + pkg.mVersionCode
5257                            + " better than installed " + ps.versionCode);
5258
5259                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5260                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5261                    synchronized (mInstallLock) {
5262                        args.cleanUpResourcesLI();
5263                    }
5264                    synchronized (mPackages) {
5265                        mSettings.enableSystemPackageLPw(ps.name);
5266                    }
5267                    updatedPkgBetter = true;
5268                }
5269            }
5270        }
5271
5272        if (updatedPkg != null) {
5273            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5274            // initially
5275            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5276
5277            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5278            // flag set initially
5279            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5280                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5281            }
5282        }
5283
5284        // Verify certificates against what was last scanned
5285        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5286
5287        /*
5288         * A new system app appeared, but we already had a non-system one of the
5289         * same name installed earlier.
5290         */
5291        boolean shouldHideSystemApp = false;
5292        if (updatedPkg == null && ps != null
5293                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5294            /*
5295             * Check to make sure the signatures match first. If they don't,
5296             * wipe the installed application and its data.
5297             */
5298            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5299                    != PackageManager.SIGNATURE_MATCH) {
5300                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5301                        + " signatures don't match existing userdata copy; removing");
5302                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5303                ps = null;
5304            } else {
5305                /*
5306                 * If the newly-added system app is an older version than the
5307                 * already installed version, hide it. It will be scanned later
5308                 * and re-added like an update.
5309                 */
5310                if (pkg.mVersionCode <= ps.versionCode) {
5311                    shouldHideSystemApp = true;
5312                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5313                            + " but new version " + pkg.mVersionCode + " better than installed "
5314                            + ps.versionCode + "; hiding system");
5315                } else {
5316                    /*
5317                     * The newly found system app is a newer version that the
5318                     * one previously installed. Simply remove the
5319                     * already-installed application and replace it with our own
5320                     * while keeping the application data.
5321                     */
5322                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5323                            + " reverting from " + ps.codePathString + ": new version "
5324                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5325                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5326                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5327                    synchronized (mInstallLock) {
5328                        args.cleanUpResourcesLI();
5329                    }
5330                }
5331            }
5332        }
5333
5334        // The apk is forward locked (not public) if its code and resources
5335        // are kept in different files. (except for app in either system or
5336        // vendor path).
5337        // TODO grab this value from PackageSettings
5338        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5339            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5340                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5341            }
5342        }
5343
5344        // TODO: extend to support forward-locked splits
5345        String resourcePath = null;
5346        String baseResourcePath = null;
5347        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5348            if (ps != null && ps.resourcePathString != null) {
5349                resourcePath = ps.resourcePathString;
5350                baseResourcePath = ps.resourcePathString;
5351            } else {
5352                // Should not happen at all. Just log an error.
5353                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5354            }
5355        } else {
5356            resourcePath = pkg.codePath;
5357            baseResourcePath = pkg.baseCodePath;
5358        }
5359
5360        // Set application objects path explicitly.
5361        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5362        pkg.applicationInfo.setCodePath(pkg.codePath);
5363        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5364        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5365        pkg.applicationInfo.setResourcePath(resourcePath);
5366        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5367        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5368
5369        // Note that we invoke the following method only if we are about to unpack an application
5370        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5371                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5372
5373        /*
5374         * If the system app should be overridden by a previously installed
5375         * data, hide the system app now and let the /data/app scan pick it up
5376         * again.
5377         */
5378        if (shouldHideSystemApp) {
5379            synchronized (mPackages) {
5380                /*
5381                 * We have to grant systems permissions before we hide, because
5382                 * grantPermissions will assume the package update is trying to
5383                 * expand its permissions.
5384                 */
5385                grantPermissionsLPw(pkg, true, pkg.packageName);
5386                mSettings.disableSystemPackageLPw(pkg.packageName);
5387            }
5388        }
5389
5390        return scannedPkg;
5391    }
5392
5393    private static String fixProcessName(String defProcessName,
5394            String processName, int uid) {
5395        if (processName == null) {
5396            return defProcessName;
5397        }
5398        return processName;
5399    }
5400
5401    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5402            throws PackageManagerException {
5403        if (pkgSetting.signatures.mSignatures != null) {
5404            // Already existing package. Make sure signatures match
5405            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5406                    == PackageManager.SIGNATURE_MATCH;
5407            if (!match) {
5408                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5409                        == PackageManager.SIGNATURE_MATCH;
5410            }
5411            if (!match) {
5412                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5413                        == PackageManager.SIGNATURE_MATCH;
5414            }
5415            if (!match) {
5416                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5417                        + pkg.packageName + " signatures do not match the "
5418                        + "previously installed version; ignoring!");
5419            }
5420        }
5421
5422        // Check for shared user signatures
5423        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5424            // Already existing package. Make sure signatures match
5425            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5426                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5427            if (!match) {
5428                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5429                        == PackageManager.SIGNATURE_MATCH;
5430            }
5431            if (!match) {
5432                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5433                        == PackageManager.SIGNATURE_MATCH;
5434            }
5435            if (!match) {
5436                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5437                        "Package " + pkg.packageName
5438                        + " has no signatures that match those in shared user "
5439                        + pkgSetting.sharedUser.name + "; ignoring!");
5440            }
5441        }
5442    }
5443
5444    /**
5445     * Enforces that only the system UID or root's UID can call a method exposed
5446     * via Binder.
5447     *
5448     * @param message used as message if SecurityException is thrown
5449     * @throws SecurityException if the caller is not system or root
5450     */
5451    private static final void enforceSystemOrRoot(String message) {
5452        final int uid = Binder.getCallingUid();
5453        if (uid != Process.SYSTEM_UID && uid != 0) {
5454            throw new SecurityException(message);
5455        }
5456    }
5457
5458    @Override
5459    public void performBootDexOpt() {
5460        enforceSystemOrRoot("Only the system can request dexopt be performed");
5461
5462        // Before everything else, see whether we need to fstrim.
5463        try {
5464            IMountService ms = PackageHelper.getMountService();
5465            if (ms != null) {
5466                final boolean isUpgrade = isUpgrade();
5467                boolean doTrim = isUpgrade;
5468                if (doTrim) {
5469                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5470                } else {
5471                    final long interval = android.provider.Settings.Global.getLong(
5472                            mContext.getContentResolver(),
5473                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5474                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5475                    if (interval > 0) {
5476                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5477                        if (timeSinceLast > interval) {
5478                            doTrim = true;
5479                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5480                                    + "; running immediately");
5481                        }
5482                    }
5483                }
5484                if (doTrim) {
5485                    if (!isFirstBoot()) {
5486                        try {
5487                            ActivityManagerNative.getDefault().showBootMessage(
5488                                    mContext.getResources().getString(
5489                                            R.string.android_upgrading_fstrim), true);
5490                        } catch (RemoteException e) {
5491                        }
5492                    }
5493                    ms.runMaintenance();
5494                }
5495            } else {
5496                Slog.e(TAG, "Mount service unavailable!");
5497            }
5498        } catch (RemoteException e) {
5499            // Can't happen; MountService is local
5500        }
5501
5502        final ArraySet<PackageParser.Package> pkgs;
5503        synchronized (mPackages) {
5504            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5505        }
5506
5507        if (pkgs != null) {
5508            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5509            // in case the device runs out of space.
5510            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5511            // Give priority to core apps.
5512            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5513                PackageParser.Package pkg = it.next();
5514                if (pkg.coreApp) {
5515                    if (DEBUG_DEXOPT) {
5516                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5517                    }
5518                    sortedPkgs.add(pkg);
5519                    it.remove();
5520                }
5521            }
5522            // Give priority to system apps that listen for pre boot complete.
5523            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5524            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5525            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5526                PackageParser.Package pkg = it.next();
5527                if (pkgNames.contains(pkg.packageName)) {
5528                    if (DEBUG_DEXOPT) {
5529                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5530                    }
5531                    sortedPkgs.add(pkg);
5532                    it.remove();
5533                }
5534            }
5535            // Give priority to system apps.
5536            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5537                PackageParser.Package pkg = it.next();
5538                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5539                    if (DEBUG_DEXOPT) {
5540                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5541                    }
5542                    sortedPkgs.add(pkg);
5543                    it.remove();
5544                }
5545            }
5546            // Give priority to updated system apps.
5547            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5548                PackageParser.Package pkg = it.next();
5549                if (pkg.isUpdatedSystemApp()) {
5550                    if (DEBUG_DEXOPT) {
5551                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5552                    }
5553                    sortedPkgs.add(pkg);
5554                    it.remove();
5555                }
5556            }
5557            // Give priority to apps that listen for boot complete.
5558            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5559            pkgNames = getPackageNamesForIntent(intent);
5560            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5561                PackageParser.Package pkg = it.next();
5562                if (pkgNames.contains(pkg.packageName)) {
5563                    if (DEBUG_DEXOPT) {
5564                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5565                    }
5566                    sortedPkgs.add(pkg);
5567                    it.remove();
5568                }
5569            }
5570            // Filter out packages that aren't recently used.
5571            filterRecentlyUsedApps(pkgs);
5572            // Add all remaining apps.
5573            for (PackageParser.Package pkg : pkgs) {
5574                if (DEBUG_DEXOPT) {
5575                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5576                }
5577                sortedPkgs.add(pkg);
5578            }
5579
5580            // If we want to be lazy, filter everything that wasn't recently used.
5581            if (mLazyDexOpt) {
5582                filterRecentlyUsedApps(sortedPkgs);
5583            }
5584
5585            int i = 0;
5586            int total = sortedPkgs.size();
5587            File dataDir = Environment.getDataDirectory();
5588            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5589            if (lowThreshold == 0) {
5590                throw new IllegalStateException("Invalid low memory threshold");
5591            }
5592            for (PackageParser.Package pkg : sortedPkgs) {
5593                long usableSpace = dataDir.getUsableSpace();
5594                if (usableSpace < lowThreshold) {
5595                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5596                    break;
5597                }
5598                performBootDexOpt(pkg, ++i, total);
5599            }
5600        }
5601    }
5602
5603    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5604        // Filter out packages that aren't recently used.
5605        //
5606        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5607        // should do a full dexopt.
5608        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5609            int total = pkgs.size();
5610            int skipped = 0;
5611            long now = System.currentTimeMillis();
5612            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5613                PackageParser.Package pkg = i.next();
5614                long then = pkg.mLastPackageUsageTimeInMills;
5615                if (then + mDexOptLRUThresholdInMills < now) {
5616                    if (DEBUG_DEXOPT) {
5617                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5618                              ((then == 0) ? "never" : new Date(then)));
5619                    }
5620                    i.remove();
5621                    skipped++;
5622                }
5623            }
5624            if (DEBUG_DEXOPT) {
5625                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5626            }
5627        }
5628    }
5629
5630    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5631        List<ResolveInfo> ris = null;
5632        try {
5633            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5634                    intent, null, 0, UserHandle.USER_OWNER);
5635        } catch (RemoteException e) {
5636        }
5637        ArraySet<String> pkgNames = new ArraySet<String>();
5638        if (ris != null) {
5639            for (ResolveInfo ri : ris) {
5640                pkgNames.add(ri.activityInfo.packageName);
5641            }
5642        }
5643        return pkgNames;
5644    }
5645
5646    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5647        if (DEBUG_DEXOPT) {
5648            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5649        }
5650        if (!isFirstBoot()) {
5651            try {
5652                ActivityManagerNative.getDefault().showBootMessage(
5653                        mContext.getResources().getString(R.string.android_upgrading_apk,
5654                                curr, total), true);
5655            } catch (RemoteException e) {
5656            }
5657        }
5658        PackageParser.Package p = pkg;
5659        synchronized (mInstallLock) {
5660            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5661                    false /* force dex */, false /* defer */, true /* include dependencies */);
5662        }
5663    }
5664
5665    @Override
5666    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5667        return performDexOpt(packageName, instructionSet, false);
5668    }
5669
5670    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5671        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5672        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5673        if (!dexopt && !updateUsage) {
5674            // We aren't going to dexopt or update usage, so bail early.
5675            return false;
5676        }
5677        PackageParser.Package p;
5678        final String targetInstructionSet;
5679        synchronized (mPackages) {
5680            p = mPackages.get(packageName);
5681            if (p == null) {
5682                return false;
5683            }
5684            if (updateUsage) {
5685                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5686            }
5687            mPackageUsage.write(false);
5688            if (!dexopt) {
5689                // We aren't going to dexopt, so bail early.
5690                return false;
5691            }
5692
5693            targetInstructionSet = instructionSet != null ? instructionSet :
5694                    getPrimaryInstructionSet(p.applicationInfo);
5695            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5696                return false;
5697            }
5698        }
5699
5700        synchronized (mInstallLock) {
5701            final String[] instructionSets = new String[] { targetInstructionSet };
5702            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5703                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5704            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5705        }
5706    }
5707
5708    public ArraySet<String> getPackagesThatNeedDexOpt() {
5709        ArraySet<String> pkgs = null;
5710        synchronized (mPackages) {
5711            for (PackageParser.Package p : mPackages.values()) {
5712                if (DEBUG_DEXOPT) {
5713                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5714                }
5715                if (!p.mDexOptPerformed.isEmpty()) {
5716                    continue;
5717                }
5718                if (pkgs == null) {
5719                    pkgs = new ArraySet<String>();
5720                }
5721                pkgs.add(p.packageName);
5722            }
5723        }
5724        return pkgs;
5725    }
5726
5727    public void shutdown() {
5728        mPackageUsage.write(true);
5729    }
5730
5731    @Override
5732    public void forceDexOpt(String packageName) {
5733        enforceSystemOrRoot("forceDexOpt");
5734
5735        PackageParser.Package pkg;
5736        synchronized (mPackages) {
5737            pkg = mPackages.get(packageName);
5738            if (pkg == null) {
5739                throw new IllegalArgumentException("Missing package: " + packageName);
5740            }
5741        }
5742
5743        synchronized (mInstallLock) {
5744            final String[] instructionSets = new String[] {
5745                    getPrimaryInstructionSet(pkg.applicationInfo) };
5746            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5747                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5748            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5749                throw new IllegalStateException("Failed to dexopt: " + res);
5750            }
5751        }
5752    }
5753
5754    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5755        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5756            Slog.w(TAG, "Unable to update from " + oldPkg.name
5757                    + " to " + newPkg.packageName
5758                    + ": old package not in system partition");
5759            return false;
5760        } else if (mPackages.get(oldPkg.name) != null) {
5761            Slog.w(TAG, "Unable to update from " + oldPkg.name
5762                    + " to " + newPkg.packageName
5763                    + ": old package still exists");
5764            return false;
5765        }
5766        return true;
5767    }
5768
5769    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
5770        int[] users = sUserManager.getUserIds();
5771        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
5772        if (res < 0) {
5773            return res;
5774        }
5775        for (int user : users) {
5776            if (user != 0) {
5777                res = mInstaller.createUserData(volumeUuid, packageName,
5778                        UserHandle.getUid(user, uid), user, seinfo);
5779                if (res < 0) {
5780                    return res;
5781                }
5782            }
5783        }
5784        return res;
5785    }
5786
5787    private int removeDataDirsLI(String volumeUuid, String packageName) {
5788        int[] users = sUserManager.getUserIds();
5789        int res = 0;
5790        for (int user : users) {
5791            int resInner = mInstaller.remove(volumeUuid, packageName, user);
5792            if (resInner < 0) {
5793                res = resInner;
5794            }
5795        }
5796
5797        return res;
5798    }
5799
5800    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
5801        int[] users = sUserManager.getUserIds();
5802        int res = 0;
5803        for (int user : users) {
5804            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
5805            if (resInner < 0) {
5806                res = resInner;
5807            }
5808        }
5809        return res;
5810    }
5811
5812    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5813            PackageParser.Package changingLib) {
5814        if (file.path != null) {
5815            usesLibraryFiles.add(file.path);
5816            return;
5817        }
5818        PackageParser.Package p = mPackages.get(file.apk);
5819        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5820            // If we are doing this while in the middle of updating a library apk,
5821            // then we need to make sure to use that new apk for determining the
5822            // dependencies here.  (We haven't yet finished committing the new apk
5823            // to the package manager state.)
5824            if (p == null || p.packageName.equals(changingLib.packageName)) {
5825                p = changingLib;
5826            }
5827        }
5828        if (p != null) {
5829            usesLibraryFiles.addAll(p.getAllCodePaths());
5830        }
5831    }
5832
5833    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5834            PackageParser.Package changingLib) throws PackageManagerException {
5835        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5836            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5837            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5838            for (int i=0; i<N; i++) {
5839                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5840                if (file == null) {
5841                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5842                            "Package " + pkg.packageName + " requires unavailable shared library "
5843                            + pkg.usesLibraries.get(i) + "; failing!");
5844                }
5845                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5846            }
5847            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5848            for (int i=0; i<N; i++) {
5849                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5850                if (file == null) {
5851                    Slog.w(TAG, "Package " + pkg.packageName
5852                            + " desires unavailable shared library "
5853                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5854                } else {
5855                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5856                }
5857            }
5858            N = usesLibraryFiles.size();
5859            if (N > 0) {
5860                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5861            } else {
5862                pkg.usesLibraryFiles = null;
5863            }
5864        }
5865    }
5866
5867    private static boolean hasString(List<String> list, List<String> which) {
5868        if (list == null) {
5869            return false;
5870        }
5871        for (int i=list.size()-1; i>=0; i--) {
5872            for (int j=which.size()-1; j>=0; j--) {
5873                if (which.get(j).equals(list.get(i))) {
5874                    return true;
5875                }
5876            }
5877        }
5878        return false;
5879    }
5880
5881    private void updateAllSharedLibrariesLPw() {
5882        for (PackageParser.Package pkg : mPackages.values()) {
5883            try {
5884                updateSharedLibrariesLPw(pkg, null);
5885            } catch (PackageManagerException e) {
5886                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5887            }
5888        }
5889    }
5890
5891    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5892            PackageParser.Package changingPkg) {
5893        ArrayList<PackageParser.Package> res = null;
5894        for (PackageParser.Package pkg : mPackages.values()) {
5895            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5896                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5897                if (res == null) {
5898                    res = new ArrayList<PackageParser.Package>();
5899                }
5900                res.add(pkg);
5901                try {
5902                    updateSharedLibrariesLPw(pkg, changingPkg);
5903                } catch (PackageManagerException e) {
5904                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5905                }
5906            }
5907        }
5908        return res;
5909    }
5910
5911    /**
5912     * Derive the value of the {@code cpuAbiOverride} based on the provided
5913     * value and an optional stored value from the package settings.
5914     */
5915    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5916        String cpuAbiOverride = null;
5917
5918        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5919            cpuAbiOverride = null;
5920        } else if (abiOverride != null) {
5921            cpuAbiOverride = abiOverride;
5922        } else if (settings != null) {
5923            cpuAbiOverride = settings.cpuAbiOverrideString;
5924        }
5925
5926        return cpuAbiOverride;
5927    }
5928
5929    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5930            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5931        boolean success = false;
5932        try {
5933            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5934                    currentTime, user);
5935            success = true;
5936            return res;
5937        } finally {
5938            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5939                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
5940            }
5941        }
5942    }
5943
5944    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5945            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5946        final File scanFile = new File(pkg.codePath);
5947        if (pkg.applicationInfo.getCodePath() == null ||
5948                pkg.applicationInfo.getResourcePath() == null) {
5949            // Bail out. The resource and code paths haven't been set.
5950            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5951                    "Code and resource paths haven't been set correctly");
5952        }
5953
5954        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5955            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5956        } else {
5957            // Only allow system apps to be flagged as core apps.
5958            pkg.coreApp = false;
5959        }
5960
5961        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5962            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5963        }
5964
5965        if (mCustomResolverComponentName != null &&
5966                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5967            setUpCustomResolverActivity(pkg);
5968        }
5969
5970        if (pkg.packageName.equals("android")) {
5971            synchronized (mPackages) {
5972                if (mAndroidApplication != null) {
5973                    Slog.w(TAG, "*************************************************");
5974                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5975                    Slog.w(TAG, " file=" + scanFile);
5976                    Slog.w(TAG, "*************************************************");
5977                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5978                            "Core android package being redefined.  Skipping.");
5979                }
5980
5981                // Set up information for our fall-back user intent resolution activity.
5982                mPlatformPackage = pkg;
5983                pkg.mVersionCode = mSdkVersion;
5984                mAndroidApplication = pkg.applicationInfo;
5985
5986                if (!mResolverReplaced) {
5987                    mResolveActivity.applicationInfo = mAndroidApplication;
5988                    mResolveActivity.name = ResolverActivity.class.getName();
5989                    mResolveActivity.packageName = mAndroidApplication.packageName;
5990                    mResolveActivity.processName = "system:ui";
5991                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5992                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5993                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5994                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5995                    mResolveActivity.exported = true;
5996                    mResolveActivity.enabled = true;
5997                    mResolveInfo.activityInfo = mResolveActivity;
5998                    mResolveInfo.priority = 0;
5999                    mResolveInfo.preferredOrder = 0;
6000                    mResolveInfo.match = 0;
6001                    mResolveComponentName = new ComponentName(
6002                            mAndroidApplication.packageName, mResolveActivity.name);
6003                }
6004            }
6005        }
6006
6007        if (DEBUG_PACKAGE_SCANNING) {
6008            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6009                Log.d(TAG, "Scanning package " + pkg.packageName);
6010        }
6011
6012        if (mPackages.containsKey(pkg.packageName)
6013                || mSharedLibraries.containsKey(pkg.packageName)) {
6014            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6015                    "Application package " + pkg.packageName
6016                    + " already installed.  Skipping duplicate.");
6017        }
6018
6019        // If we're only installing presumed-existing packages, require that the
6020        // scanned APK is both already known and at the path previously established
6021        // for it.  Previously unknown packages we pick up normally, but if we have an
6022        // a priori expectation about this package's install presence, enforce it.
6023        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6024            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6025            if (known != null) {
6026                if (DEBUG_PACKAGE_SCANNING) {
6027                    Log.d(TAG, "Examining " + pkg.codePath
6028                            + " and requiring known paths " + known.codePathString
6029                            + " & " + known.resourcePathString);
6030                }
6031                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6032                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6033                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6034                            "Application package " + pkg.packageName
6035                            + " found at " + pkg.applicationInfo.getCodePath()
6036                            + " but expected at " + known.codePathString + "; ignoring.");
6037                }
6038            }
6039        }
6040
6041        // Initialize package source and resource directories
6042        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6043        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6044
6045        SharedUserSetting suid = null;
6046        PackageSetting pkgSetting = null;
6047
6048        if (!isSystemApp(pkg)) {
6049            // Only system apps can use these features.
6050            pkg.mOriginalPackages = null;
6051            pkg.mRealPackage = null;
6052            pkg.mAdoptPermissions = null;
6053        }
6054
6055        // writer
6056        synchronized (mPackages) {
6057            if (pkg.mSharedUserId != null) {
6058                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6059                if (suid == null) {
6060                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6061                            "Creating application package " + pkg.packageName
6062                            + " for shared user failed");
6063                }
6064                if (DEBUG_PACKAGE_SCANNING) {
6065                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6066                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6067                                + "): packages=" + suid.packages);
6068                }
6069            }
6070
6071            // Check if we are renaming from an original package name.
6072            PackageSetting origPackage = null;
6073            String realName = null;
6074            if (pkg.mOriginalPackages != null) {
6075                // This package may need to be renamed to a previously
6076                // installed name.  Let's check on that...
6077                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6078                if (pkg.mOriginalPackages.contains(renamed)) {
6079                    // This package had originally been installed as the
6080                    // original name, and we have already taken care of
6081                    // transitioning to the new one.  Just update the new
6082                    // one to continue using the old name.
6083                    realName = pkg.mRealPackage;
6084                    if (!pkg.packageName.equals(renamed)) {
6085                        // Callers into this function may have already taken
6086                        // care of renaming the package; only do it here if
6087                        // it is not already done.
6088                        pkg.setPackageName(renamed);
6089                    }
6090
6091                } else {
6092                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6093                        if ((origPackage = mSettings.peekPackageLPr(
6094                                pkg.mOriginalPackages.get(i))) != null) {
6095                            // We do have the package already installed under its
6096                            // original name...  should we use it?
6097                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6098                                // New package is not compatible with original.
6099                                origPackage = null;
6100                                continue;
6101                            } else if (origPackage.sharedUser != null) {
6102                                // Make sure uid is compatible between packages.
6103                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6104                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6105                                            + " to " + pkg.packageName + ": old uid "
6106                                            + origPackage.sharedUser.name
6107                                            + " differs from " + pkg.mSharedUserId);
6108                                    origPackage = null;
6109                                    continue;
6110                                }
6111                            } else {
6112                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6113                                        + pkg.packageName + " to old name " + origPackage.name);
6114                            }
6115                            break;
6116                        }
6117                    }
6118                }
6119            }
6120
6121            if (mTransferedPackages.contains(pkg.packageName)) {
6122                Slog.w(TAG, "Package " + pkg.packageName
6123                        + " was transferred to another, but its .apk remains");
6124            }
6125
6126            // Just create the setting, don't add it yet. For already existing packages
6127            // the PkgSetting exists already and doesn't have to be created.
6128            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6129                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6130                    pkg.applicationInfo.primaryCpuAbi,
6131                    pkg.applicationInfo.secondaryCpuAbi,
6132                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6133                    user, false);
6134            if (pkgSetting == null) {
6135                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6136                        "Creating application package " + pkg.packageName + " failed");
6137            }
6138
6139            if (pkgSetting.origPackage != null) {
6140                // If we are first transitioning from an original package,
6141                // fix up the new package's name now.  We need to do this after
6142                // looking up the package under its new name, so getPackageLP
6143                // can take care of fiddling things correctly.
6144                pkg.setPackageName(origPackage.name);
6145
6146                // File a report about this.
6147                String msg = "New package " + pkgSetting.realName
6148                        + " renamed to replace old package " + pkgSetting.name;
6149                reportSettingsProblem(Log.WARN, msg);
6150
6151                // Make a note of it.
6152                mTransferedPackages.add(origPackage.name);
6153
6154                // No longer need to retain this.
6155                pkgSetting.origPackage = null;
6156            }
6157
6158            if (realName != null) {
6159                // Make a note of it.
6160                mTransferedPackages.add(pkg.packageName);
6161            }
6162
6163            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6164                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6165            }
6166
6167            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6168                // Check all shared libraries and map to their actual file path.
6169                // We only do this here for apps not on a system dir, because those
6170                // are the only ones that can fail an install due to this.  We
6171                // will take care of the system apps by updating all of their
6172                // library paths after the scan is done.
6173                updateSharedLibrariesLPw(pkg, null);
6174            }
6175
6176            if (mFoundPolicyFile) {
6177                SELinuxMMAC.assignSeinfoValue(pkg);
6178            }
6179
6180            pkg.applicationInfo.uid = pkgSetting.appId;
6181            pkg.mExtras = pkgSetting;
6182            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6183                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6184                    // We just determined the app is signed correctly, so bring
6185                    // over the latest parsed certs.
6186                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6187                } else {
6188                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6189                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6190                                "Package " + pkg.packageName + " upgrade keys do not match the "
6191                                + "previously installed version");
6192                    } else {
6193                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6194                        String msg = "System package " + pkg.packageName
6195                            + " signature changed; retaining data.";
6196                        reportSettingsProblem(Log.WARN, msg);
6197                    }
6198                }
6199            } else {
6200                try {
6201                    verifySignaturesLP(pkgSetting, pkg);
6202                    // We just determined the app is signed correctly, so bring
6203                    // over the latest parsed certs.
6204                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6205                } catch (PackageManagerException e) {
6206                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6207                        throw e;
6208                    }
6209                    // The signature has changed, but this package is in the system
6210                    // image...  let's recover!
6211                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6212                    // However...  if this package is part of a shared user, but it
6213                    // doesn't match the signature of the shared user, let's fail.
6214                    // What this means is that you can't change the signatures
6215                    // associated with an overall shared user, which doesn't seem all
6216                    // that unreasonable.
6217                    if (pkgSetting.sharedUser != null) {
6218                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6219                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6220                            throw new PackageManagerException(
6221                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6222                                            "Signature mismatch for shared user : "
6223                                            + pkgSetting.sharedUser);
6224                        }
6225                    }
6226                    // File a report about this.
6227                    String msg = "System package " + pkg.packageName
6228                        + " signature changed; retaining data.";
6229                    reportSettingsProblem(Log.WARN, msg);
6230                }
6231            }
6232            // Verify that this new package doesn't have any content providers
6233            // that conflict with existing packages.  Only do this if the
6234            // package isn't already installed, since we don't want to break
6235            // things that are installed.
6236            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6237                final int N = pkg.providers.size();
6238                int i;
6239                for (i=0; i<N; i++) {
6240                    PackageParser.Provider p = pkg.providers.get(i);
6241                    if (p.info.authority != null) {
6242                        String names[] = p.info.authority.split(";");
6243                        for (int j = 0; j < names.length; j++) {
6244                            if (mProvidersByAuthority.containsKey(names[j])) {
6245                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6246                                final String otherPackageName =
6247                                        ((other != null && other.getComponentName() != null) ?
6248                                                other.getComponentName().getPackageName() : "?");
6249                                throw new PackageManagerException(
6250                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6251                                                "Can't install because provider name " + names[j]
6252                                                + " (in package " + pkg.applicationInfo.packageName
6253                                                + ") is already used by " + otherPackageName);
6254                            }
6255                        }
6256                    }
6257                }
6258            }
6259
6260            if (pkg.mAdoptPermissions != null) {
6261                // This package wants to adopt ownership of permissions from
6262                // another package.
6263                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6264                    final String origName = pkg.mAdoptPermissions.get(i);
6265                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6266                    if (orig != null) {
6267                        if (verifyPackageUpdateLPr(orig, pkg)) {
6268                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6269                                    + pkg.packageName);
6270                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6271                        }
6272                    }
6273                }
6274            }
6275        }
6276
6277        final String pkgName = pkg.packageName;
6278
6279        final long scanFileTime = scanFile.lastModified();
6280        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6281        pkg.applicationInfo.processName = fixProcessName(
6282                pkg.applicationInfo.packageName,
6283                pkg.applicationInfo.processName,
6284                pkg.applicationInfo.uid);
6285
6286        File dataPath;
6287        if (mPlatformPackage == pkg) {
6288            // The system package is special.
6289            dataPath = new File(Environment.getDataDirectory(), "system");
6290
6291            pkg.applicationInfo.dataDir = dataPath.getPath();
6292
6293        } else {
6294            // This is a normal package, need to make its data directory.
6295            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6296                    UserHandle.USER_OWNER);
6297
6298            boolean uidError = false;
6299            if (dataPath.exists()) {
6300                int currentUid = 0;
6301                try {
6302                    StructStat stat = Os.stat(dataPath.getPath());
6303                    currentUid = stat.st_uid;
6304                } catch (ErrnoException e) {
6305                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6306                }
6307
6308                // If we have mismatched owners for the data path, we have a problem.
6309                if (currentUid != pkg.applicationInfo.uid) {
6310                    boolean recovered = false;
6311                    if (currentUid == 0) {
6312                        // The directory somehow became owned by root.  Wow.
6313                        // This is probably because the system was stopped while
6314                        // installd was in the middle of messing with its libs
6315                        // directory.  Ask installd to fix that.
6316                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6317                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6318                        if (ret >= 0) {
6319                            recovered = true;
6320                            String msg = "Package " + pkg.packageName
6321                                    + " unexpectedly changed to uid 0; recovered to " +
6322                                    + pkg.applicationInfo.uid;
6323                            reportSettingsProblem(Log.WARN, msg);
6324                        }
6325                    }
6326                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6327                            || (scanFlags&SCAN_BOOTING) != 0)) {
6328                        // If this is a system app, we can at least delete its
6329                        // current data so the application will still work.
6330                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6331                        if (ret >= 0) {
6332                            // TODO: Kill the processes first
6333                            // Old data gone!
6334                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6335                                    ? "System package " : "Third party package ";
6336                            String msg = prefix + pkg.packageName
6337                                    + " has changed from uid: "
6338                                    + currentUid + " to "
6339                                    + pkg.applicationInfo.uid + "; old data erased";
6340                            reportSettingsProblem(Log.WARN, msg);
6341                            recovered = true;
6342
6343                            // And now re-install the app.
6344                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6345                                    pkg.applicationInfo.seinfo);
6346                            if (ret == -1) {
6347                                // Ack should not happen!
6348                                msg = prefix + pkg.packageName
6349                                        + " could not have data directory re-created after delete.";
6350                                reportSettingsProblem(Log.WARN, msg);
6351                                throw new PackageManagerException(
6352                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6353                            }
6354                        }
6355                        if (!recovered) {
6356                            mHasSystemUidErrors = true;
6357                        }
6358                    } else if (!recovered) {
6359                        // If we allow this install to proceed, we will be broken.
6360                        // Abort, abort!
6361                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6362                                "scanPackageLI");
6363                    }
6364                    if (!recovered) {
6365                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6366                            + pkg.applicationInfo.uid + "/fs_"
6367                            + currentUid;
6368                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6369                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6370                        String msg = "Package " + pkg.packageName
6371                                + " has mismatched uid: "
6372                                + currentUid + " on disk, "
6373                                + pkg.applicationInfo.uid + " in settings";
6374                        // writer
6375                        synchronized (mPackages) {
6376                            mSettings.mReadMessages.append(msg);
6377                            mSettings.mReadMessages.append('\n');
6378                            uidError = true;
6379                            if (!pkgSetting.uidError) {
6380                                reportSettingsProblem(Log.ERROR, msg);
6381                            }
6382                        }
6383                    }
6384                }
6385                pkg.applicationInfo.dataDir = dataPath.getPath();
6386                if (mShouldRestoreconData) {
6387                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6388                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6389                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6390                }
6391            } else {
6392                if (DEBUG_PACKAGE_SCANNING) {
6393                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6394                        Log.v(TAG, "Want this data dir: " + dataPath);
6395                }
6396                //invoke installer to do the actual installation
6397                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6398                        pkg.applicationInfo.seinfo);
6399                if (ret < 0) {
6400                    // Error from installer
6401                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6402                            "Unable to create data dirs [errorCode=" + ret + "]");
6403                }
6404
6405                if (dataPath.exists()) {
6406                    pkg.applicationInfo.dataDir = dataPath.getPath();
6407                } else {
6408                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6409                    pkg.applicationInfo.dataDir = null;
6410                }
6411            }
6412
6413            pkgSetting.uidError = uidError;
6414        }
6415
6416        final String path = scanFile.getPath();
6417        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6418
6419        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6420            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6421
6422            // Some system apps still use directory structure for native libraries
6423            // in which case we might end up not detecting abi solely based on apk
6424            // structure. Try to detect abi based on directory structure.
6425            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6426                    pkg.applicationInfo.primaryCpuAbi == null) {
6427                setBundledAppAbisAndRoots(pkg, pkgSetting);
6428                setNativeLibraryPaths(pkg);
6429            }
6430
6431        } else {
6432            if ((scanFlags & SCAN_MOVE) != 0) {
6433                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6434                // but we already have this packages package info in the PackageSetting. We just
6435                // use that and derive the native library path based on the new codepath.
6436                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6437                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6438            }
6439
6440            // Set native library paths again. For moves, the path will be updated based on the
6441            // ABIs we've determined above. For non-moves, the path will be updated based on the
6442            // ABIs we determined during compilation, but the path will depend on the final
6443            // package path (after the rename away from the stage path).
6444            setNativeLibraryPaths(pkg);
6445        }
6446
6447        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6448        final int[] userIds = sUserManager.getUserIds();
6449        synchronized (mInstallLock) {
6450            // Create a native library symlink only if we have native libraries
6451            // and if the native libraries are 32 bit libraries. We do not provide
6452            // this symlink for 64 bit libraries.
6453            if (pkg.applicationInfo.primaryCpuAbi != null &&
6454                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6455                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6456                for (int userId : userIds) {
6457                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6458                            nativeLibPath, userId) < 0) {
6459                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6460                                "Failed linking native library dir (user=" + userId + ")");
6461                    }
6462                }
6463            }
6464        }
6465
6466        // This is a special case for the "system" package, where the ABI is
6467        // dictated by the zygote configuration (and init.rc). We should keep track
6468        // of this ABI so that we can deal with "normal" applications that run under
6469        // the same UID correctly.
6470        if (mPlatformPackage == pkg) {
6471            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6472                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6473        }
6474
6475        // If there's a mismatch between the abi-override in the package setting
6476        // and the abiOverride specified for the install. Warn about this because we
6477        // would've already compiled the app without taking the package setting into
6478        // account.
6479        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6480            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6481                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6482                        " for package: " + pkg.packageName);
6483            }
6484        }
6485
6486        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6487        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6488        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6489
6490        // Copy the derived override back to the parsed package, so that we can
6491        // update the package settings accordingly.
6492        pkg.cpuAbiOverride = cpuAbiOverride;
6493
6494        if (DEBUG_ABI_SELECTION) {
6495            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6496                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6497                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6498        }
6499
6500        // Push the derived path down into PackageSettings so we know what to
6501        // clean up at uninstall time.
6502        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6503
6504        if (DEBUG_ABI_SELECTION) {
6505            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6506                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6507                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6508        }
6509
6510        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6511            // We don't do this here during boot because we can do it all
6512            // at once after scanning all existing packages.
6513            //
6514            // We also do this *before* we perform dexopt on this package, so that
6515            // we can avoid redundant dexopts, and also to make sure we've got the
6516            // code and package path correct.
6517            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6518                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6519        }
6520
6521        if ((scanFlags & SCAN_NO_DEX) == 0) {
6522            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6523                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6524            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6525                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6526            }
6527        }
6528        if (mFactoryTest && pkg.requestedPermissions.contains(
6529                android.Manifest.permission.FACTORY_TEST)) {
6530            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6531        }
6532
6533        ArrayList<PackageParser.Package> clientLibPkgs = null;
6534
6535        // writer
6536        synchronized (mPackages) {
6537            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6538                // Only system apps can add new shared libraries.
6539                if (pkg.libraryNames != null) {
6540                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6541                        String name = pkg.libraryNames.get(i);
6542                        boolean allowed = false;
6543                        if (pkg.isUpdatedSystemApp()) {
6544                            // New library entries can only be added through the
6545                            // system image.  This is important to get rid of a lot
6546                            // of nasty edge cases: for example if we allowed a non-
6547                            // system update of the app to add a library, then uninstalling
6548                            // the update would make the library go away, and assumptions
6549                            // we made such as through app install filtering would now
6550                            // have allowed apps on the device which aren't compatible
6551                            // with it.  Better to just have the restriction here, be
6552                            // conservative, and create many fewer cases that can negatively
6553                            // impact the user experience.
6554                            final PackageSetting sysPs = mSettings
6555                                    .getDisabledSystemPkgLPr(pkg.packageName);
6556                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6557                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6558                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6559                                        allowed = true;
6560                                        allowed = true;
6561                                        break;
6562                                    }
6563                                }
6564                            }
6565                        } else {
6566                            allowed = true;
6567                        }
6568                        if (allowed) {
6569                            if (!mSharedLibraries.containsKey(name)) {
6570                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6571                            } else if (!name.equals(pkg.packageName)) {
6572                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6573                                        + name + " already exists; skipping");
6574                            }
6575                        } else {
6576                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6577                                    + name + " that is not declared on system image; skipping");
6578                        }
6579                    }
6580                    if ((scanFlags&SCAN_BOOTING) == 0) {
6581                        // If we are not booting, we need to update any applications
6582                        // that are clients of our shared library.  If we are booting,
6583                        // this will all be done once the scan is complete.
6584                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6585                    }
6586                }
6587            }
6588        }
6589
6590        // We also need to dexopt any apps that are dependent on this library.  Note that
6591        // if these fail, we should abort the install since installing the library will
6592        // result in some apps being broken.
6593        if (clientLibPkgs != null) {
6594            if ((scanFlags & SCAN_NO_DEX) == 0) {
6595                for (int i = 0; i < clientLibPkgs.size(); i++) {
6596                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6597                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6598                            null /* instruction sets */, forceDex,
6599                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6600                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6601                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6602                                "scanPackageLI failed to dexopt clientLibPkgs");
6603                    }
6604                }
6605            }
6606        }
6607
6608        // Also need to kill any apps that are dependent on the library.
6609        if (clientLibPkgs != null) {
6610            for (int i=0; i<clientLibPkgs.size(); i++) {
6611                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6612                killApplication(clientPkg.applicationInfo.packageName,
6613                        clientPkg.applicationInfo.uid, "update lib");
6614            }
6615        }
6616
6617        // Make sure we're not adding any bogus keyset info
6618        KeySetManagerService ksms = mSettings.mKeySetManagerService;
6619        ksms.assertScannedPackageValid(pkg);
6620
6621        // writer
6622        synchronized (mPackages) {
6623            // We don't expect installation to fail beyond this point
6624
6625            // Add the new setting to mSettings
6626            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6627            // Add the new setting to mPackages
6628            mPackages.put(pkg.applicationInfo.packageName, pkg);
6629            // Make sure we don't accidentally delete its data.
6630            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6631            while (iter.hasNext()) {
6632                PackageCleanItem item = iter.next();
6633                if (pkgName.equals(item.packageName)) {
6634                    iter.remove();
6635                }
6636            }
6637
6638            // Take care of first install / last update times.
6639            if (currentTime != 0) {
6640                if (pkgSetting.firstInstallTime == 0) {
6641                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6642                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6643                    pkgSetting.lastUpdateTime = currentTime;
6644                }
6645            } else if (pkgSetting.firstInstallTime == 0) {
6646                // We need *something*.  Take time time stamp of the file.
6647                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6648            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6649                if (scanFileTime != pkgSetting.timeStamp) {
6650                    // A package on the system image has changed; consider this
6651                    // to be an update.
6652                    pkgSetting.lastUpdateTime = scanFileTime;
6653                }
6654            }
6655
6656            // Add the package's KeySets to the global KeySetManagerService
6657            ksms.addScannedPackageLPw(pkg);
6658
6659            int N = pkg.providers.size();
6660            StringBuilder r = null;
6661            int i;
6662            for (i=0; i<N; i++) {
6663                PackageParser.Provider p = pkg.providers.get(i);
6664                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6665                        p.info.processName, pkg.applicationInfo.uid);
6666                mProviders.addProvider(p);
6667                p.syncable = p.info.isSyncable;
6668                if (p.info.authority != null) {
6669                    String names[] = p.info.authority.split(";");
6670                    p.info.authority = null;
6671                    for (int j = 0; j < names.length; j++) {
6672                        if (j == 1 && p.syncable) {
6673                            // We only want the first authority for a provider to possibly be
6674                            // syncable, so if we already added this provider using a different
6675                            // authority clear the syncable flag. We copy the provider before
6676                            // changing it because the mProviders object contains a reference
6677                            // to a provider that we don't want to change.
6678                            // Only do this for the second authority since the resulting provider
6679                            // object can be the same for all future authorities for this provider.
6680                            p = new PackageParser.Provider(p);
6681                            p.syncable = false;
6682                        }
6683                        if (!mProvidersByAuthority.containsKey(names[j])) {
6684                            mProvidersByAuthority.put(names[j], p);
6685                            if (p.info.authority == null) {
6686                                p.info.authority = names[j];
6687                            } else {
6688                                p.info.authority = p.info.authority + ";" + names[j];
6689                            }
6690                            if (DEBUG_PACKAGE_SCANNING) {
6691                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6692                                    Log.d(TAG, "Registered content provider: " + names[j]
6693                                            + ", className = " + p.info.name + ", isSyncable = "
6694                                            + p.info.isSyncable);
6695                            }
6696                        } else {
6697                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6698                            Slog.w(TAG, "Skipping provider name " + names[j] +
6699                                    " (in package " + pkg.applicationInfo.packageName +
6700                                    "): name already used by "
6701                                    + ((other != null && other.getComponentName() != null)
6702                                            ? other.getComponentName().getPackageName() : "?"));
6703                        }
6704                    }
6705                }
6706                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6707                    if (r == null) {
6708                        r = new StringBuilder(256);
6709                    } else {
6710                        r.append(' ');
6711                    }
6712                    r.append(p.info.name);
6713                }
6714            }
6715            if (r != null) {
6716                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6717            }
6718
6719            N = pkg.services.size();
6720            r = null;
6721            for (i=0; i<N; i++) {
6722                PackageParser.Service s = pkg.services.get(i);
6723                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6724                        s.info.processName, pkg.applicationInfo.uid);
6725                mServices.addService(s);
6726                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6727                    if (r == null) {
6728                        r = new StringBuilder(256);
6729                    } else {
6730                        r.append(' ');
6731                    }
6732                    r.append(s.info.name);
6733                }
6734            }
6735            if (r != null) {
6736                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6737            }
6738
6739            N = pkg.receivers.size();
6740            r = null;
6741            for (i=0; i<N; i++) {
6742                PackageParser.Activity a = pkg.receivers.get(i);
6743                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6744                        a.info.processName, pkg.applicationInfo.uid);
6745                mReceivers.addActivity(a, "receiver");
6746                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6747                    if (r == null) {
6748                        r = new StringBuilder(256);
6749                    } else {
6750                        r.append(' ');
6751                    }
6752                    r.append(a.info.name);
6753                }
6754            }
6755            if (r != null) {
6756                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6757            }
6758
6759            N = pkg.activities.size();
6760            r = null;
6761            for (i=0; i<N; i++) {
6762                PackageParser.Activity a = pkg.activities.get(i);
6763                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6764                        a.info.processName, pkg.applicationInfo.uid);
6765                mActivities.addActivity(a, "activity");
6766                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6767                    if (r == null) {
6768                        r = new StringBuilder(256);
6769                    } else {
6770                        r.append(' ');
6771                    }
6772                    r.append(a.info.name);
6773                }
6774            }
6775            if (r != null) {
6776                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6777            }
6778
6779            N = pkg.permissionGroups.size();
6780            r = null;
6781            for (i=0; i<N; i++) {
6782                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6783                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6784                if (cur == null) {
6785                    mPermissionGroups.put(pg.info.name, pg);
6786                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6787                        if (r == null) {
6788                            r = new StringBuilder(256);
6789                        } else {
6790                            r.append(' ');
6791                        }
6792                        r.append(pg.info.name);
6793                    }
6794                } else {
6795                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6796                            + pg.info.packageName + " ignored: original from "
6797                            + cur.info.packageName);
6798                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6799                        if (r == null) {
6800                            r = new StringBuilder(256);
6801                        } else {
6802                            r.append(' ');
6803                        }
6804                        r.append("DUP:");
6805                        r.append(pg.info.name);
6806                    }
6807                }
6808            }
6809            if (r != null) {
6810                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6811            }
6812
6813            N = pkg.permissions.size();
6814            r = null;
6815            for (i=0; i<N; i++) {
6816                PackageParser.Permission p = pkg.permissions.get(i);
6817
6818                // Now that permission groups have a special meaning, we ignore permission
6819                // groups for legacy apps to prevent unexpected behavior. In particular,
6820                // permissions for one app being granted to someone just becuase they happen
6821                // to be in a group defined by another app (before this had no implications).
6822                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
6823                    p.group = mPermissionGroups.get(p.info.group);
6824                    // Warn for a permission in an unknown group.
6825                    if (p.info.group != null && p.group == null) {
6826                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6827                                + p.info.packageName + " in an unknown group " + p.info.group);
6828                    }
6829                }
6830
6831                ArrayMap<String, BasePermission> permissionMap =
6832                        p.tree ? mSettings.mPermissionTrees
6833                                : mSettings.mPermissions;
6834                BasePermission bp = permissionMap.get(p.info.name);
6835
6836                // Allow system apps to redefine non-system permissions
6837                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6838                    final boolean currentOwnerIsSystem = (bp.perm != null
6839                            && isSystemApp(bp.perm.owner));
6840                    if (isSystemApp(p.owner)) {
6841                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6842                            // It's a built-in permission and no owner, take ownership now
6843                            bp.packageSetting = pkgSetting;
6844                            bp.perm = p;
6845                            bp.uid = pkg.applicationInfo.uid;
6846                            bp.sourcePackage = p.info.packageName;
6847                        } else if (!currentOwnerIsSystem) {
6848                            String msg = "New decl " + p.owner + " of permission  "
6849                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6850                            reportSettingsProblem(Log.WARN, msg);
6851                            bp = null;
6852                        }
6853                    }
6854                }
6855
6856                if (bp == null) {
6857                    bp = new BasePermission(p.info.name, p.info.packageName,
6858                            BasePermission.TYPE_NORMAL);
6859                    permissionMap.put(p.info.name, bp);
6860                }
6861
6862                if (bp.perm == null) {
6863                    if (bp.sourcePackage == null
6864                            || bp.sourcePackage.equals(p.info.packageName)) {
6865                        BasePermission tree = findPermissionTreeLP(p.info.name);
6866                        if (tree == null
6867                                || tree.sourcePackage.equals(p.info.packageName)) {
6868                            bp.packageSetting = pkgSetting;
6869                            bp.perm = p;
6870                            bp.uid = pkg.applicationInfo.uid;
6871                            bp.sourcePackage = p.info.packageName;
6872                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6873                                if (r == null) {
6874                                    r = new StringBuilder(256);
6875                                } else {
6876                                    r.append(' ');
6877                                }
6878                                r.append(p.info.name);
6879                            }
6880                        } else {
6881                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6882                                    + p.info.packageName + " ignored: base tree "
6883                                    + tree.name + " is from package "
6884                                    + tree.sourcePackage);
6885                        }
6886                    } else {
6887                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6888                                + p.info.packageName + " ignored: original from "
6889                                + bp.sourcePackage);
6890                    }
6891                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6892                    if (r == null) {
6893                        r = new StringBuilder(256);
6894                    } else {
6895                        r.append(' ');
6896                    }
6897                    r.append("DUP:");
6898                    r.append(p.info.name);
6899                }
6900                if (bp.perm == p) {
6901                    bp.protectionLevel = p.info.protectionLevel;
6902                }
6903            }
6904
6905            if (r != null) {
6906                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6907            }
6908
6909            N = pkg.instrumentation.size();
6910            r = null;
6911            for (i=0; i<N; i++) {
6912                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6913                a.info.packageName = pkg.applicationInfo.packageName;
6914                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6915                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6916                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6917                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6918                a.info.dataDir = pkg.applicationInfo.dataDir;
6919
6920                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6921                // need other information about the application, like the ABI and what not ?
6922                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6923                mInstrumentation.put(a.getComponentName(), a);
6924                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6925                    if (r == null) {
6926                        r = new StringBuilder(256);
6927                    } else {
6928                        r.append(' ');
6929                    }
6930                    r.append(a.info.name);
6931                }
6932            }
6933            if (r != null) {
6934                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6935            }
6936
6937            if (pkg.protectedBroadcasts != null) {
6938                N = pkg.protectedBroadcasts.size();
6939                for (i=0; i<N; i++) {
6940                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6941                }
6942            }
6943
6944            pkgSetting.setTimeStamp(scanFileTime);
6945
6946            // Create idmap files for pairs of (packages, overlay packages).
6947            // Note: "android", ie framework-res.apk, is handled by native layers.
6948            if (pkg.mOverlayTarget != null) {
6949                // This is an overlay package.
6950                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6951                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6952                        mOverlays.put(pkg.mOverlayTarget,
6953                                new ArrayMap<String, PackageParser.Package>());
6954                    }
6955                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6956                    map.put(pkg.packageName, pkg);
6957                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6958                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6959                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6960                                "scanPackageLI failed to createIdmap");
6961                    }
6962                }
6963            } else if (mOverlays.containsKey(pkg.packageName) &&
6964                    !pkg.packageName.equals("android")) {
6965                // This is a regular package, with one or more known overlay packages.
6966                createIdmapsForPackageLI(pkg);
6967            }
6968        }
6969
6970        return pkg;
6971    }
6972
6973    /**
6974     * Derive the ABI of a non-system package located at {@code scanFile}. This information
6975     * is derived purely on the basis of the contents of {@code scanFile} and
6976     * {@code cpuAbiOverride}.
6977     *
6978     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
6979     */
6980    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
6981                                 String cpuAbiOverride, boolean extractLibs)
6982            throws PackageManagerException {
6983        // TODO: We can probably be smarter about this stuff. For installed apps,
6984        // we can calculate this information at install time once and for all. For
6985        // system apps, we can probably assume that this information doesn't change
6986        // after the first boot scan. As things stand, we do lots of unnecessary work.
6987
6988        // Give ourselves some initial paths; we'll come back for another
6989        // pass once we've determined ABI below.
6990        setNativeLibraryPaths(pkg);
6991
6992        // We would never need to extract libs for forward-locked and external packages,
6993        // since the container service will do it for us. We shouldn't attempt to
6994        // extract libs from system app when it was not updated.
6995        if (pkg.isForwardLocked() || isExternal(pkg) ||
6996            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
6997            extractLibs = false;
6998        }
6999
7000        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7001        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7002
7003        NativeLibraryHelper.Handle handle = null;
7004        try {
7005            handle = NativeLibraryHelper.Handle.create(scanFile);
7006            // TODO(multiArch): This can be null for apps that didn't go through the
7007            // usual installation process. We can calculate it again, like we
7008            // do during install time.
7009            //
7010            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7011            // unnecessary.
7012            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7013
7014            // Null out the abis so that they can be recalculated.
7015            pkg.applicationInfo.primaryCpuAbi = null;
7016            pkg.applicationInfo.secondaryCpuAbi = null;
7017            if (isMultiArch(pkg.applicationInfo)) {
7018                // Warn if we've set an abiOverride for multi-lib packages..
7019                // By definition, we need to copy both 32 and 64 bit libraries for
7020                // such packages.
7021                if (pkg.cpuAbiOverride != null
7022                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7023                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7024                }
7025
7026                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7027                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7028                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7029                    if (extractLibs) {
7030                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7031                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7032                                useIsaSpecificSubdirs);
7033                    } else {
7034                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7035                    }
7036                }
7037
7038                maybeThrowExceptionForMultiArchCopy(
7039                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7040
7041                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7042                    if (extractLibs) {
7043                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7044                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7045                                useIsaSpecificSubdirs);
7046                    } else {
7047                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7048                    }
7049                }
7050
7051                maybeThrowExceptionForMultiArchCopy(
7052                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7053
7054                if (abi64 >= 0) {
7055                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7056                }
7057
7058                if (abi32 >= 0) {
7059                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7060                    if (abi64 >= 0) {
7061                        pkg.applicationInfo.secondaryCpuAbi = abi;
7062                    } else {
7063                        pkg.applicationInfo.primaryCpuAbi = abi;
7064                    }
7065                }
7066            } else {
7067                String[] abiList = (cpuAbiOverride != null) ?
7068                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7069
7070                // Enable gross and lame hacks for apps that are built with old
7071                // SDK tools. We must scan their APKs for renderscript bitcode and
7072                // not launch them if it's present. Don't bother checking on devices
7073                // that don't have 64 bit support.
7074                boolean needsRenderScriptOverride = false;
7075                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7076                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7077                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7078                    needsRenderScriptOverride = true;
7079                }
7080
7081                final int copyRet;
7082                if (extractLibs) {
7083                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7084                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7085                } else {
7086                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7087                }
7088
7089                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7090                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7091                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7092                }
7093
7094                if (copyRet >= 0) {
7095                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7096                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7097                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7098                } else if (needsRenderScriptOverride) {
7099                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7100                }
7101            }
7102        } catch (IOException ioe) {
7103            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7104        } finally {
7105            IoUtils.closeQuietly(handle);
7106        }
7107
7108        // Now that we've calculated the ABIs and determined if it's an internal app,
7109        // we will go ahead and populate the nativeLibraryPath.
7110        setNativeLibraryPaths(pkg);
7111    }
7112
7113    /**
7114     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7115     * i.e, so that all packages can be run inside a single process if required.
7116     *
7117     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7118     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7119     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7120     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7121     * updating a package that belongs to a shared user.
7122     *
7123     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7124     * adds unnecessary complexity.
7125     */
7126    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7127            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7128        String requiredInstructionSet = null;
7129        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7130            requiredInstructionSet = VMRuntime.getInstructionSet(
7131                     scannedPackage.applicationInfo.primaryCpuAbi);
7132        }
7133
7134        PackageSetting requirer = null;
7135        for (PackageSetting ps : packagesForUser) {
7136            // If packagesForUser contains scannedPackage, we skip it. This will happen
7137            // when scannedPackage is an update of an existing package. Without this check,
7138            // we will never be able to change the ABI of any package belonging to a shared
7139            // user, even if it's compatible with other packages.
7140            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7141                if (ps.primaryCpuAbiString == null) {
7142                    continue;
7143                }
7144
7145                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7146                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7147                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7148                    // this but there's not much we can do.
7149                    String errorMessage = "Instruction set mismatch, "
7150                            + ((requirer == null) ? "[caller]" : requirer)
7151                            + " requires " + requiredInstructionSet + " whereas " + ps
7152                            + " requires " + instructionSet;
7153                    Slog.w(TAG, errorMessage);
7154                }
7155
7156                if (requiredInstructionSet == null) {
7157                    requiredInstructionSet = instructionSet;
7158                    requirer = ps;
7159                }
7160            }
7161        }
7162
7163        if (requiredInstructionSet != null) {
7164            String adjustedAbi;
7165            if (requirer != null) {
7166                // requirer != null implies that either scannedPackage was null or that scannedPackage
7167                // did not require an ABI, in which case we have to adjust scannedPackage to match
7168                // the ABI of the set (which is the same as requirer's ABI)
7169                adjustedAbi = requirer.primaryCpuAbiString;
7170                if (scannedPackage != null) {
7171                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7172                }
7173            } else {
7174                // requirer == null implies that we're updating all ABIs in the set to
7175                // match scannedPackage.
7176                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7177            }
7178
7179            for (PackageSetting ps : packagesForUser) {
7180                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7181                    if (ps.primaryCpuAbiString != null) {
7182                        continue;
7183                    }
7184
7185                    ps.primaryCpuAbiString = adjustedAbi;
7186                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7187                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7188                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7189
7190                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7191                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7192                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7193                            ps.primaryCpuAbiString = null;
7194                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7195                            return;
7196                        } else {
7197                            mInstaller.rmdex(ps.codePathString,
7198                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7199                        }
7200                    }
7201                }
7202            }
7203        }
7204    }
7205
7206    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7207        synchronized (mPackages) {
7208            mResolverReplaced = true;
7209            // Set up information for custom user intent resolution activity.
7210            mResolveActivity.applicationInfo = pkg.applicationInfo;
7211            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7212            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7213            mResolveActivity.processName = pkg.applicationInfo.packageName;
7214            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7215            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7216                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7217            mResolveActivity.theme = 0;
7218            mResolveActivity.exported = true;
7219            mResolveActivity.enabled = true;
7220            mResolveInfo.activityInfo = mResolveActivity;
7221            mResolveInfo.priority = 0;
7222            mResolveInfo.preferredOrder = 0;
7223            mResolveInfo.match = 0;
7224            mResolveComponentName = mCustomResolverComponentName;
7225            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7226                    mResolveComponentName);
7227        }
7228    }
7229
7230    private static String calculateBundledApkRoot(final String codePathString) {
7231        final File codePath = new File(codePathString);
7232        final File codeRoot;
7233        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7234            codeRoot = Environment.getRootDirectory();
7235        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7236            codeRoot = Environment.getOemDirectory();
7237        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7238            codeRoot = Environment.getVendorDirectory();
7239        } else {
7240            // Unrecognized code path; take its top real segment as the apk root:
7241            // e.g. /something/app/blah.apk => /something
7242            try {
7243                File f = codePath.getCanonicalFile();
7244                File parent = f.getParentFile();    // non-null because codePath is a file
7245                File tmp;
7246                while ((tmp = parent.getParentFile()) != null) {
7247                    f = parent;
7248                    parent = tmp;
7249                }
7250                codeRoot = f;
7251                Slog.w(TAG, "Unrecognized code path "
7252                        + codePath + " - using " + codeRoot);
7253            } catch (IOException e) {
7254                // Can't canonicalize the code path -- shenanigans?
7255                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7256                return Environment.getRootDirectory().getPath();
7257            }
7258        }
7259        return codeRoot.getPath();
7260    }
7261
7262    /**
7263     * Derive and set the location of native libraries for the given package,
7264     * which varies depending on where and how the package was installed.
7265     */
7266    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7267        final ApplicationInfo info = pkg.applicationInfo;
7268        final String codePath = pkg.codePath;
7269        final File codeFile = new File(codePath);
7270        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7271        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7272
7273        info.nativeLibraryRootDir = null;
7274        info.nativeLibraryRootRequiresIsa = false;
7275        info.nativeLibraryDir = null;
7276        info.secondaryNativeLibraryDir = null;
7277
7278        if (isApkFile(codeFile)) {
7279            // Monolithic install
7280            if (bundledApp) {
7281                // If "/system/lib64/apkname" exists, assume that is the per-package
7282                // native library directory to use; otherwise use "/system/lib/apkname".
7283                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7284                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7285                        getPrimaryInstructionSet(info));
7286
7287                // This is a bundled system app so choose the path based on the ABI.
7288                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7289                // is just the default path.
7290                final String apkName = deriveCodePathName(codePath);
7291                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7292                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7293                        apkName).getAbsolutePath();
7294
7295                if (info.secondaryCpuAbi != null) {
7296                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7297                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7298                            secondaryLibDir, apkName).getAbsolutePath();
7299                }
7300            } else if (asecApp) {
7301                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7302                        .getAbsolutePath();
7303            } else {
7304                final String apkName = deriveCodePathName(codePath);
7305                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7306                        .getAbsolutePath();
7307            }
7308
7309            info.nativeLibraryRootRequiresIsa = false;
7310            info.nativeLibraryDir = info.nativeLibraryRootDir;
7311        } else {
7312            // Cluster install
7313            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7314            info.nativeLibraryRootRequiresIsa = true;
7315
7316            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7317                    getPrimaryInstructionSet(info)).getAbsolutePath();
7318
7319            if (info.secondaryCpuAbi != null) {
7320                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7321                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7322            }
7323        }
7324    }
7325
7326    /**
7327     * Calculate the abis and roots for a bundled app. These can uniquely
7328     * be determined from the contents of the system partition, i.e whether
7329     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7330     * of this information, and instead assume that the system was built
7331     * sensibly.
7332     */
7333    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7334                                           PackageSetting pkgSetting) {
7335        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7336
7337        // If "/system/lib64/apkname" exists, assume that is the per-package
7338        // native library directory to use; otherwise use "/system/lib/apkname".
7339        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7340        setBundledAppAbi(pkg, apkRoot, apkName);
7341        // pkgSetting might be null during rescan following uninstall of updates
7342        // to a bundled app, so accommodate that possibility.  The settings in
7343        // that case will be established later from the parsed package.
7344        //
7345        // If the settings aren't null, sync them up with what we've just derived.
7346        // note that apkRoot isn't stored in the package settings.
7347        if (pkgSetting != null) {
7348            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7349            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7350        }
7351    }
7352
7353    /**
7354     * Deduces the ABI of a bundled app and sets the relevant fields on the
7355     * parsed pkg object.
7356     *
7357     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7358     *        under which system libraries are installed.
7359     * @param apkName the name of the installed package.
7360     */
7361    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7362        final File codeFile = new File(pkg.codePath);
7363
7364        final boolean has64BitLibs;
7365        final boolean has32BitLibs;
7366        if (isApkFile(codeFile)) {
7367            // Monolithic install
7368            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7369            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7370        } else {
7371            // Cluster install
7372            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7373            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7374                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7375                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7376                has64BitLibs = (new File(rootDir, isa)).exists();
7377            } else {
7378                has64BitLibs = false;
7379            }
7380            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7381                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7382                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7383                has32BitLibs = (new File(rootDir, isa)).exists();
7384            } else {
7385                has32BitLibs = false;
7386            }
7387        }
7388
7389        if (has64BitLibs && !has32BitLibs) {
7390            // The package has 64 bit libs, but not 32 bit libs. Its primary
7391            // ABI should be 64 bit. We can safely assume here that the bundled
7392            // native libraries correspond to the most preferred ABI in the list.
7393
7394            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7395            pkg.applicationInfo.secondaryCpuAbi = null;
7396        } else if (has32BitLibs && !has64BitLibs) {
7397            // The package has 32 bit libs but not 64 bit libs. Its primary
7398            // ABI should be 32 bit.
7399
7400            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7401            pkg.applicationInfo.secondaryCpuAbi = null;
7402        } else if (has32BitLibs && has64BitLibs) {
7403            // The application has both 64 and 32 bit bundled libraries. We check
7404            // here that the app declares multiArch support, and warn if it doesn't.
7405            //
7406            // We will be lenient here and record both ABIs. The primary will be the
7407            // ABI that's higher on the list, i.e, a device that's configured to prefer
7408            // 64 bit apps will see a 64 bit primary ABI,
7409
7410            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7411                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7412            }
7413
7414            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7415                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7416                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7417            } else {
7418                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7419                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7420            }
7421        } else {
7422            pkg.applicationInfo.primaryCpuAbi = null;
7423            pkg.applicationInfo.secondaryCpuAbi = null;
7424        }
7425    }
7426
7427    private void killApplication(String pkgName, int appId, String reason) {
7428        // Request the ActivityManager to kill the process(only for existing packages)
7429        // so that we do not end up in a confused state while the user is still using the older
7430        // version of the application while the new one gets installed.
7431        IActivityManager am = ActivityManagerNative.getDefault();
7432        if (am != null) {
7433            try {
7434                am.killApplicationWithAppId(pkgName, appId, reason);
7435            } catch (RemoteException e) {
7436            }
7437        }
7438    }
7439
7440    void removePackageLI(PackageSetting ps, boolean chatty) {
7441        if (DEBUG_INSTALL) {
7442            if (chatty)
7443                Log.d(TAG, "Removing package " + ps.name);
7444        }
7445
7446        // writer
7447        synchronized (mPackages) {
7448            mPackages.remove(ps.name);
7449            final PackageParser.Package pkg = ps.pkg;
7450            if (pkg != null) {
7451                cleanPackageDataStructuresLILPw(pkg, chatty);
7452            }
7453        }
7454    }
7455
7456    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7457        if (DEBUG_INSTALL) {
7458            if (chatty)
7459                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7460        }
7461
7462        // writer
7463        synchronized (mPackages) {
7464            mPackages.remove(pkg.applicationInfo.packageName);
7465            cleanPackageDataStructuresLILPw(pkg, chatty);
7466        }
7467    }
7468
7469    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7470        int N = pkg.providers.size();
7471        StringBuilder r = null;
7472        int i;
7473        for (i=0; i<N; i++) {
7474            PackageParser.Provider p = pkg.providers.get(i);
7475            mProviders.removeProvider(p);
7476            if (p.info.authority == null) {
7477
7478                /* There was another ContentProvider with this authority when
7479                 * this app was installed so this authority is null,
7480                 * Ignore it as we don't have to unregister the provider.
7481                 */
7482                continue;
7483            }
7484            String names[] = p.info.authority.split(";");
7485            for (int j = 0; j < names.length; j++) {
7486                if (mProvidersByAuthority.get(names[j]) == p) {
7487                    mProvidersByAuthority.remove(names[j]);
7488                    if (DEBUG_REMOVE) {
7489                        if (chatty)
7490                            Log.d(TAG, "Unregistered content provider: " + names[j]
7491                                    + ", className = " + p.info.name + ", isSyncable = "
7492                                    + p.info.isSyncable);
7493                    }
7494                }
7495            }
7496            if (DEBUG_REMOVE && chatty) {
7497                if (r == null) {
7498                    r = new StringBuilder(256);
7499                } else {
7500                    r.append(' ');
7501                }
7502                r.append(p.info.name);
7503            }
7504        }
7505        if (r != null) {
7506            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7507        }
7508
7509        N = pkg.services.size();
7510        r = null;
7511        for (i=0; i<N; i++) {
7512            PackageParser.Service s = pkg.services.get(i);
7513            mServices.removeService(s);
7514            if (chatty) {
7515                if (r == null) {
7516                    r = new StringBuilder(256);
7517                } else {
7518                    r.append(' ');
7519                }
7520                r.append(s.info.name);
7521            }
7522        }
7523        if (r != null) {
7524            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7525        }
7526
7527        N = pkg.receivers.size();
7528        r = null;
7529        for (i=0; i<N; i++) {
7530            PackageParser.Activity a = pkg.receivers.get(i);
7531            mReceivers.removeActivity(a, "receiver");
7532            if (DEBUG_REMOVE && chatty) {
7533                if (r == null) {
7534                    r = new StringBuilder(256);
7535                } else {
7536                    r.append(' ');
7537                }
7538                r.append(a.info.name);
7539            }
7540        }
7541        if (r != null) {
7542            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7543        }
7544
7545        N = pkg.activities.size();
7546        r = null;
7547        for (i=0; i<N; i++) {
7548            PackageParser.Activity a = pkg.activities.get(i);
7549            mActivities.removeActivity(a, "activity");
7550            if (DEBUG_REMOVE && chatty) {
7551                if (r == null) {
7552                    r = new StringBuilder(256);
7553                } else {
7554                    r.append(' ');
7555                }
7556                r.append(a.info.name);
7557            }
7558        }
7559        if (r != null) {
7560            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7561        }
7562
7563        N = pkg.permissions.size();
7564        r = null;
7565        for (i=0; i<N; i++) {
7566            PackageParser.Permission p = pkg.permissions.get(i);
7567            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7568            if (bp == null) {
7569                bp = mSettings.mPermissionTrees.get(p.info.name);
7570            }
7571            if (bp != null && bp.perm == p) {
7572                bp.perm = null;
7573                if (DEBUG_REMOVE && chatty) {
7574                    if (r == null) {
7575                        r = new StringBuilder(256);
7576                    } else {
7577                        r.append(' ');
7578                    }
7579                    r.append(p.info.name);
7580                }
7581            }
7582            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7583                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7584                if (appOpPerms != null) {
7585                    appOpPerms.remove(pkg.packageName);
7586                }
7587            }
7588        }
7589        if (r != null) {
7590            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7591        }
7592
7593        N = pkg.requestedPermissions.size();
7594        r = null;
7595        for (i=0; i<N; i++) {
7596            String perm = pkg.requestedPermissions.get(i);
7597            BasePermission bp = mSettings.mPermissions.get(perm);
7598            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7599                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7600                if (appOpPerms != null) {
7601                    appOpPerms.remove(pkg.packageName);
7602                    if (appOpPerms.isEmpty()) {
7603                        mAppOpPermissionPackages.remove(perm);
7604                    }
7605                }
7606            }
7607        }
7608        if (r != null) {
7609            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7610        }
7611
7612        N = pkg.instrumentation.size();
7613        r = null;
7614        for (i=0; i<N; i++) {
7615            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7616            mInstrumentation.remove(a.getComponentName());
7617            if (DEBUG_REMOVE && chatty) {
7618                if (r == null) {
7619                    r = new StringBuilder(256);
7620                } else {
7621                    r.append(' ');
7622                }
7623                r.append(a.info.name);
7624            }
7625        }
7626        if (r != null) {
7627            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7628        }
7629
7630        r = null;
7631        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7632            // Only system apps can hold shared libraries.
7633            if (pkg.libraryNames != null) {
7634                for (i=0; i<pkg.libraryNames.size(); i++) {
7635                    String name = pkg.libraryNames.get(i);
7636                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7637                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7638                        mSharedLibraries.remove(name);
7639                        if (DEBUG_REMOVE && chatty) {
7640                            if (r == null) {
7641                                r = new StringBuilder(256);
7642                            } else {
7643                                r.append(' ');
7644                            }
7645                            r.append(name);
7646                        }
7647                    }
7648                }
7649            }
7650        }
7651        if (r != null) {
7652            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7653        }
7654    }
7655
7656    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7657        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7658            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7659                return true;
7660            }
7661        }
7662        return false;
7663    }
7664
7665    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7666    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7667    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7668
7669    private void updatePermissionsLPw(String changingPkg,
7670            PackageParser.Package pkgInfo, int flags) {
7671        // Make sure there are no dangling permission trees.
7672        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7673        while (it.hasNext()) {
7674            final BasePermission bp = it.next();
7675            if (bp.packageSetting == null) {
7676                // We may not yet have parsed the package, so just see if
7677                // we still know about its settings.
7678                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7679            }
7680            if (bp.packageSetting == null) {
7681                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7682                        + " from package " + bp.sourcePackage);
7683                it.remove();
7684            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7685                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7686                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7687                            + " from package " + bp.sourcePackage);
7688                    flags |= UPDATE_PERMISSIONS_ALL;
7689                    it.remove();
7690                }
7691            }
7692        }
7693
7694        // Make sure all dynamic permissions have been assigned to a package,
7695        // and make sure there are no dangling permissions.
7696        it = mSettings.mPermissions.values().iterator();
7697        while (it.hasNext()) {
7698            final BasePermission bp = it.next();
7699            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7700                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7701                        + bp.name + " pkg=" + bp.sourcePackage
7702                        + " info=" + bp.pendingInfo);
7703                if (bp.packageSetting == null && bp.pendingInfo != null) {
7704                    final BasePermission tree = findPermissionTreeLP(bp.name);
7705                    if (tree != null && tree.perm != null) {
7706                        bp.packageSetting = tree.packageSetting;
7707                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7708                                new PermissionInfo(bp.pendingInfo));
7709                        bp.perm.info.packageName = tree.perm.info.packageName;
7710                        bp.perm.info.name = bp.name;
7711                        bp.uid = tree.uid;
7712                    }
7713                }
7714            }
7715            if (bp.packageSetting == null) {
7716                // We may not yet have parsed the package, so just see if
7717                // we still know about its settings.
7718                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7719            }
7720            if (bp.packageSetting == null) {
7721                Slog.w(TAG, "Removing dangling permission: " + bp.name
7722                        + " from package " + bp.sourcePackage);
7723                it.remove();
7724            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7725                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7726                    Slog.i(TAG, "Removing old permission: " + bp.name
7727                            + " from package " + bp.sourcePackage);
7728                    flags |= UPDATE_PERMISSIONS_ALL;
7729                    it.remove();
7730                }
7731            }
7732        }
7733
7734        // Now update the permissions for all packages, in particular
7735        // replace the granted permissions of the system packages.
7736        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7737            for (PackageParser.Package pkg : mPackages.values()) {
7738                if (pkg != pkgInfo) {
7739                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7740                            changingPkg);
7741                }
7742            }
7743        }
7744
7745        if (pkgInfo != null) {
7746            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7747        }
7748    }
7749
7750    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7751            String packageOfInterest) {
7752        // IMPORTANT: There are two types of permissions: install and runtime.
7753        // Install time permissions are granted when the app is installed to
7754        // all device users and users added in the future. Runtime permissions
7755        // are granted at runtime explicitly to specific users. Normal and signature
7756        // protected permissions are install time permissions. Dangerous permissions
7757        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7758        // otherwise they are runtime permissions. This function does not manage
7759        // runtime permissions except for the case an app targeting Lollipop MR1
7760        // being upgraded to target a newer SDK, in which case dangerous permissions
7761        // are transformed from install time to runtime ones.
7762
7763        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7764        if (ps == null) {
7765            return;
7766        }
7767
7768        PermissionsState permissionsState = ps.getPermissionsState();
7769        PermissionsState origPermissions = permissionsState;
7770
7771        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7772
7773        int[] upgradeUserIds = EMPTY_INT_ARRAY;
7774        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
7775
7776        boolean changedInstallPermission = false;
7777
7778        if (replace) {
7779            ps.installPermissionsFixed = false;
7780            if (!ps.isSharedUser()) {
7781                origPermissions = new PermissionsState(permissionsState);
7782                permissionsState.reset();
7783            }
7784        }
7785
7786        permissionsState.setGlobalGids(mGlobalGids);
7787
7788        final int N = pkg.requestedPermissions.size();
7789        for (int i=0; i<N; i++) {
7790            final String name = pkg.requestedPermissions.get(i);
7791            final BasePermission bp = mSettings.mPermissions.get(name);
7792
7793            if (DEBUG_INSTALL) {
7794                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7795            }
7796
7797            if (bp == null || bp.packageSetting == null) {
7798                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7799                    Slog.w(TAG, "Unknown permission " + name
7800                            + " in package " + pkg.packageName);
7801                }
7802                continue;
7803            }
7804
7805            final String perm = bp.name;
7806            boolean allowedSig = false;
7807            int grant = GRANT_DENIED;
7808
7809            // Keep track of app op permissions.
7810            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7811                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7812                if (pkgs == null) {
7813                    pkgs = new ArraySet<>();
7814                    mAppOpPermissionPackages.put(bp.name, pkgs);
7815                }
7816                pkgs.add(pkg.packageName);
7817            }
7818
7819            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7820            switch (level) {
7821                case PermissionInfo.PROTECTION_NORMAL: {
7822                    // For all apps normal permissions are install time ones.
7823                    grant = GRANT_INSTALL;
7824                } break;
7825
7826                case PermissionInfo.PROTECTION_DANGEROUS: {
7827                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7828                        // For legacy apps dangerous permissions are install time ones.
7829                        grant = GRANT_INSTALL_LEGACY;
7830                    } else if (ps.isSystem()) {
7831                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7832                        if (origPermissions.hasInstallPermission(bp.name)) {
7833                            // If a system app had an install permission, then the app was
7834                            // upgraded and we grant the permissions as runtime to all users.
7835                            grant = GRANT_UPGRADE;
7836                            upgradeUserIds = currentUserIds;
7837                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7838                            // If users changed since the last permissions update for a
7839                            // system app, we grant the permission as runtime to the new users.
7840                            grant = GRANT_UPGRADE;
7841                            upgradeUserIds = currentUserIds;
7842                            for (int userId : updatedUserIds) {
7843                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7844                            }
7845                        } else {
7846                            // Otherwise, we grant the permission as runtime if the app
7847                            // already had it, i.e. we preserve runtime permissions.
7848                            grant = GRANT_RUNTIME;
7849                        }
7850                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7851                        // For legacy apps that became modern, install becomes runtime.
7852                        grant = GRANT_UPGRADE;
7853                        upgradeUserIds = currentUserIds;
7854                    } else if (replace) {
7855                        // For upgraded modern apps keep runtime permissions unchanged.
7856                        grant = GRANT_RUNTIME;
7857                    }
7858                } break;
7859
7860                case PermissionInfo.PROTECTION_SIGNATURE: {
7861                    // For all apps signature permissions are install time ones.
7862                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7863                    if (allowedSig) {
7864                        grant = GRANT_INSTALL;
7865                    }
7866                } break;
7867            }
7868
7869            if (DEBUG_INSTALL) {
7870                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7871            }
7872
7873            if (grant != GRANT_DENIED) {
7874                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7875                    // If this is an existing, non-system package, then
7876                    // we can't add any new permissions to it.
7877                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7878                        // Except...  if this is a permission that was added
7879                        // to the platform (note: need to only do this when
7880                        // updating the platform).
7881                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7882                            grant = GRANT_DENIED;
7883                        }
7884                    }
7885                }
7886
7887                switch (grant) {
7888                    case GRANT_INSTALL: {
7889                        // Revoke this as runtime permission to handle the case of
7890                        // a runtime permssion being downgraded to an install one.
7891                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7892                            if (origPermissions.getRuntimePermissionState(
7893                                    bp.name, userId) != null) {
7894                                // Revoke the runtime permission and clear the flags.
7895                                origPermissions.revokeRuntimePermission(bp, userId);
7896                                origPermissions.updatePermissionFlags(bp, userId,
7897                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
7898                                // If we revoked a permission permission, we have to write.
7899                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7900                                        changedRuntimePermissionUserIds, userId);
7901                            }
7902                        }
7903                        // Grant an install permission.
7904                        if (permissionsState.grantInstallPermission(bp) !=
7905                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7906                            changedInstallPermission = true;
7907                        }
7908                    } break;
7909
7910                    case GRANT_INSTALL_LEGACY: {
7911                        // Grant an install permission.
7912                        if (permissionsState.grantInstallPermission(bp) !=
7913                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7914                            changedInstallPermission = true;
7915                        }
7916                    } break;
7917
7918                    case GRANT_RUNTIME: {
7919                        // Grant previously granted runtime permissions.
7920                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7921                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7922                                PermissionState permissionState = origPermissions
7923                                        .getRuntimePermissionState(bp.name, userId);
7924                                final int flags = permissionState.getFlags();
7925                                if (permissionsState.grantRuntimePermission(bp, userId) ==
7926                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7927                                    // If we cannot put the permission as it was, we have to write.
7928                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7929                                            changedRuntimePermissionUserIds, userId);
7930                                } else {
7931                                    // System components not only get the permissions but
7932                                    // they are also fixed, so nothing can change that.
7933                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7934                                            ? flags
7935                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7936                                    // Propagate the permission flags.
7937                                    permissionsState.updatePermissionFlags(bp, userId,
7938                                            newFlags, newFlags);
7939                                }
7940                            }
7941                        }
7942                    } break;
7943
7944                    case GRANT_UPGRADE: {
7945                        // Grant runtime permissions for a previously held install permission.
7946                        PermissionState permissionState = origPermissions
7947                                .getInstallPermissionState(bp.name);
7948                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
7949
7950                        origPermissions.revokeInstallPermission(bp);
7951                        // We will be transferring the permission flags, so clear them.
7952                        origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
7953                                PackageManager.MASK_PERMISSION_FLAGS, 0);
7954
7955                        // If the permission is not to be promoted to runtime we ignore it and
7956                        // also its other flags as they are not applicable to install permissions.
7957                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
7958                            for (int userId : upgradeUserIds) {
7959                                if (permissionsState.grantRuntimePermission(bp, userId) !=
7960                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7961                                    // System components not only get the permissions but
7962                                    // they are also fixed so nothing can change that.
7963                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7964                                            ? flags
7965                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7966                                    // Transfer the permission flags.
7967                                    permissionsState.updatePermissionFlags(bp, userId,
7968                                            newFlags, newFlags);
7969                                    // If we granted the permission, we have to write.
7970                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7971                                            changedRuntimePermissionUserIds, userId);
7972                                }
7973                            }
7974                        }
7975                    } break;
7976
7977                    default: {
7978                        if (packageOfInterest == null
7979                                || packageOfInterest.equals(pkg.packageName)) {
7980                            Slog.w(TAG, "Not granting permission " + perm
7981                                    + " to package " + pkg.packageName
7982                                    + " because it was previously installed without");
7983                        }
7984                    } break;
7985                }
7986            } else {
7987                if (permissionsState.revokeInstallPermission(bp) !=
7988                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7989                    // Also drop the permission flags.
7990                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
7991                            PackageManager.MASK_PERMISSION_FLAGS, 0);
7992                    changedInstallPermission = true;
7993                    Slog.i(TAG, "Un-granting permission " + perm
7994                            + " from package " + pkg.packageName
7995                            + " (protectionLevel=" + bp.protectionLevel
7996                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7997                            + ")");
7998                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7999                    // Don't print warning for app op permissions, since it is fine for them
8000                    // not to be granted, there is a UI for the user to decide.
8001                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8002                        Slog.w(TAG, "Not granting permission " + perm
8003                                + " to package " + pkg.packageName
8004                                + " (protectionLevel=" + bp.protectionLevel
8005                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8006                                + ")");
8007                    }
8008                }
8009            }
8010        }
8011
8012        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8013                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8014            // This is the first that we have heard about this package, so the
8015            // permissions we have now selected are fixed until explicitly
8016            // changed.
8017            ps.installPermissionsFixed = true;
8018        }
8019
8020        ps.setPermissionsUpdatedForUserIds(currentUserIds);
8021
8022        // Persist the runtime permissions state for users with changes.
8023        for (int userId : changedRuntimePermissionUserIds) {
8024            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8025        }
8026    }
8027
8028    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8029        boolean allowed = false;
8030        final int NP = PackageParser.NEW_PERMISSIONS.length;
8031        for (int ip=0; ip<NP; ip++) {
8032            final PackageParser.NewPermissionInfo npi
8033                    = PackageParser.NEW_PERMISSIONS[ip];
8034            if (npi.name.equals(perm)
8035                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8036                allowed = true;
8037                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8038                        + pkg.packageName);
8039                break;
8040            }
8041        }
8042        return allowed;
8043    }
8044
8045    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8046            BasePermission bp, PermissionsState origPermissions) {
8047        boolean allowed;
8048        allowed = (compareSignatures(
8049                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8050                        == PackageManager.SIGNATURE_MATCH)
8051                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8052                        == PackageManager.SIGNATURE_MATCH);
8053        if (!allowed && (bp.protectionLevel
8054                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
8055            if (isSystemApp(pkg)) {
8056                // For updated system applications, a system permission
8057                // is granted only if it had been defined by the original application.
8058                if (pkg.isUpdatedSystemApp()) {
8059                    final PackageSetting sysPs = mSettings
8060                            .getDisabledSystemPkgLPr(pkg.packageName);
8061                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8062                        // If the original was granted this permission, we take
8063                        // that grant decision as read and propagate it to the
8064                        // update.
8065                        if (sysPs.isPrivileged()) {
8066                            allowed = true;
8067                        }
8068                    } else {
8069                        // The system apk may have been updated with an older
8070                        // version of the one on the data partition, but which
8071                        // granted a new system permission that it didn't have
8072                        // before.  In this case we do want to allow the app to
8073                        // now get the new permission if the ancestral apk is
8074                        // privileged to get it.
8075                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8076                            for (int j=0;
8077                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8078                                if (perm.equals(
8079                                        sysPs.pkg.requestedPermissions.get(j))) {
8080                                    allowed = true;
8081                                    break;
8082                                }
8083                            }
8084                        }
8085                    }
8086                } else {
8087                    allowed = isPrivilegedApp(pkg);
8088                }
8089            }
8090        }
8091        if (!allowed && (bp.protectionLevel
8092                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8093            // For development permissions, a development permission
8094            // is granted only if it was already granted.
8095            allowed = origPermissions.hasInstallPermission(perm);
8096        }
8097        return allowed;
8098    }
8099
8100    final class ActivityIntentResolver
8101            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8102        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8103                boolean defaultOnly, int userId) {
8104            if (!sUserManager.exists(userId)) return null;
8105            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8106            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8107        }
8108
8109        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8110                int userId) {
8111            if (!sUserManager.exists(userId)) return null;
8112            mFlags = flags;
8113            return super.queryIntent(intent, resolvedType,
8114                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8115        }
8116
8117        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8118                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8119            if (!sUserManager.exists(userId)) return null;
8120            if (packageActivities == null) {
8121                return null;
8122            }
8123            mFlags = flags;
8124            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8125            final int N = packageActivities.size();
8126            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8127                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8128
8129            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8130            for (int i = 0; i < N; ++i) {
8131                intentFilters = packageActivities.get(i).intents;
8132                if (intentFilters != null && intentFilters.size() > 0) {
8133                    PackageParser.ActivityIntentInfo[] array =
8134                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8135                    intentFilters.toArray(array);
8136                    listCut.add(array);
8137                }
8138            }
8139            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8140        }
8141
8142        public final void addActivity(PackageParser.Activity a, String type) {
8143            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8144            mActivities.put(a.getComponentName(), a);
8145            if (DEBUG_SHOW_INFO)
8146                Log.v(
8147                TAG, "  " + type + " " +
8148                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8149            if (DEBUG_SHOW_INFO)
8150                Log.v(TAG, "    Class=" + a.info.name);
8151            final int NI = a.intents.size();
8152            for (int j=0; j<NI; j++) {
8153                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8154                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8155                    intent.setPriority(0);
8156                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8157                            + a.className + " with priority > 0, forcing to 0");
8158                }
8159                if (DEBUG_SHOW_INFO) {
8160                    Log.v(TAG, "    IntentFilter:");
8161                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8162                }
8163                if (!intent.debugCheck()) {
8164                    Log.w(TAG, "==> For Activity " + a.info.name);
8165                }
8166                addFilter(intent);
8167            }
8168        }
8169
8170        public final void removeActivity(PackageParser.Activity a, String type) {
8171            mActivities.remove(a.getComponentName());
8172            if (DEBUG_SHOW_INFO) {
8173                Log.v(TAG, "  " + type + " "
8174                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8175                                : a.info.name) + ":");
8176                Log.v(TAG, "    Class=" + a.info.name);
8177            }
8178            final int NI = a.intents.size();
8179            for (int j=0; j<NI; j++) {
8180                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8181                if (DEBUG_SHOW_INFO) {
8182                    Log.v(TAG, "    IntentFilter:");
8183                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8184                }
8185                removeFilter(intent);
8186            }
8187        }
8188
8189        @Override
8190        protected boolean allowFilterResult(
8191                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8192            ActivityInfo filterAi = filter.activity.info;
8193            for (int i=dest.size()-1; i>=0; i--) {
8194                ActivityInfo destAi = dest.get(i).activityInfo;
8195                if (destAi.name == filterAi.name
8196                        && destAi.packageName == filterAi.packageName) {
8197                    return false;
8198                }
8199            }
8200            return true;
8201        }
8202
8203        @Override
8204        protected ActivityIntentInfo[] newArray(int size) {
8205            return new ActivityIntentInfo[size];
8206        }
8207
8208        @Override
8209        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8210            if (!sUserManager.exists(userId)) return true;
8211            PackageParser.Package p = filter.activity.owner;
8212            if (p != null) {
8213                PackageSetting ps = (PackageSetting)p.mExtras;
8214                if (ps != null) {
8215                    // System apps are never considered stopped for purposes of
8216                    // filtering, because there may be no way for the user to
8217                    // actually re-launch them.
8218                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8219                            && ps.getStopped(userId);
8220                }
8221            }
8222            return false;
8223        }
8224
8225        @Override
8226        protected boolean isPackageForFilter(String packageName,
8227                PackageParser.ActivityIntentInfo info) {
8228            return packageName.equals(info.activity.owner.packageName);
8229        }
8230
8231        @Override
8232        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8233                int match, int userId) {
8234            if (!sUserManager.exists(userId)) return null;
8235            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8236                return null;
8237            }
8238            final PackageParser.Activity activity = info.activity;
8239            if (mSafeMode && (activity.info.applicationInfo.flags
8240                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8241                return null;
8242            }
8243            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8244            if (ps == null) {
8245                return null;
8246            }
8247            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8248                    ps.readUserState(userId), userId);
8249            if (ai == null) {
8250                return null;
8251            }
8252            final ResolveInfo res = new ResolveInfo();
8253            res.activityInfo = ai;
8254            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8255                res.filter = info;
8256            }
8257            if (info != null) {
8258                res.handleAllWebDataURI = info.handleAllWebDataURI();
8259            }
8260            res.priority = info.getPriority();
8261            res.preferredOrder = activity.owner.mPreferredOrder;
8262            //System.out.println("Result: " + res.activityInfo.className +
8263            //                   " = " + res.priority);
8264            res.match = match;
8265            res.isDefault = info.hasDefault;
8266            res.labelRes = info.labelRes;
8267            res.nonLocalizedLabel = info.nonLocalizedLabel;
8268            if (userNeedsBadging(userId)) {
8269                res.noResourceId = true;
8270            } else {
8271                res.icon = info.icon;
8272            }
8273            res.iconResourceId = info.icon;
8274            res.system = res.activityInfo.applicationInfo.isSystemApp();
8275            return res;
8276        }
8277
8278        @Override
8279        protected void sortResults(List<ResolveInfo> results) {
8280            Collections.sort(results, mResolvePrioritySorter);
8281        }
8282
8283        @Override
8284        protected void dumpFilter(PrintWriter out, String prefix,
8285                PackageParser.ActivityIntentInfo filter) {
8286            out.print(prefix); out.print(
8287                    Integer.toHexString(System.identityHashCode(filter.activity)));
8288                    out.print(' ');
8289                    filter.activity.printComponentShortName(out);
8290                    out.print(" filter ");
8291                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8292        }
8293
8294        @Override
8295        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8296            return filter.activity;
8297        }
8298
8299        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8300            PackageParser.Activity activity = (PackageParser.Activity)label;
8301            out.print(prefix); out.print(
8302                    Integer.toHexString(System.identityHashCode(activity)));
8303                    out.print(' ');
8304                    activity.printComponentShortName(out);
8305            if (count > 1) {
8306                out.print(" ("); out.print(count); out.print(" filters)");
8307            }
8308            out.println();
8309        }
8310
8311//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8312//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8313//            final List<ResolveInfo> retList = Lists.newArrayList();
8314//            while (i.hasNext()) {
8315//                final ResolveInfo resolveInfo = i.next();
8316//                if (isEnabledLP(resolveInfo.activityInfo)) {
8317//                    retList.add(resolveInfo);
8318//                }
8319//            }
8320//            return retList;
8321//        }
8322
8323        // Keys are String (activity class name), values are Activity.
8324        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8325                = new ArrayMap<ComponentName, PackageParser.Activity>();
8326        private int mFlags;
8327    }
8328
8329    private final class ServiceIntentResolver
8330            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8331        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8332                boolean defaultOnly, int userId) {
8333            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8334            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8335        }
8336
8337        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8338                int userId) {
8339            if (!sUserManager.exists(userId)) return null;
8340            mFlags = flags;
8341            return super.queryIntent(intent, resolvedType,
8342                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8343        }
8344
8345        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8346                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8347            if (!sUserManager.exists(userId)) return null;
8348            if (packageServices == null) {
8349                return null;
8350            }
8351            mFlags = flags;
8352            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8353            final int N = packageServices.size();
8354            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8355                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8356
8357            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8358            for (int i = 0; i < N; ++i) {
8359                intentFilters = packageServices.get(i).intents;
8360                if (intentFilters != null && intentFilters.size() > 0) {
8361                    PackageParser.ServiceIntentInfo[] array =
8362                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8363                    intentFilters.toArray(array);
8364                    listCut.add(array);
8365                }
8366            }
8367            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8368        }
8369
8370        public final void addService(PackageParser.Service s) {
8371            mServices.put(s.getComponentName(), s);
8372            if (DEBUG_SHOW_INFO) {
8373                Log.v(TAG, "  "
8374                        + (s.info.nonLocalizedLabel != null
8375                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8376                Log.v(TAG, "    Class=" + s.info.name);
8377            }
8378            final int NI = s.intents.size();
8379            int j;
8380            for (j=0; j<NI; j++) {
8381                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8382                if (DEBUG_SHOW_INFO) {
8383                    Log.v(TAG, "    IntentFilter:");
8384                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8385                }
8386                if (!intent.debugCheck()) {
8387                    Log.w(TAG, "==> For Service " + s.info.name);
8388                }
8389                addFilter(intent);
8390            }
8391        }
8392
8393        public final void removeService(PackageParser.Service s) {
8394            mServices.remove(s.getComponentName());
8395            if (DEBUG_SHOW_INFO) {
8396                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8397                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8398                Log.v(TAG, "    Class=" + s.info.name);
8399            }
8400            final int NI = s.intents.size();
8401            int j;
8402            for (j=0; j<NI; j++) {
8403                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8404                if (DEBUG_SHOW_INFO) {
8405                    Log.v(TAG, "    IntentFilter:");
8406                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8407                }
8408                removeFilter(intent);
8409            }
8410        }
8411
8412        @Override
8413        protected boolean allowFilterResult(
8414                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8415            ServiceInfo filterSi = filter.service.info;
8416            for (int i=dest.size()-1; i>=0; i--) {
8417                ServiceInfo destAi = dest.get(i).serviceInfo;
8418                if (destAi.name == filterSi.name
8419                        && destAi.packageName == filterSi.packageName) {
8420                    return false;
8421                }
8422            }
8423            return true;
8424        }
8425
8426        @Override
8427        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8428            return new PackageParser.ServiceIntentInfo[size];
8429        }
8430
8431        @Override
8432        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8433            if (!sUserManager.exists(userId)) return true;
8434            PackageParser.Package p = filter.service.owner;
8435            if (p != null) {
8436                PackageSetting ps = (PackageSetting)p.mExtras;
8437                if (ps != null) {
8438                    // System apps are never considered stopped for purposes of
8439                    // filtering, because there may be no way for the user to
8440                    // actually re-launch them.
8441                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8442                            && ps.getStopped(userId);
8443                }
8444            }
8445            return false;
8446        }
8447
8448        @Override
8449        protected boolean isPackageForFilter(String packageName,
8450                PackageParser.ServiceIntentInfo info) {
8451            return packageName.equals(info.service.owner.packageName);
8452        }
8453
8454        @Override
8455        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8456                int match, int userId) {
8457            if (!sUserManager.exists(userId)) return null;
8458            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8459            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8460                return null;
8461            }
8462            final PackageParser.Service service = info.service;
8463            if (mSafeMode && (service.info.applicationInfo.flags
8464                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8465                return null;
8466            }
8467            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8468            if (ps == null) {
8469                return null;
8470            }
8471            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8472                    ps.readUserState(userId), userId);
8473            if (si == null) {
8474                return null;
8475            }
8476            final ResolveInfo res = new ResolveInfo();
8477            res.serviceInfo = si;
8478            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8479                res.filter = filter;
8480            }
8481            res.priority = info.getPriority();
8482            res.preferredOrder = service.owner.mPreferredOrder;
8483            res.match = match;
8484            res.isDefault = info.hasDefault;
8485            res.labelRes = info.labelRes;
8486            res.nonLocalizedLabel = info.nonLocalizedLabel;
8487            res.icon = info.icon;
8488            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8489            return res;
8490        }
8491
8492        @Override
8493        protected void sortResults(List<ResolveInfo> results) {
8494            Collections.sort(results, mResolvePrioritySorter);
8495        }
8496
8497        @Override
8498        protected void dumpFilter(PrintWriter out, String prefix,
8499                PackageParser.ServiceIntentInfo filter) {
8500            out.print(prefix); out.print(
8501                    Integer.toHexString(System.identityHashCode(filter.service)));
8502                    out.print(' ');
8503                    filter.service.printComponentShortName(out);
8504                    out.print(" filter ");
8505                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8506        }
8507
8508        @Override
8509        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8510            return filter.service;
8511        }
8512
8513        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8514            PackageParser.Service service = (PackageParser.Service)label;
8515            out.print(prefix); out.print(
8516                    Integer.toHexString(System.identityHashCode(service)));
8517                    out.print(' ');
8518                    service.printComponentShortName(out);
8519            if (count > 1) {
8520                out.print(" ("); out.print(count); out.print(" filters)");
8521            }
8522            out.println();
8523        }
8524
8525//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8526//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8527//            final List<ResolveInfo> retList = Lists.newArrayList();
8528//            while (i.hasNext()) {
8529//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8530//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8531//                    retList.add(resolveInfo);
8532//                }
8533//            }
8534//            return retList;
8535//        }
8536
8537        // Keys are String (activity class name), values are Activity.
8538        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8539                = new ArrayMap<ComponentName, PackageParser.Service>();
8540        private int mFlags;
8541    };
8542
8543    private final class ProviderIntentResolver
8544            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8545        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8546                boolean defaultOnly, int userId) {
8547            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8548            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8549        }
8550
8551        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8552                int userId) {
8553            if (!sUserManager.exists(userId))
8554                return null;
8555            mFlags = flags;
8556            return super.queryIntent(intent, resolvedType,
8557                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8558        }
8559
8560        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8561                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8562            if (!sUserManager.exists(userId))
8563                return null;
8564            if (packageProviders == null) {
8565                return null;
8566            }
8567            mFlags = flags;
8568            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8569            final int N = packageProviders.size();
8570            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8571                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8572
8573            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8574            for (int i = 0; i < N; ++i) {
8575                intentFilters = packageProviders.get(i).intents;
8576                if (intentFilters != null && intentFilters.size() > 0) {
8577                    PackageParser.ProviderIntentInfo[] array =
8578                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8579                    intentFilters.toArray(array);
8580                    listCut.add(array);
8581                }
8582            }
8583            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8584        }
8585
8586        public final void addProvider(PackageParser.Provider p) {
8587            if (mProviders.containsKey(p.getComponentName())) {
8588                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8589                return;
8590            }
8591
8592            mProviders.put(p.getComponentName(), p);
8593            if (DEBUG_SHOW_INFO) {
8594                Log.v(TAG, "  "
8595                        + (p.info.nonLocalizedLabel != null
8596                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8597                Log.v(TAG, "    Class=" + p.info.name);
8598            }
8599            final int NI = p.intents.size();
8600            int j;
8601            for (j = 0; j < NI; j++) {
8602                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8603                if (DEBUG_SHOW_INFO) {
8604                    Log.v(TAG, "    IntentFilter:");
8605                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8606                }
8607                if (!intent.debugCheck()) {
8608                    Log.w(TAG, "==> For Provider " + p.info.name);
8609                }
8610                addFilter(intent);
8611            }
8612        }
8613
8614        public final void removeProvider(PackageParser.Provider p) {
8615            mProviders.remove(p.getComponentName());
8616            if (DEBUG_SHOW_INFO) {
8617                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8618                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8619                Log.v(TAG, "    Class=" + p.info.name);
8620            }
8621            final int NI = p.intents.size();
8622            int j;
8623            for (j = 0; j < NI; j++) {
8624                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8625                if (DEBUG_SHOW_INFO) {
8626                    Log.v(TAG, "    IntentFilter:");
8627                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8628                }
8629                removeFilter(intent);
8630            }
8631        }
8632
8633        @Override
8634        protected boolean allowFilterResult(
8635                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8636            ProviderInfo filterPi = filter.provider.info;
8637            for (int i = dest.size() - 1; i >= 0; i--) {
8638                ProviderInfo destPi = dest.get(i).providerInfo;
8639                if (destPi.name == filterPi.name
8640                        && destPi.packageName == filterPi.packageName) {
8641                    return false;
8642                }
8643            }
8644            return true;
8645        }
8646
8647        @Override
8648        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8649            return new PackageParser.ProviderIntentInfo[size];
8650        }
8651
8652        @Override
8653        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8654            if (!sUserManager.exists(userId))
8655                return true;
8656            PackageParser.Package p = filter.provider.owner;
8657            if (p != null) {
8658                PackageSetting ps = (PackageSetting) p.mExtras;
8659                if (ps != null) {
8660                    // System apps are never considered stopped for purposes of
8661                    // filtering, because there may be no way for the user to
8662                    // actually re-launch them.
8663                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8664                            && ps.getStopped(userId);
8665                }
8666            }
8667            return false;
8668        }
8669
8670        @Override
8671        protected boolean isPackageForFilter(String packageName,
8672                PackageParser.ProviderIntentInfo info) {
8673            return packageName.equals(info.provider.owner.packageName);
8674        }
8675
8676        @Override
8677        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8678                int match, int userId) {
8679            if (!sUserManager.exists(userId))
8680                return null;
8681            final PackageParser.ProviderIntentInfo info = filter;
8682            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8683                return null;
8684            }
8685            final PackageParser.Provider provider = info.provider;
8686            if (mSafeMode && (provider.info.applicationInfo.flags
8687                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8688                return null;
8689            }
8690            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8691            if (ps == null) {
8692                return null;
8693            }
8694            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8695                    ps.readUserState(userId), userId);
8696            if (pi == null) {
8697                return null;
8698            }
8699            final ResolveInfo res = new ResolveInfo();
8700            res.providerInfo = pi;
8701            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8702                res.filter = filter;
8703            }
8704            res.priority = info.getPriority();
8705            res.preferredOrder = provider.owner.mPreferredOrder;
8706            res.match = match;
8707            res.isDefault = info.hasDefault;
8708            res.labelRes = info.labelRes;
8709            res.nonLocalizedLabel = info.nonLocalizedLabel;
8710            res.icon = info.icon;
8711            res.system = res.providerInfo.applicationInfo.isSystemApp();
8712            return res;
8713        }
8714
8715        @Override
8716        protected void sortResults(List<ResolveInfo> results) {
8717            Collections.sort(results, mResolvePrioritySorter);
8718        }
8719
8720        @Override
8721        protected void dumpFilter(PrintWriter out, String prefix,
8722                PackageParser.ProviderIntentInfo filter) {
8723            out.print(prefix);
8724            out.print(
8725                    Integer.toHexString(System.identityHashCode(filter.provider)));
8726            out.print(' ');
8727            filter.provider.printComponentShortName(out);
8728            out.print(" filter ");
8729            out.println(Integer.toHexString(System.identityHashCode(filter)));
8730        }
8731
8732        @Override
8733        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8734            return filter.provider;
8735        }
8736
8737        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8738            PackageParser.Provider provider = (PackageParser.Provider)label;
8739            out.print(prefix); out.print(
8740                    Integer.toHexString(System.identityHashCode(provider)));
8741                    out.print(' ');
8742                    provider.printComponentShortName(out);
8743            if (count > 1) {
8744                out.print(" ("); out.print(count); out.print(" filters)");
8745            }
8746            out.println();
8747        }
8748
8749        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8750                = new ArrayMap<ComponentName, PackageParser.Provider>();
8751        private int mFlags;
8752    };
8753
8754    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8755            new Comparator<ResolveInfo>() {
8756        public int compare(ResolveInfo r1, ResolveInfo r2) {
8757            int v1 = r1.priority;
8758            int v2 = r2.priority;
8759            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8760            if (v1 != v2) {
8761                return (v1 > v2) ? -1 : 1;
8762            }
8763            v1 = r1.preferredOrder;
8764            v2 = r2.preferredOrder;
8765            if (v1 != v2) {
8766                return (v1 > v2) ? -1 : 1;
8767            }
8768            if (r1.isDefault != r2.isDefault) {
8769                return r1.isDefault ? -1 : 1;
8770            }
8771            v1 = r1.match;
8772            v2 = r2.match;
8773            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8774            if (v1 != v2) {
8775                return (v1 > v2) ? -1 : 1;
8776            }
8777            if (r1.system != r2.system) {
8778                return r1.system ? -1 : 1;
8779            }
8780            return 0;
8781        }
8782    };
8783
8784    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8785            new Comparator<ProviderInfo>() {
8786        public int compare(ProviderInfo p1, ProviderInfo p2) {
8787            final int v1 = p1.initOrder;
8788            final int v2 = p2.initOrder;
8789            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8790        }
8791    };
8792
8793    final void sendPackageBroadcast(final String action, final String pkg,
8794            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
8795            final int[] userIds) {
8796        mHandler.post(new Runnable() {
8797            @Override
8798            public void run() {
8799                try {
8800                    final IActivityManager am = ActivityManagerNative.getDefault();
8801                    if (am == null) return;
8802                    final int[] resolvedUserIds;
8803                    if (userIds == null) {
8804                        resolvedUserIds = am.getRunningUserIds();
8805                    } else {
8806                        resolvedUserIds = userIds;
8807                    }
8808                    for (int id : resolvedUserIds) {
8809                        final Intent intent = new Intent(action,
8810                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
8811                        if (extras != null) {
8812                            intent.putExtras(extras);
8813                        }
8814                        if (targetPkg != null) {
8815                            intent.setPackage(targetPkg);
8816                        }
8817                        // Modify the UID when posting to other users
8818                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8819                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
8820                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8821                            intent.putExtra(Intent.EXTRA_UID, uid);
8822                        }
8823                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8824                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8825                        if (DEBUG_BROADCASTS) {
8826                            RuntimeException here = new RuntimeException("here");
8827                            here.fillInStackTrace();
8828                            Slog.d(TAG, "Sending to user " + id + ": "
8829                                    + intent.toShortString(false, true, false, false)
8830                                    + " " + intent.getExtras(), here);
8831                        }
8832                        am.broadcastIntent(null, intent, null, finishedReceiver,
8833                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
8834                                null, finishedReceiver != null, false, id);
8835                    }
8836                } catch (RemoteException ex) {
8837                }
8838            }
8839        });
8840    }
8841
8842    /**
8843     * Check if the external storage media is available. This is true if there
8844     * is a mounted external storage medium or if the external storage is
8845     * emulated.
8846     */
8847    private boolean isExternalMediaAvailable() {
8848        return mMediaMounted || Environment.isExternalStorageEmulated();
8849    }
8850
8851    @Override
8852    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8853        // writer
8854        synchronized (mPackages) {
8855            if (!isExternalMediaAvailable()) {
8856                // If the external storage is no longer mounted at this point,
8857                // the caller may not have been able to delete all of this
8858                // packages files and can not delete any more.  Bail.
8859                return null;
8860            }
8861            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8862            if (lastPackage != null) {
8863                pkgs.remove(lastPackage);
8864            }
8865            if (pkgs.size() > 0) {
8866                return pkgs.get(0);
8867            }
8868        }
8869        return null;
8870    }
8871
8872    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8873        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8874                userId, andCode ? 1 : 0, packageName);
8875        if (mSystemReady) {
8876            msg.sendToTarget();
8877        } else {
8878            if (mPostSystemReadyMessages == null) {
8879                mPostSystemReadyMessages = new ArrayList<>();
8880            }
8881            mPostSystemReadyMessages.add(msg);
8882        }
8883    }
8884
8885    void startCleaningPackages() {
8886        // reader
8887        synchronized (mPackages) {
8888            if (!isExternalMediaAvailable()) {
8889                return;
8890            }
8891            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8892                return;
8893            }
8894        }
8895        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8896        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8897        IActivityManager am = ActivityManagerNative.getDefault();
8898        if (am != null) {
8899            try {
8900                am.startService(null, intent, null, UserHandle.USER_OWNER);
8901            } catch (RemoteException e) {
8902            }
8903        }
8904    }
8905
8906    @Override
8907    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8908            int installFlags, String installerPackageName, VerificationParams verificationParams,
8909            String packageAbiOverride) {
8910        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
8911                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
8912    }
8913
8914    @Override
8915    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8916            int installFlags, String installerPackageName, VerificationParams verificationParams,
8917            String packageAbiOverride, int userId) {
8918        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8919
8920        final int callingUid = Binder.getCallingUid();
8921        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8922
8923        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8924            try {
8925                if (observer != null) {
8926                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8927                }
8928            } catch (RemoteException re) {
8929            }
8930            return;
8931        }
8932
8933        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8934            installFlags |= PackageManager.INSTALL_FROM_ADB;
8935
8936        } else {
8937            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8938            // about installerPackageName.
8939
8940            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8941            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8942        }
8943
8944        UserHandle user;
8945        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8946            user = UserHandle.ALL;
8947        } else {
8948            user = new UserHandle(userId);
8949        }
8950
8951        // Only system components can circumvent runtime permissions when installing.
8952        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
8953                && mContext.checkCallingOrSelfPermission(Manifest.permission
8954                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
8955            throw new SecurityException("You need the "
8956                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
8957                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
8958        }
8959
8960        verificationParams.setInstallerUid(callingUid);
8961
8962        final File originFile = new File(originPath);
8963        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8964
8965        final Message msg = mHandler.obtainMessage(INIT_COPY);
8966        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
8967                null, verificationParams, user, packageAbiOverride);
8968        mHandler.sendMessage(msg);
8969    }
8970
8971    void installStage(String packageName, File stagedDir, String stagedCid,
8972            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8973            String installerPackageName, int installerUid, UserHandle user) {
8974        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8975                params.referrerUri, installerUid, null);
8976
8977        final OriginInfo origin;
8978        if (stagedDir != null) {
8979            origin = OriginInfo.fromStagedFile(stagedDir);
8980        } else {
8981            origin = OriginInfo.fromStagedContainer(stagedCid);
8982        }
8983
8984        final Message msg = mHandler.obtainMessage(INIT_COPY);
8985        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
8986                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
8987        mHandler.sendMessage(msg);
8988    }
8989
8990    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8991        Bundle extras = new Bundle(1);
8992        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8993
8994        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8995                packageName, extras, null, null, new int[] {userId});
8996        try {
8997            IActivityManager am = ActivityManagerNative.getDefault();
8998            final boolean isSystem =
8999                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9000            if (isSystem && am.isUserRunning(userId, false)) {
9001                // The just-installed/enabled app is bundled on the system, so presumed
9002                // to be able to run automatically without needing an explicit launch.
9003                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9004                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9005                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9006                        .setPackage(packageName);
9007                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9008                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9009            }
9010        } catch (RemoteException e) {
9011            // shouldn't happen
9012            Slog.w(TAG, "Unable to bootstrap installed package", e);
9013        }
9014    }
9015
9016    @Override
9017    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9018            int userId) {
9019        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9020        PackageSetting pkgSetting;
9021        final int uid = Binder.getCallingUid();
9022        enforceCrossUserPermission(uid, userId, true, true,
9023                "setApplicationHiddenSetting for user " + userId);
9024
9025        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9026            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9027            return false;
9028        }
9029
9030        long callingId = Binder.clearCallingIdentity();
9031        try {
9032            boolean sendAdded = false;
9033            boolean sendRemoved = false;
9034            // writer
9035            synchronized (mPackages) {
9036                pkgSetting = mSettings.mPackages.get(packageName);
9037                if (pkgSetting == null) {
9038                    return false;
9039                }
9040                if (pkgSetting.getHidden(userId) != hidden) {
9041                    pkgSetting.setHidden(hidden, userId);
9042                    mSettings.writePackageRestrictionsLPr(userId);
9043                    if (hidden) {
9044                        sendRemoved = true;
9045                    } else {
9046                        sendAdded = true;
9047                    }
9048                }
9049            }
9050            if (sendAdded) {
9051                sendPackageAddedForUser(packageName, pkgSetting, userId);
9052                return true;
9053            }
9054            if (sendRemoved) {
9055                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9056                        "hiding pkg");
9057                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9058            }
9059        } finally {
9060            Binder.restoreCallingIdentity(callingId);
9061        }
9062        return false;
9063    }
9064
9065    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9066            int userId) {
9067        final PackageRemovedInfo info = new PackageRemovedInfo();
9068        info.removedPackage = packageName;
9069        info.removedUsers = new int[] {userId};
9070        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9071        info.sendBroadcast(false, false, false);
9072    }
9073
9074    /**
9075     * Returns true if application is not found or there was an error. Otherwise it returns
9076     * the hidden state of the package for the given user.
9077     */
9078    @Override
9079    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9080        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9081        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9082                false, "getApplicationHidden for user " + userId);
9083        PackageSetting pkgSetting;
9084        long callingId = Binder.clearCallingIdentity();
9085        try {
9086            // writer
9087            synchronized (mPackages) {
9088                pkgSetting = mSettings.mPackages.get(packageName);
9089                if (pkgSetting == null) {
9090                    return true;
9091                }
9092                return pkgSetting.getHidden(userId);
9093            }
9094        } finally {
9095            Binder.restoreCallingIdentity(callingId);
9096        }
9097    }
9098
9099    /**
9100     * @hide
9101     */
9102    @Override
9103    public int installExistingPackageAsUser(String packageName, int userId) {
9104        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9105                null);
9106        PackageSetting pkgSetting;
9107        final int uid = Binder.getCallingUid();
9108        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9109                + userId);
9110        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9111            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9112        }
9113
9114        long callingId = Binder.clearCallingIdentity();
9115        try {
9116            boolean sendAdded = false;
9117
9118            // writer
9119            synchronized (mPackages) {
9120                pkgSetting = mSettings.mPackages.get(packageName);
9121                if (pkgSetting == null) {
9122                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9123                }
9124                if (!pkgSetting.getInstalled(userId)) {
9125                    pkgSetting.setInstalled(true, userId);
9126                    pkgSetting.setHidden(false, userId);
9127                    mSettings.writePackageRestrictionsLPr(userId);
9128                    sendAdded = true;
9129                }
9130            }
9131
9132            if (sendAdded) {
9133                sendPackageAddedForUser(packageName, pkgSetting, userId);
9134            }
9135        } finally {
9136            Binder.restoreCallingIdentity(callingId);
9137        }
9138
9139        return PackageManager.INSTALL_SUCCEEDED;
9140    }
9141
9142    boolean isUserRestricted(int userId, String restrictionKey) {
9143        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9144        if (restrictions.getBoolean(restrictionKey, false)) {
9145            Log.w(TAG, "User is restricted: " + restrictionKey);
9146            return true;
9147        }
9148        return false;
9149    }
9150
9151    @Override
9152    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9153        mContext.enforceCallingOrSelfPermission(
9154                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9155                "Only package verification agents can verify applications");
9156
9157        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9158        final PackageVerificationResponse response = new PackageVerificationResponse(
9159                verificationCode, Binder.getCallingUid());
9160        msg.arg1 = id;
9161        msg.obj = response;
9162        mHandler.sendMessage(msg);
9163    }
9164
9165    @Override
9166    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9167            long millisecondsToDelay) {
9168        mContext.enforceCallingOrSelfPermission(
9169                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9170                "Only package verification agents can extend verification timeouts");
9171
9172        final PackageVerificationState state = mPendingVerification.get(id);
9173        final PackageVerificationResponse response = new PackageVerificationResponse(
9174                verificationCodeAtTimeout, Binder.getCallingUid());
9175
9176        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9177            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9178        }
9179        if (millisecondsToDelay < 0) {
9180            millisecondsToDelay = 0;
9181        }
9182        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9183                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9184            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9185        }
9186
9187        if ((state != null) && !state.timeoutExtended()) {
9188            state.extendTimeout();
9189
9190            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9191            msg.arg1 = id;
9192            msg.obj = response;
9193            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9194        }
9195    }
9196
9197    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9198            int verificationCode, UserHandle user) {
9199        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9200        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9201        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9202        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9203        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9204
9205        mContext.sendBroadcastAsUser(intent, user,
9206                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9207    }
9208
9209    private ComponentName matchComponentForVerifier(String packageName,
9210            List<ResolveInfo> receivers) {
9211        ActivityInfo targetReceiver = null;
9212
9213        final int NR = receivers.size();
9214        for (int i = 0; i < NR; i++) {
9215            final ResolveInfo info = receivers.get(i);
9216            if (info.activityInfo == null) {
9217                continue;
9218            }
9219
9220            if (packageName.equals(info.activityInfo.packageName)) {
9221                targetReceiver = info.activityInfo;
9222                break;
9223            }
9224        }
9225
9226        if (targetReceiver == null) {
9227            return null;
9228        }
9229
9230        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9231    }
9232
9233    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9234            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9235        if (pkgInfo.verifiers.length == 0) {
9236            return null;
9237        }
9238
9239        final int N = pkgInfo.verifiers.length;
9240        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9241        for (int i = 0; i < N; i++) {
9242            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9243
9244            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9245                    receivers);
9246            if (comp == null) {
9247                continue;
9248            }
9249
9250            final int verifierUid = getUidForVerifier(verifierInfo);
9251            if (verifierUid == -1) {
9252                continue;
9253            }
9254
9255            if (DEBUG_VERIFY) {
9256                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9257                        + " with the correct signature");
9258            }
9259            sufficientVerifiers.add(comp);
9260            verificationState.addSufficientVerifier(verifierUid);
9261        }
9262
9263        return sufficientVerifiers;
9264    }
9265
9266    private int getUidForVerifier(VerifierInfo verifierInfo) {
9267        synchronized (mPackages) {
9268            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9269            if (pkg == null) {
9270                return -1;
9271            } else if (pkg.mSignatures.length != 1) {
9272                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9273                        + " has more than one signature; ignoring");
9274                return -1;
9275            }
9276
9277            /*
9278             * If the public key of the package's signature does not match
9279             * our expected public key, then this is a different package and
9280             * we should skip.
9281             */
9282
9283            final byte[] expectedPublicKey;
9284            try {
9285                final Signature verifierSig = pkg.mSignatures[0];
9286                final PublicKey publicKey = verifierSig.getPublicKey();
9287                expectedPublicKey = publicKey.getEncoded();
9288            } catch (CertificateException e) {
9289                return -1;
9290            }
9291
9292            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9293
9294            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9295                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9296                        + " does not have the expected public key; ignoring");
9297                return -1;
9298            }
9299
9300            return pkg.applicationInfo.uid;
9301        }
9302    }
9303
9304    @Override
9305    public void finishPackageInstall(int token) {
9306        enforceSystemOrRoot("Only the system is allowed to finish installs");
9307
9308        if (DEBUG_INSTALL) {
9309            Slog.v(TAG, "BM finishing package install for " + token);
9310        }
9311
9312        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9313        mHandler.sendMessage(msg);
9314    }
9315
9316    /**
9317     * Get the verification agent timeout.
9318     *
9319     * @return verification timeout in milliseconds
9320     */
9321    private long getVerificationTimeout() {
9322        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9323                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9324                DEFAULT_VERIFICATION_TIMEOUT);
9325    }
9326
9327    /**
9328     * Get the default verification agent response code.
9329     *
9330     * @return default verification response code
9331     */
9332    private int getDefaultVerificationResponse() {
9333        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9334                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9335                DEFAULT_VERIFICATION_RESPONSE);
9336    }
9337
9338    /**
9339     * Check whether or not package verification has been enabled.
9340     *
9341     * @return true if verification should be performed
9342     */
9343    private boolean isVerificationEnabled(int userId, int installFlags) {
9344        if (!DEFAULT_VERIFY_ENABLE) {
9345            return false;
9346        }
9347
9348        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9349
9350        // Check if installing from ADB
9351        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9352            // Do not run verification in a test harness environment
9353            if (ActivityManager.isRunningInTestHarness()) {
9354                return false;
9355            }
9356            if (ensureVerifyAppsEnabled) {
9357                return true;
9358            }
9359            // Check if the developer does not want package verification for ADB installs
9360            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9361                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9362                return false;
9363            }
9364        }
9365
9366        if (ensureVerifyAppsEnabled) {
9367            return true;
9368        }
9369
9370        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9371                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9372    }
9373
9374    @Override
9375    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9376            throws RemoteException {
9377        mContext.enforceCallingOrSelfPermission(
9378                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9379                "Only intentfilter verification agents can verify applications");
9380
9381        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9382        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9383                Binder.getCallingUid(), verificationCode, failedDomains);
9384        msg.arg1 = id;
9385        msg.obj = response;
9386        mHandler.sendMessage(msg);
9387    }
9388
9389    @Override
9390    public int getIntentVerificationStatus(String packageName, int userId) {
9391        synchronized (mPackages) {
9392            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9393        }
9394    }
9395
9396    @Override
9397    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9398        boolean result = false;
9399        synchronized (mPackages) {
9400            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9401        }
9402        if (result) {
9403            scheduleWritePackageRestrictionsLocked(userId);
9404        }
9405        return result;
9406    }
9407
9408    @Override
9409    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9410        synchronized (mPackages) {
9411            return mSettings.getIntentFilterVerificationsLPr(packageName);
9412        }
9413    }
9414
9415    @Override
9416    public List<IntentFilter> getAllIntentFilters(String packageName) {
9417        if (TextUtils.isEmpty(packageName)) {
9418            return Collections.<IntentFilter>emptyList();
9419        }
9420        synchronized (mPackages) {
9421            PackageParser.Package pkg = mPackages.get(packageName);
9422            if (pkg == null || pkg.activities == null) {
9423                return Collections.<IntentFilter>emptyList();
9424            }
9425            final int count = pkg.activities.size();
9426            ArrayList<IntentFilter> result = new ArrayList<>();
9427            for (int n=0; n<count; n++) {
9428                PackageParser.Activity activity = pkg.activities.get(n);
9429                if (activity.intents != null || activity.intents.size() > 0) {
9430                    result.addAll(activity.intents);
9431                }
9432            }
9433            return result;
9434        }
9435    }
9436
9437    @Override
9438    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9439        synchronized (mPackages) {
9440            boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9441            if (packageName != null) {
9442                result |= updateIntentVerificationStatus(packageName,
9443                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9444                        UserHandle.myUserId());
9445            }
9446            return result;
9447        }
9448    }
9449
9450    @Override
9451    public String getDefaultBrowserPackageName(int userId) {
9452        synchronized (mPackages) {
9453            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9454        }
9455    }
9456
9457    /**
9458     * Get the "allow unknown sources" setting.
9459     *
9460     * @return the current "allow unknown sources" setting
9461     */
9462    private int getUnknownSourcesSettings() {
9463        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9464                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9465                -1);
9466    }
9467
9468    @Override
9469    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9470        final int uid = Binder.getCallingUid();
9471        // writer
9472        synchronized (mPackages) {
9473            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9474            if (targetPackageSetting == null) {
9475                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9476            }
9477
9478            PackageSetting installerPackageSetting;
9479            if (installerPackageName != null) {
9480                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9481                if (installerPackageSetting == null) {
9482                    throw new IllegalArgumentException("Unknown installer package: "
9483                            + installerPackageName);
9484                }
9485            } else {
9486                installerPackageSetting = null;
9487            }
9488
9489            Signature[] callerSignature;
9490            Object obj = mSettings.getUserIdLPr(uid);
9491            if (obj != null) {
9492                if (obj instanceof SharedUserSetting) {
9493                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9494                } else if (obj instanceof PackageSetting) {
9495                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9496                } else {
9497                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9498                }
9499            } else {
9500                throw new SecurityException("Unknown calling uid " + uid);
9501            }
9502
9503            // Verify: can't set installerPackageName to a package that is
9504            // not signed with the same cert as the caller.
9505            if (installerPackageSetting != null) {
9506                if (compareSignatures(callerSignature,
9507                        installerPackageSetting.signatures.mSignatures)
9508                        != PackageManager.SIGNATURE_MATCH) {
9509                    throw new SecurityException(
9510                            "Caller does not have same cert as new installer package "
9511                            + installerPackageName);
9512                }
9513            }
9514
9515            // Verify: if target already has an installer package, it must
9516            // be signed with the same cert as the caller.
9517            if (targetPackageSetting.installerPackageName != null) {
9518                PackageSetting setting = mSettings.mPackages.get(
9519                        targetPackageSetting.installerPackageName);
9520                // If the currently set package isn't valid, then it's always
9521                // okay to change it.
9522                if (setting != null) {
9523                    if (compareSignatures(callerSignature,
9524                            setting.signatures.mSignatures)
9525                            != PackageManager.SIGNATURE_MATCH) {
9526                        throw new SecurityException(
9527                                "Caller does not have same cert as old installer package "
9528                                + targetPackageSetting.installerPackageName);
9529                    }
9530                }
9531            }
9532
9533            // Okay!
9534            targetPackageSetting.installerPackageName = installerPackageName;
9535            scheduleWriteSettingsLocked();
9536        }
9537    }
9538
9539    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9540        // Queue up an async operation since the package installation may take a little while.
9541        mHandler.post(new Runnable() {
9542            public void run() {
9543                mHandler.removeCallbacks(this);
9544                 // Result object to be returned
9545                PackageInstalledInfo res = new PackageInstalledInfo();
9546                res.returnCode = currentStatus;
9547                res.uid = -1;
9548                res.pkg = null;
9549                res.removedInfo = new PackageRemovedInfo();
9550                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9551                    args.doPreInstall(res.returnCode);
9552                    synchronized (mInstallLock) {
9553                        installPackageLI(args, res);
9554                    }
9555                    args.doPostInstall(res.returnCode, res.uid);
9556                }
9557
9558                // A restore should be performed at this point if (a) the install
9559                // succeeded, (b) the operation is not an update, and (c) the new
9560                // package has not opted out of backup participation.
9561                final boolean update = res.removedInfo.removedPackage != null;
9562                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9563                boolean doRestore = !update
9564                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9565
9566                // Set up the post-install work request bookkeeping.  This will be used
9567                // and cleaned up by the post-install event handling regardless of whether
9568                // there's a restore pass performed.  Token values are >= 1.
9569                int token;
9570                if (mNextInstallToken < 0) mNextInstallToken = 1;
9571                token = mNextInstallToken++;
9572
9573                PostInstallData data = new PostInstallData(args, res);
9574                mRunningInstalls.put(token, data);
9575                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9576
9577                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9578                    // Pass responsibility to the Backup Manager.  It will perform a
9579                    // restore if appropriate, then pass responsibility back to the
9580                    // Package Manager to run the post-install observer callbacks
9581                    // and broadcasts.
9582                    IBackupManager bm = IBackupManager.Stub.asInterface(
9583                            ServiceManager.getService(Context.BACKUP_SERVICE));
9584                    if (bm != null) {
9585                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9586                                + " to BM for possible restore");
9587                        try {
9588                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9589                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9590                            } else {
9591                                doRestore = false;
9592                            }
9593                        } catch (RemoteException e) {
9594                            // can't happen; the backup manager is local
9595                        } catch (Exception e) {
9596                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9597                            doRestore = false;
9598                        }
9599                    } else {
9600                        Slog.e(TAG, "Backup Manager not found!");
9601                        doRestore = false;
9602                    }
9603                }
9604
9605                if (!doRestore) {
9606                    // No restore possible, or the Backup Manager was mysteriously not
9607                    // available -- just fire the post-install work request directly.
9608                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9609                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9610                    mHandler.sendMessage(msg);
9611                }
9612            }
9613        });
9614    }
9615
9616    private abstract class HandlerParams {
9617        private static final int MAX_RETRIES = 4;
9618
9619        /**
9620         * Number of times startCopy() has been attempted and had a non-fatal
9621         * error.
9622         */
9623        private int mRetries = 0;
9624
9625        /** User handle for the user requesting the information or installation. */
9626        private final UserHandle mUser;
9627
9628        HandlerParams(UserHandle user) {
9629            mUser = user;
9630        }
9631
9632        UserHandle getUser() {
9633            return mUser;
9634        }
9635
9636        final boolean startCopy() {
9637            boolean res;
9638            try {
9639                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9640
9641                if (++mRetries > MAX_RETRIES) {
9642                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9643                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9644                    handleServiceError();
9645                    return false;
9646                } else {
9647                    handleStartCopy();
9648                    res = true;
9649                }
9650            } catch (RemoteException e) {
9651                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9652                mHandler.sendEmptyMessage(MCS_RECONNECT);
9653                res = false;
9654            }
9655            handleReturnCode();
9656            return res;
9657        }
9658
9659        final void serviceError() {
9660            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9661            handleServiceError();
9662            handleReturnCode();
9663        }
9664
9665        abstract void handleStartCopy() throws RemoteException;
9666        abstract void handleServiceError();
9667        abstract void handleReturnCode();
9668    }
9669
9670    class MeasureParams extends HandlerParams {
9671        private final PackageStats mStats;
9672        private boolean mSuccess;
9673
9674        private final IPackageStatsObserver mObserver;
9675
9676        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9677            super(new UserHandle(stats.userHandle));
9678            mObserver = observer;
9679            mStats = stats;
9680        }
9681
9682        @Override
9683        public String toString() {
9684            return "MeasureParams{"
9685                + Integer.toHexString(System.identityHashCode(this))
9686                + " " + mStats.packageName + "}";
9687        }
9688
9689        @Override
9690        void handleStartCopy() throws RemoteException {
9691            synchronized (mInstallLock) {
9692                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9693            }
9694
9695            if (mSuccess) {
9696                final boolean mounted;
9697                if (Environment.isExternalStorageEmulated()) {
9698                    mounted = true;
9699                } else {
9700                    final String status = Environment.getExternalStorageState();
9701                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9702                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9703                }
9704
9705                if (mounted) {
9706                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9707
9708                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9709                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9710
9711                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9712                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9713
9714                    // Always subtract cache size, since it's a subdirectory
9715                    mStats.externalDataSize -= mStats.externalCacheSize;
9716
9717                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9718                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9719
9720                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9721                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9722                }
9723            }
9724        }
9725
9726        @Override
9727        void handleReturnCode() {
9728            if (mObserver != null) {
9729                try {
9730                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9731                } catch (RemoteException e) {
9732                    Slog.i(TAG, "Observer no longer exists.");
9733                }
9734            }
9735        }
9736
9737        @Override
9738        void handleServiceError() {
9739            Slog.e(TAG, "Could not measure application " + mStats.packageName
9740                            + " external storage");
9741        }
9742    }
9743
9744    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9745            throws RemoteException {
9746        long result = 0;
9747        for (File path : paths) {
9748            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9749        }
9750        return result;
9751    }
9752
9753    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9754        for (File path : paths) {
9755            try {
9756                mcs.clearDirectory(path.getAbsolutePath());
9757            } catch (RemoteException e) {
9758            }
9759        }
9760    }
9761
9762    static class OriginInfo {
9763        /**
9764         * Location where install is coming from, before it has been
9765         * copied/renamed into place. This could be a single monolithic APK
9766         * file, or a cluster directory. This location may be untrusted.
9767         */
9768        final File file;
9769        final String cid;
9770
9771        /**
9772         * Flag indicating that {@link #file} or {@link #cid} has already been
9773         * staged, meaning downstream users don't need to defensively copy the
9774         * contents.
9775         */
9776        final boolean staged;
9777
9778        /**
9779         * Flag indicating that {@link #file} or {@link #cid} is an already
9780         * installed app that is being moved.
9781         */
9782        final boolean existing;
9783
9784        final String resolvedPath;
9785        final File resolvedFile;
9786
9787        static OriginInfo fromNothing() {
9788            return new OriginInfo(null, null, false, false);
9789        }
9790
9791        static OriginInfo fromUntrustedFile(File file) {
9792            return new OriginInfo(file, null, false, false);
9793        }
9794
9795        static OriginInfo fromExistingFile(File file) {
9796            return new OriginInfo(file, null, false, true);
9797        }
9798
9799        static OriginInfo fromStagedFile(File file) {
9800            return new OriginInfo(file, null, true, false);
9801        }
9802
9803        static OriginInfo fromStagedContainer(String cid) {
9804            return new OriginInfo(null, cid, true, false);
9805        }
9806
9807        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9808            this.file = file;
9809            this.cid = cid;
9810            this.staged = staged;
9811            this.existing = existing;
9812
9813            if (cid != null) {
9814                resolvedPath = PackageHelper.getSdDir(cid);
9815                resolvedFile = new File(resolvedPath);
9816            } else if (file != null) {
9817                resolvedPath = file.getAbsolutePath();
9818                resolvedFile = file;
9819            } else {
9820                resolvedPath = null;
9821                resolvedFile = null;
9822            }
9823        }
9824    }
9825
9826    class MoveInfo {
9827        final int moveId;
9828        final String fromUuid;
9829        final String toUuid;
9830        final String packageName;
9831        final String dataAppName;
9832        final int appId;
9833        final String seinfo;
9834
9835        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
9836                String dataAppName, int appId, String seinfo) {
9837            this.moveId = moveId;
9838            this.fromUuid = fromUuid;
9839            this.toUuid = toUuid;
9840            this.packageName = packageName;
9841            this.dataAppName = dataAppName;
9842            this.appId = appId;
9843            this.seinfo = seinfo;
9844        }
9845    }
9846
9847    class InstallParams extends HandlerParams {
9848        final OriginInfo origin;
9849        final MoveInfo move;
9850        final IPackageInstallObserver2 observer;
9851        int installFlags;
9852        final String installerPackageName;
9853        final String volumeUuid;
9854        final VerificationParams verificationParams;
9855        private InstallArgs mArgs;
9856        private int mRet;
9857        final String packageAbiOverride;
9858
9859        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
9860                int installFlags, String installerPackageName, String volumeUuid,
9861                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9862            super(user);
9863            this.origin = origin;
9864            this.move = move;
9865            this.observer = observer;
9866            this.installFlags = installFlags;
9867            this.installerPackageName = installerPackageName;
9868            this.volumeUuid = volumeUuid;
9869            this.verificationParams = verificationParams;
9870            this.packageAbiOverride = packageAbiOverride;
9871        }
9872
9873        @Override
9874        public String toString() {
9875            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9876                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9877        }
9878
9879        public ManifestDigest getManifestDigest() {
9880            if (verificationParams == null) {
9881                return null;
9882            }
9883            return verificationParams.getManifestDigest();
9884        }
9885
9886        private int installLocationPolicy(PackageInfoLite pkgLite) {
9887            String packageName = pkgLite.packageName;
9888            int installLocation = pkgLite.installLocation;
9889            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9890            // reader
9891            synchronized (mPackages) {
9892                PackageParser.Package pkg = mPackages.get(packageName);
9893                if (pkg != null) {
9894                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9895                        // Check for downgrading.
9896                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9897                            try {
9898                                checkDowngrade(pkg, pkgLite);
9899                            } catch (PackageManagerException e) {
9900                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9901                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9902                            }
9903                        }
9904                        // Check for updated system application.
9905                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9906                            if (onSd) {
9907                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9908                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9909                            }
9910                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9911                        } else {
9912                            if (onSd) {
9913                                // Install flag overrides everything.
9914                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9915                            }
9916                            // If current upgrade specifies particular preference
9917                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
9918                                // Application explicitly specified internal.
9919                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9920                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
9921                                // App explictly prefers external. Let policy decide
9922                            } else {
9923                                // Prefer previous location
9924                                if (isExternal(pkg)) {
9925                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9926                                }
9927                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9928                            }
9929                        }
9930                    } else {
9931                        // Invalid install. Return error code
9932                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
9933                    }
9934                }
9935            }
9936            // All the special cases have been taken care of.
9937            // Return result based on recommended install location.
9938            if (onSd) {
9939                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9940            }
9941            return pkgLite.recommendedInstallLocation;
9942        }
9943
9944        /*
9945         * Invoke remote method to get package information and install
9946         * location values. Override install location based on default
9947         * policy if needed and then create install arguments based
9948         * on the install location.
9949         */
9950        public void handleStartCopy() throws RemoteException {
9951            int ret = PackageManager.INSTALL_SUCCEEDED;
9952
9953            // If we're already staged, we've firmly committed to an install location
9954            if (origin.staged) {
9955                if (origin.file != null) {
9956                    installFlags |= PackageManager.INSTALL_INTERNAL;
9957                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9958                } else if (origin.cid != null) {
9959                    installFlags |= PackageManager.INSTALL_EXTERNAL;
9960                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
9961                } else {
9962                    throw new IllegalStateException("Invalid stage location");
9963                }
9964            }
9965
9966            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9967            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9968
9969            PackageInfoLite pkgLite = null;
9970
9971            if (onInt && onSd) {
9972                // Check if both bits are set.
9973                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9974                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9975            } else {
9976                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9977                        packageAbiOverride);
9978
9979                /*
9980                 * If we have too little free space, try to free cache
9981                 * before giving up.
9982                 */
9983                if (!origin.staged && pkgLite.recommendedInstallLocation
9984                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9985                    // TODO: focus freeing disk space on the target device
9986                    final StorageManager storage = StorageManager.from(mContext);
9987                    final long lowThreshold = storage.getStorageLowBytes(
9988                            Environment.getDataDirectory());
9989
9990                    final long sizeBytes = mContainerService.calculateInstalledSize(
9991                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9992
9993                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
9994                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9995                                installFlags, packageAbiOverride);
9996                    }
9997
9998                    /*
9999                     * The cache free must have deleted the file we
10000                     * downloaded to install.
10001                     *
10002                     * TODO: fix the "freeCache" call to not delete
10003                     *       the file we care about.
10004                     */
10005                    if (pkgLite.recommendedInstallLocation
10006                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10007                        pkgLite.recommendedInstallLocation
10008                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10009                    }
10010                }
10011            }
10012
10013            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10014                int loc = pkgLite.recommendedInstallLocation;
10015                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10016                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10017                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10018                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10019                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10020                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10021                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10022                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10023                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10024                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10025                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10026                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10027                } else {
10028                    // Override with defaults if needed.
10029                    loc = installLocationPolicy(pkgLite);
10030                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10031                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10032                    } else if (!onSd && !onInt) {
10033                        // Override install location with flags
10034                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10035                            // Set the flag to install on external media.
10036                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10037                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10038                        } else {
10039                            // Make sure the flag for installing on external
10040                            // media is unset
10041                            installFlags |= PackageManager.INSTALL_INTERNAL;
10042                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10043                        }
10044                    }
10045                }
10046            }
10047
10048            final InstallArgs args = createInstallArgs(this);
10049            mArgs = args;
10050
10051            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10052                 /*
10053                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10054                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10055                 */
10056                int userIdentifier = getUser().getIdentifier();
10057                if (userIdentifier == UserHandle.USER_ALL
10058                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10059                    userIdentifier = UserHandle.USER_OWNER;
10060                }
10061
10062                /*
10063                 * Determine if we have any installed package verifiers. If we
10064                 * do, then we'll defer to them to verify the packages.
10065                 */
10066                final int requiredUid = mRequiredVerifierPackage == null ? -1
10067                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10068                if (!origin.existing && requiredUid != -1
10069                        && isVerificationEnabled(userIdentifier, installFlags)) {
10070                    final Intent verification = new Intent(
10071                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10072                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10073                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10074                            PACKAGE_MIME_TYPE);
10075                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10076
10077                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10078                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10079                            0 /* TODO: Which userId? */);
10080
10081                    if (DEBUG_VERIFY) {
10082                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10083                                + verification.toString() + " with " + pkgLite.verifiers.length
10084                                + " optional verifiers");
10085                    }
10086
10087                    final int verificationId = mPendingVerificationToken++;
10088
10089                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10090
10091                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10092                            installerPackageName);
10093
10094                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10095                            installFlags);
10096
10097                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10098                            pkgLite.packageName);
10099
10100                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10101                            pkgLite.versionCode);
10102
10103                    if (verificationParams != null) {
10104                        if (verificationParams.getVerificationURI() != null) {
10105                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10106                                 verificationParams.getVerificationURI());
10107                        }
10108                        if (verificationParams.getOriginatingURI() != null) {
10109                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10110                                  verificationParams.getOriginatingURI());
10111                        }
10112                        if (verificationParams.getReferrer() != null) {
10113                            verification.putExtra(Intent.EXTRA_REFERRER,
10114                                  verificationParams.getReferrer());
10115                        }
10116                        if (verificationParams.getOriginatingUid() >= 0) {
10117                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10118                                  verificationParams.getOriginatingUid());
10119                        }
10120                        if (verificationParams.getInstallerUid() >= 0) {
10121                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10122                                  verificationParams.getInstallerUid());
10123                        }
10124                    }
10125
10126                    final PackageVerificationState verificationState = new PackageVerificationState(
10127                            requiredUid, args);
10128
10129                    mPendingVerification.append(verificationId, verificationState);
10130
10131                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10132                            receivers, verificationState);
10133
10134                    /*
10135                     * If any sufficient verifiers were listed in the package
10136                     * manifest, attempt to ask them.
10137                     */
10138                    if (sufficientVerifiers != null) {
10139                        final int N = sufficientVerifiers.size();
10140                        if (N == 0) {
10141                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10142                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10143                        } else {
10144                            for (int i = 0; i < N; i++) {
10145                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10146
10147                                final Intent sufficientIntent = new Intent(verification);
10148                                sufficientIntent.setComponent(verifierComponent);
10149
10150                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10151                            }
10152                        }
10153                    }
10154
10155                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10156                            mRequiredVerifierPackage, receivers);
10157                    if (ret == PackageManager.INSTALL_SUCCEEDED
10158                            && mRequiredVerifierPackage != null) {
10159                        /*
10160                         * Send the intent to the required verification agent,
10161                         * but only start the verification timeout after the
10162                         * target BroadcastReceivers have run.
10163                         */
10164                        verification.setComponent(requiredVerifierComponent);
10165                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10166                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10167                                new BroadcastReceiver() {
10168                                    @Override
10169                                    public void onReceive(Context context, Intent intent) {
10170                                        final Message msg = mHandler
10171                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10172                                        msg.arg1 = verificationId;
10173                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10174                                    }
10175                                }, null, 0, null, null);
10176
10177                        /*
10178                         * We don't want the copy to proceed until verification
10179                         * succeeds, so null out this field.
10180                         */
10181                        mArgs = null;
10182                    }
10183                } else {
10184                    /*
10185                     * No package verification is enabled, so immediately start
10186                     * the remote call to initiate copy using temporary file.
10187                     */
10188                    ret = args.copyApk(mContainerService, true);
10189                }
10190            }
10191
10192            mRet = ret;
10193        }
10194
10195        @Override
10196        void handleReturnCode() {
10197            // If mArgs is null, then MCS couldn't be reached. When it
10198            // reconnects, it will try again to install. At that point, this
10199            // will succeed.
10200            if (mArgs != null) {
10201                processPendingInstall(mArgs, mRet);
10202            }
10203        }
10204
10205        @Override
10206        void handleServiceError() {
10207            mArgs = createInstallArgs(this);
10208            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10209        }
10210
10211        public boolean isForwardLocked() {
10212            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10213        }
10214    }
10215
10216    /**
10217     * Used during creation of InstallArgs
10218     *
10219     * @param installFlags package installation flags
10220     * @return true if should be installed on external storage
10221     */
10222    private static boolean installOnExternalAsec(int installFlags) {
10223        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10224            return false;
10225        }
10226        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10227            return true;
10228        }
10229        return false;
10230    }
10231
10232    /**
10233     * Used during creation of InstallArgs
10234     *
10235     * @param installFlags package installation flags
10236     * @return true if should be installed as forward locked
10237     */
10238    private static boolean installForwardLocked(int installFlags) {
10239        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10240    }
10241
10242    private InstallArgs createInstallArgs(InstallParams params) {
10243        if (params.move != null) {
10244            return new MoveInstallArgs(params);
10245        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10246            return new AsecInstallArgs(params);
10247        } else {
10248            return new FileInstallArgs(params);
10249        }
10250    }
10251
10252    /**
10253     * Create args that describe an existing installed package. Typically used
10254     * when cleaning up old installs, or used as a move source.
10255     */
10256    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10257            String resourcePath, String[] instructionSets) {
10258        final boolean isInAsec;
10259        if (installOnExternalAsec(installFlags)) {
10260            /* Apps on SD card are always in ASEC containers. */
10261            isInAsec = true;
10262        } else if (installForwardLocked(installFlags)
10263                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10264            /*
10265             * Forward-locked apps are only in ASEC containers if they're the
10266             * new style
10267             */
10268            isInAsec = true;
10269        } else {
10270            isInAsec = false;
10271        }
10272
10273        if (isInAsec) {
10274            return new AsecInstallArgs(codePath, instructionSets,
10275                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10276        } else {
10277            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10278        }
10279    }
10280
10281    static abstract class InstallArgs {
10282        /** @see InstallParams#origin */
10283        final OriginInfo origin;
10284        /** @see InstallParams#move */
10285        final MoveInfo move;
10286
10287        final IPackageInstallObserver2 observer;
10288        // Always refers to PackageManager flags only
10289        final int installFlags;
10290        final String installerPackageName;
10291        final String volumeUuid;
10292        final ManifestDigest manifestDigest;
10293        final UserHandle user;
10294        final String abiOverride;
10295
10296        // The list of instruction sets supported by this app. This is currently
10297        // only used during the rmdex() phase to clean up resources. We can get rid of this
10298        // if we move dex files under the common app path.
10299        /* nullable */ String[] instructionSets;
10300
10301        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10302                int installFlags, String installerPackageName, String volumeUuid,
10303                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10304                String abiOverride) {
10305            this.origin = origin;
10306            this.move = move;
10307            this.installFlags = installFlags;
10308            this.observer = observer;
10309            this.installerPackageName = installerPackageName;
10310            this.volumeUuid = volumeUuid;
10311            this.manifestDigest = manifestDigest;
10312            this.user = user;
10313            this.instructionSets = instructionSets;
10314            this.abiOverride = abiOverride;
10315        }
10316
10317        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10318        abstract int doPreInstall(int status);
10319
10320        /**
10321         * Rename package into final resting place. All paths on the given
10322         * scanned package should be updated to reflect the rename.
10323         */
10324        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10325        abstract int doPostInstall(int status, int uid);
10326
10327        /** @see PackageSettingBase#codePathString */
10328        abstract String getCodePath();
10329        /** @see PackageSettingBase#resourcePathString */
10330        abstract String getResourcePath();
10331
10332        // Need installer lock especially for dex file removal.
10333        abstract void cleanUpResourcesLI();
10334        abstract boolean doPostDeleteLI(boolean delete);
10335
10336        /**
10337         * Called before the source arguments are copied. This is used mostly
10338         * for MoveParams when it needs to read the source file to put it in the
10339         * destination.
10340         */
10341        int doPreCopy() {
10342            return PackageManager.INSTALL_SUCCEEDED;
10343        }
10344
10345        /**
10346         * Called after the source arguments are copied. This is used mostly for
10347         * MoveParams when it needs to read the source file to put it in the
10348         * destination.
10349         *
10350         * @return
10351         */
10352        int doPostCopy(int uid) {
10353            return PackageManager.INSTALL_SUCCEEDED;
10354        }
10355
10356        protected boolean isFwdLocked() {
10357            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10358        }
10359
10360        protected boolean isExternalAsec() {
10361            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10362        }
10363
10364        UserHandle getUser() {
10365            return user;
10366        }
10367    }
10368
10369    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10370        if (!allCodePaths.isEmpty()) {
10371            if (instructionSets == null) {
10372                throw new IllegalStateException("instructionSet == null");
10373            }
10374            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10375            for (String codePath : allCodePaths) {
10376                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10377                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10378                    if (retCode < 0) {
10379                        Slog.w(TAG, "Couldn't remove dex file for package: "
10380                                + " at location " + codePath + ", retcode=" + retCode);
10381                        // we don't consider this to be a failure of the core package deletion
10382                    }
10383                }
10384            }
10385        }
10386    }
10387
10388    /**
10389     * Logic to handle installation of non-ASEC applications, including copying
10390     * and renaming logic.
10391     */
10392    class FileInstallArgs extends InstallArgs {
10393        private File codeFile;
10394        private File resourceFile;
10395
10396        // Example topology:
10397        // /data/app/com.example/base.apk
10398        // /data/app/com.example/split_foo.apk
10399        // /data/app/com.example/lib/arm/libfoo.so
10400        // /data/app/com.example/lib/arm64/libfoo.so
10401        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10402
10403        /** New install */
10404        FileInstallArgs(InstallParams params) {
10405            super(params.origin, params.move, params.observer, params.installFlags,
10406                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10407                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10408            if (isFwdLocked()) {
10409                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10410            }
10411        }
10412
10413        /** Existing install */
10414        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10415            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10416                    null);
10417            this.codeFile = (codePath != null) ? new File(codePath) : null;
10418            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10419        }
10420
10421        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10422            if (origin.staged) {
10423                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10424                codeFile = origin.file;
10425                resourceFile = origin.file;
10426                return PackageManager.INSTALL_SUCCEEDED;
10427            }
10428
10429            try {
10430                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10431                codeFile = tempDir;
10432                resourceFile = tempDir;
10433            } catch (IOException e) {
10434                Slog.w(TAG, "Failed to create copy file: " + e);
10435                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10436            }
10437
10438            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10439                @Override
10440                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10441                    if (!FileUtils.isValidExtFilename(name)) {
10442                        throw new IllegalArgumentException("Invalid filename: " + name);
10443                    }
10444                    try {
10445                        final File file = new File(codeFile, name);
10446                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10447                                O_RDWR | O_CREAT, 0644);
10448                        Os.chmod(file.getAbsolutePath(), 0644);
10449                        return new ParcelFileDescriptor(fd);
10450                    } catch (ErrnoException e) {
10451                        throw new RemoteException("Failed to open: " + e.getMessage());
10452                    }
10453                }
10454            };
10455
10456            int ret = PackageManager.INSTALL_SUCCEEDED;
10457            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10458            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10459                Slog.e(TAG, "Failed to copy package");
10460                return ret;
10461            }
10462
10463            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10464            NativeLibraryHelper.Handle handle = null;
10465            try {
10466                handle = NativeLibraryHelper.Handle.create(codeFile);
10467                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10468                        abiOverride);
10469            } catch (IOException e) {
10470                Slog.e(TAG, "Copying native libraries failed", e);
10471                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10472            } finally {
10473                IoUtils.closeQuietly(handle);
10474            }
10475
10476            return ret;
10477        }
10478
10479        int doPreInstall(int status) {
10480            if (status != PackageManager.INSTALL_SUCCEEDED) {
10481                cleanUp();
10482            }
10483            return status;
10484        }
10485
10486        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10487            if (status != PackageManager.INSTALL_SUCCEEDED) {
10488                cleanUp();
10489                return false;
10490            }
10491
10492            final File targetDir = codeFile.getParentFile();
10493            final File beforeCodeFile = codeFile;
10494            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10495
10496            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10497            try {
10498                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10499            } catch (ErrnoException e) {
10500                Slog.w(TAG, "Failed to rename", e);
10501                return false;
10502            }
10503
10504            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10505                Slog.w(TAG, "Failed to restorecon");
10506                return false;
10507            }
10508
10509            // Reflect the rename internally
10510            codeFile = afterCodeFile;
10511            resourceFile = afterCodeFile;
10512
10513            // Reflect the rename in scanned details
10514            pkg.codePath = afterCodeFile.getAbsolutePath();
10515            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10516                    pkg.baseCodePath);
10517            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10518                    pkg.splitCodePaths);
10519
10520            // Reflect the rename in app info
10521            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10522            pkg.applicationInfo.setCodePath(pkg.codePath);
10523            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10524            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10525            pkg.applicationInfo.setResourcePath(pkg.codePath);
10526            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10527            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10528
10529            return true;
10530        }
10531
10532        int doPostInstall(int status, int uid) {
10533            if (status != PackageManager.INSTALL_SUCCEEDED) {
10534                cleanUp();
10535            }
10536            return status;
10537        }
10538
10539        @Override
10540        String getCodePath() {
10541            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10542        }
10543
10544        @Override
10545        String getResourcePath() {
10546            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10547        }
10548
10549        private boolean cleanUp() {
10550            if (codeFile == null || !codeFile.exists()) {
10551                return false;
10552            }
10553
10554            if (codeFile.isDirectory()) {
10555                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10556            } else {
10557                codeFile.delete();
10558            }
10559
10560            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10561                resourceFile.delete();
10562            }
10563
10564            return true;
10565        }
10566
10567        void cleanUpResourcesLI() {
10568            // Try enumerating all code paths before deleting
10569            List<String> allCodePaths = Collections.EMPTY_LIST;
10570            if (codeFile != null && codeFile.exists()) {
10571                try {
10572                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10573                    allCodePaths = pkg.getAllCodePaths();
10574                } catch (PackageParserException e) {
10575                    // Ignored; we tried our best
10576                }
10577            }
10578
10579            cleanUp();
10580            removeDexFiles(allCodePaths, instructionSets);
10581        }
10582
10583        boolean doPostDeleteLI(boolean delete) {
10584            // XXX err, shouldn't we respect the delete flag?
10585            cleanUpResourcesLI();
10586            return true;
10587        }
10588    }
10589
10590    private boolean isAsecExternal(String cid) {
10591        final String asecPath = PackageHelper.getSdFilesystem(cid);
10592        return !asecPath.startsWith(mAsecInternalPath);
10593    }
10594
10595    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10596            PackageManagerException {
10597        if (copyRet < 0) {
10598            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10599                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10600                throw new PackageManagerException(copyRet, message);
10601            }
10602        }
10603    }
10604
10605    /**
10606     * Extract the MountService "container ID" from the full code path of an
10607     * .apk.
10608     */
10609    static String cidFromCodePath(String fullCodePath) {
10610        int eidx = fullCodePath.lastIndexOf("/");
10611        String subStr1 = fullCodePath.substring(0, eidx);
10612        int sidx = subStr1.lastIndexOf("/");
10613        return subStr1.substring(sidx+1, eidx);
10614    }
10615
10616    /**
10617     * Logic to handle installation of ASEC applications, including copying and
10618     * renaming logic.
10619     */
10620    class AsecInstallArgs extends InstallArgs {
10621        static final String RES_FILE_NAME = "pkg.apk";
10622        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10623
10624        String cid;
10625        String packagePath;
10626        String resourcePath;
10627
10628        /** New install */
10629        AsecInstallArgs(InstallParams params) {
10630            super(params.origin, params.move, params.observer, params.installFlags,
10631                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10632                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10633        }
10634
10635        /** Existing install */
10636        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10637                        boolean isExternal, boolean isForwardLocked) {
10638            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10639                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10640                    instructionSets, null);
10641            // Hackily pretend we're still looking at a full code path
10642            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10643                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10644            }
10645
10646            // Extract cid from fullCodePath
10647            int eidx = fullCodePath.lastIndexOf("/");
10648            String subStr1 = fullCodePath.substring(0, eidx);
10649            int sidx = subStr1.lastIndexOf("/");
10650            cid = subStr1.substring(sidx+1, eidx);
10651            setMountPath(subStr1);
10652        }
10653
10654        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10655            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10656                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10657                    instructionSets, null);
10658            this.cid = cid;
10659            setMountPath(PackageHelper.getSdDir(cid));
10660        }
10661
10662        void createCopyFile() {
10663            cid = mInstallerService.allocateExternalStageCidLegacy();
10664        }
10665
10666        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10667            if (origin.staged) {
10668                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
10669                cid = origin.cid;
10670                setMountPath(PackageHelper.getSdDir(cid));
10671                return PackageManager.INSTALL_SUCCEEDED;
10672            }
10673
10674            if (temp) {
10675                createCopyFile();
10676            } else {
10677                /*
10678                 * Pre-emptively destroy the container since it's destroyed if
10679                 * copying fails due to it existing anyway.
10680                 */
10681                PackageHelper.destroySdDir(cid);
10682            }
10683
10684            final String newMountPath = imcs.copyPackageToContainer(
10685                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10686                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10687
10688            if (newMountPath != null) {
10689                setMountPath(newMountPath);
10690                return PackageManager.INSTALL_SUCCEEDED;
10691            } else {
10692                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10693            }
10694        }
10695
10696        @Override
10697        String getCodePath() {
10698            return packagePath;
10699        }
10700
10701        @Override
10702        String getResourcePath() {
10703            return resourcePath;
10704        }
10705
10706        int doPreInstall(int status) {
10707            if (status != PackageManager.INSTALL_SUCCEEDED) {
10708                // Destroy container
10709                PackageHelper.destroySdDir(cid);
10710            } else {
10711                boolean mounted = PackageHelper.isContainerMounted(cid);
10712                if (!mounted) {
10713                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10714                            Process.SYSTEM_UID);
10715                    if (newMountPath != null) {
10716                        setMountPath(newMountPath);
10717                    } else {
10718                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10719                    }
10720                }
10721            }
10722            return status;
10723        }
10724
10725        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10726            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10727            String newMountPath = null;
10728            if (PackageHelper.isContainerMounted(cid)) {
10729                // Unmount the container
10730                if (!PackageHelper.unMountSdDir(cid)) {
10731                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10732                    return false;
10733                }
10734            }
10735            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10736                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10737                        " which might be stale. Will try to clean up.");
10738                // Clean up the stale container and proceed to recreate.
10739                if (!PackageHelper.destroySdDir(newCacheId)) {
10740                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10741                    return false;
10742                }
10743                // Successfully cleaned up stale container. Try to rename again.
10744                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10745                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10746                            + " inspite of cleaning it up.");
10747                    return false;
10748                }
10749            }
10750            if (!PackageHelper.isContainerMounted(newCacheId)) {
10751                Slog.w(TAG, "Mounting container " + newCacheId);
10752                newMountPath = PackageHelper.mountSdDir(newCacheId,
10753                        getEncryptKey(), Process.SYSTEM_UID);
10754            } else {
10755                newMountPath = PackageHelper.getSdDir(newCacheId);
10756            }
10757            if (newMountPath == null) {
10758                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10759                return false;
10760            }
10761            Log.i(TAG, "Succesfully renamed " + cid +
10762                    " to " + newCacheId +
10763                    " at new path: " + newMountPath);
10764            cid = newCacheId;
10765
10766            final File beforeCodeFile = new File(packagePath);
10767            setMountPath(newMountPath);
10768            final File afterCodeFile = new File(packagePath);
10769
10770            // Reflect the rename in scanned details
10771            pkg.codePath = afterCodeFile.getAbsolutePath();
10772            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10773                    pkg.baseCodePath);
10774            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10775                    pkg.splitCodePaths);
10776
10777            // Reflect the rename in app info
10778            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10779            pkg.applicationInfo.setCodePath(pkg.codePath);
10780            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10781            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10782            pkg.applicationInfo.setResourcePath(pkg.codePath);
10783            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10784            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10785
10786            return true;
10787        }
10788
10789        private void setMountPath(String mountPath) {
10790            final File mountFile = new File(mountPath);
10791
10792            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10793            if (monolithicFile.exists()) {
10794                packagePath = monolithicFile.getAbsolutePath();
10795                if (isFwdLocked()) {
10796                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10797                } else {
10798                    resourcePath = packagePath;
10799                }
10800            } else {
10801                packagePath = mountFile.getAbsolutePath();
10802                resourcePath = packagePath;
10803            }
10804        }
10805
10806        int doPostInstall(int status, int uid) {
10807            if (status != PackageManager.INSTALL_SUCCEEDED) {
10808                cleanUp();
10809            } else {
10810                final int groupOwner;
10811                final String protectedFile;
10812                if (isFwdLocked()) {
10813                    groupOwner = UserHandle.getSharedAppGid(uid);
10814                    protectedFile = RES_FILE_NAME;
10815                } else {
10816                    groupOwner = -1;
10817                    protectedFile = null;
10818                }
10819
10820                if (uid < Process.FIRST_APPLICATION_UID
10821                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10822                    Slog.e(TAG, "Failed to finalize " + cid);
10823                    PackageHelper.destroySdDir(cid);
10824                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10825                }
10826
10827                boolean mounted = PackageHelper.isContainerMounted(cid);
10828                if (!mounted) {
10829                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10830                }
10831            }
10832            return status;
10833        }
10834
10835        private void cleanUp() {
10836            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10837
10838            // Destroy secure container
10839            PackageHelper.destroySdDir(cid);
10840        }
10841
10842        private List<String> getAllCodePaths() {
10843            final File codeFile = new File(getCodePath());
10844            if (codeFile != null && codeFile.exists()) {
10845                try {
10846                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10847                    return pkg.getAllCodePaths();
10848                } catch (PackageParserException e) {
10849                    // Ignored; we tried our best
10850                }
10851            }
10852            return Collections.EMPTY_LIST;
10853        }
10854
10855        void cleanUpResourcesLI() {
10856            // Enumerate all code paths before deleting
10857            cleanUpResourcesLI(getAllCodePaths());
10858        }
10859
10860        private void cleanUpResourcesLI(List<String> allCodePaths) {
10861            cleanUp();
10862            removeDexFiles(allCodePaths, instructionSets);
10863        }
10864
10865        String getPackageName() {
10866            return getAsecPackageName(cid);
10867        }
10868
10869        boolean doPostDeleteLI(boolean delete) {
10870            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10871            final List<String> allCodePaths = getAllCodePaths();
10872            boolean mounted = PackageHelper.isContainerMounted(cid);
10873            if (mounted) {
10874                // Unmount first
10875                if (PackageHelper.unMountSdDir(cid)) {
10876                    mounted = false;
10877                }
10878            }
10879            if (!mounted && delete) {
10880                cleanUpResourcesLI(allCodePaths);
10881            }
10882            return !mounted;
10883        }
10884
10885        @Override
10886        int doPreCopy() {
10887            if (isFwdLocked()) {
10888                if (!PackageHelper.fixSdPermissions(cid,
10889                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10890                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10891                }
10892            }
10893
10894            return PackageManager.INSTALL_SUCCEEDED;
10895        }
10896
10897        @Override
10898        int doPostCopy(int uid) {
10899            if (isFwdLocked()) {
10900                if (uid < Process.FIRST_APPLICATION_UID
10901                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10902                                RES_FILE_NAME)) {
10903                    Slog.e(TAG, "Failed to finalize " + cid);
10904                    PackageHelper.destroySdDir(cid);
10905                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10906                }
10907            }
10908
10909            return PackageManager.INSTALL_SUCCEEDED;
10910        }
10911    }
10912
10913    /**
10914     * Logic to handle movement of existing installed applications.
10915     */
10916    class MoveInstallArgs extends InstallArgs {
10917        private File codeFile;
10918        private File resourceFile;
10919
10920        /** New install */
10921        MoveInstallArgs(InstallParams params) {
10922            super(params.origin, params.move, params.observer, params.installFlags,
10923                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10924                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10925        }
10926
10927        int copyApk(IMediaContainerService imcs, boolean temp) {
10928            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
10929                    + move.fromUuid + " to " + move.toUuid);
10930            synchronized (mInstaller) {
10931                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
10932                        move.dataAppName, move.appId, move.seinfo) != 0) {
10933                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10934                }
10935            }
10936
10937            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
10938            resourceFile = codeFile;
10939            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
10940
10941            return PackageManager.INSTALL_SUCCEEDED;
10942        }
10943
10944        int doPreInstall(int status) {
10945            if (status != PackageManager.INSTALL_SUCCEEDED) {
10946                cleanUp();
10947            }
10948            return status;
10949        }
10950
10951        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10952            if (status != PackageManager.INSTALL_SUCCEEDED) {
10953                cleanUp();
10954                return false;
10955            }
10956
10957            // Reflect the move in app info
10958            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10959            pkg.applicationInfo.setCodePath(pkg.codePath);
10960            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10961            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10962            pkg.applicationInfo.setResourcePath(pkg.codePath);
10963            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10964            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10965
10966            return true;
10967        }
10968
10969        int doPostInstall(int status, int uid) {
10970            if (status != PackageManager.INSTALL_SUCCEEDED) {
10971                cleanUp();
10972            }
10973            return status;
10974        }
10975
10976        @Override
10977        String getCodePath() {
10978            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10979        }
10980
10981        @Override
10982        String getResourcePath() {
10983            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10984        }
10985
10986        private boolean cleanUp() {
10987            if (codeFile == null || !codeFile.exists()) {
10988                return false;
10989            }
10990
10991            if (codeFile.isDirectory()) {
10992                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10993            } else {
10994                codeFile.delete();
10995            }
10996
10997            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10998                resourceFile.delete();
10999            }
11000
11001            return true;
11002        }
11003
11004        void cleanUpResourcesLI() {
11005            cleanUp();
11006        }
11007
11008        boolean doPostDeleteLI(boolean delete) {
11009            // XXX err, shouldn't we respect the delete flag?
11010            cleanUpResourcesLI();
11011            return true;
11012        }
11013    }
11014
11015    static String getAsecPackageName(String packageCid) {
11016        int idx = packageCid.lastIndexOf("-");
11017        if (idx == -1) {
11018            return packageCid;
11019        }
11020        return packageCid.substring(0, idx);
11021    }
11022
11023    // Utility method used to create code paths based on package name and available index.
11024    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11025        String idxStr = "";
11026        int idx = 1;
11027        // Fall back to default value of idx=1 if prefix is not
11028        // part of oldCodePath
11029        if (oldCodePath != null) {
11030            String subStr = oldCodePath;
11031            // Drop the suffix right away
11032            if (suffix != null && subStr.endsWith(suffix)) {
11033                subStr = subStr.substring(0, subStr.length() - suffix.length());
11034            }
11035            // If oldCodePath already contains prefix find out the
11036            // ending index to either increment or decrement.
11037            int sidx = subStr.lastIndexOf(prefix);
11038            if (sidx != -1) {
11039                subStr = subStr.substring(sidx + prefix.length());
11040                if (subStr != null) {
11041                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11042                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11043                    }
11044                    try {
11045                        idx = Integer.parseInt(subStr);
11046                        if (idx <= 1) {
11047                            idx++;
11048                        } else {
11049                            idx--;
11050                        }
11051                    } catch(NumberFormatException e) {
11052                    }
11053                }
11054            }
11055        }
11056        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11057        return prefix + idxStr;
11058    }
11059
11060    private File getNextCodePath(File targetDir, String packageName) {
11061        int suffix = 1;
11062        File result;
11063        do {
11064            result = new File(targetDir, packageName + "-" + suffix);
11065            suffix++;
11066        } while (result.exists());
11067        return result;
11068    }
11069
11070    // Utility method that returns the relative package path with respect
11071    // to the installation directory. Like say for /data/data/com.test-1.apk
11072    // string com.test-1 is returned.
11073    static String deriveCodePathName(String codePath) {
11074        if (codePath == null) {
11075            return null;
11076        }
11077        final File codeFile = new File(codePath);
11078        final String name = codeFile.getName();
11079        if (codeFile.isDirectory()) {
11080            return name;
11081        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11082            final int lastDot = name.lastIndexOf('.');
11083            return name.substring(0, lastDot);
11084        } else {
11085            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11086            return null;
11087        }
11088    }
11089
11090    class PackageInstalledInfo {
11091        String name;
11092        int uid;
11093        // The set of users that originally had this package installed.
11094        int[] origUsers;
11095        // The set of users that now have this package installed.
11096        int[] newUsers;
11097        PackageParser.Package pkg;
11098        int returnCode;
11099        String returnMsg;
11100        PackageRemovedInfo removedInfo;
11101
11102        public void setError(int code, String msg) {
11103            returnCode = code;
11104            returnMsg = msg;
11105            Slog.w(TAG, msg);
11106        }
11107
11108        public void setError(String msg, PackageParserException e) {
11109            returnCode = e.error;
11110            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11111            Slog.w(TAG, msg, e);
11112        }
11113
11114        public void setError(String msg, PackageManagerException e) {
11115            returnCode = e.error;
11116            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11117            Slog.w(TAG, msg, e);
11118        }
11119
11120        // In some error cases we want to convey more info back to the observer
11121        String origPackage;
11122        String origPermission;
11123    }
11124
11125    /*
11126     * Install a non-existing package.
11127     */
11128    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11129            UserHandle user, String installerPackageName, String volumeUuid,
11130            PackageInstalledInfo res) {
11131        // Remember this for later, in case we need to rollback this install
11132        String pkgName = pkg.packageName;
11133
11134        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11135        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
11136                UserHandle.USER_OWNER).exists();
11137        synchronized(mPackages) {
11138            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11139                // A package with the same name is already installed, though
11140                // it has been renamed to an older name.  The package we
11141                // are trying to install should be installed as an update to
11142                // the existing one, but that has not been requested, so bail.
11143                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11144                        + " without first uninstalling package running as "
11145                        + mSettings.mRenamedPackages.get(pkgName));
11146                return;
11147            }
11148            if (mPackages.containsKey(pkgName)) {
11149                // Don't allow installation over an existing package with the same name.
11150                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11151                        + " without first uninstalling.");
11152                return;
11153            }
11154        }
11155
11156        try {
11157            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11158                    System.currentTimeMillis(), user);
11159
11160            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11161            // delete the partially installed application. the data directory will have to be
11162            // restored if it was already existing
11163            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11164                // remove package from internal structures.  Note that we want deletePackageX to
11165                // delete the package data and cache directories that it created in
11166                // scanPackageLocked, unless those directories existed before we even tried to
11167                // install.
11168                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11169                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11170                                res.removedInfo, true);
11171            }
11172
11173        } catch (PackageManagerException e) {
11174            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11175        }
11176    }
11177
11178    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11179        // Can't rotate keys during boot or if sharedUser.
11180        if (oldPs == null || (scanFlags&SCAN_BOOTING) != 0 || oldPs.sharedUser != null
11181                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11182            return false;
11183        }
11184        // app is using upgradeKeySets; make sure all are valid
11185        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11186        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11187        for (int i = 0; i < upgradeKeySets.length; i++) {
11188            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11189                Slog.wtf(TAG, "Package "
11190                         + (oldPs.name != null ? oldPs.name : "<null>")
11191                         + " contains upgrade-key-set reference to unknown key-set: "
11192                         + upgradeKeySets[i]
11193                         + " reverting to signatures check.");
11194                return false;
11195            }
11196        }
11197        return true;
11198    }
11199
11200    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11201        // Upgrade keysets are being used.  Determine if new package has a superset of the
11202        // required keys.
11203        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11204        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11205        for (int i = 0; i < upgradeKeySets.length; i++) {
11206            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11207            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11208                return true;
11209            }
11210        }
11211        return false;
11212    }
11213
11214    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11215            UserHandle user, String installerPackageName, String volumeUuid,
11216            PackageInstalledInfo res) {
11217        final PackageParser.Package oldPackage;
11218        final String pkgName = pkg.packageName;
11219        final int[] allUsers;
11220        final boolean[] perUserInstalled;
11221        final boolean weFroze;
11222
11223        // First find the old package info and check signatures
11224        synchronized(mPackages) {
11225            oldPackage = mPackages.get(pkgName);
11226            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11227            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11228            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11229                if(!checkUpgradeKeySetLP(ps, pkg)) {
11230                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11231                            "New package not signed by keys specified by upgrade-keysets: "
11232                            + pkgName);
11233                    return;
11234                }
11235            } else {
11236                // default to original signature matching
11237                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11238                    != PackageManager.SIGNATURE_MATCH) {
11239                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11240                            "New package has a different signature: " + pkgName);
11241                    return;
11242                }
11243            }
11244
11245            // In case of rollback, remember per-user/profile install state
11246            allUsers = sUserManager.getUserIds();
11247            perUserInstalled = new boolean[allUsers.length];
11248            for (int i = 0; i < allUsers.length; i++) {
11249                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11250            }
11251
11252            // Mark the app as frozen to prevent launching during the upgrade
11253            // process, and then kill all running instances
11254            if (!ps.frozen) {
11255                ps.frozen = true;
11256                weFroze = true;
11257            } else {
11258                weFroze = false;
11259            }
11260        }
11261
11262        // Now that we're guarded by frozen state, kill app during upgrade
11263        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11264
11265        try {
11266            boolean sysPkg = (isSystemApp(oldPackage));
11267            if (sysPkg) {
11268                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11269                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11270            } else {
11271                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11272                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11273            }
11274        } finally {
11275            // Regardless of success or failure of upgrade steps above, always
11276            // unfreeze the package if we froze it
11277            if (weFroze) {
11278                unfreezePackage(pkgName);
11279            }
11280        }
11281    }
11282
11283    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11284            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11285            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11286            String volumeUuid, PackageInstalledInfo res) {
11287        String pkgName = deletedPackage.packageName;
11288        boolean deletedPkg = true;
11289        boolean updatedSettings = false;
11290
11291        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11292                + deletedPackage);
11293        long origUpdateTime;
11294        if (pkg.mExtras != null) {
11295            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11296        } else {
11297            origUpdateTime = 0;
11298        }
11299
11300        // First delete the existing package while retaining the data directory
11301        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11302                res.removedInfo, true)) {
11303            // If the existing package wasn't successfully deleted
11304            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11305            deletedPkg = false;
11306        } else {
11307            // Successfully deleted the old package; proceed with replace.
11308
11309            // If deleted package lived in a container, give users a chance to
11310            // relinquish resources before killing.
11311            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11312                if (DEBUG_INSTALL) {
11313                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11314                }
11315                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11316                final ArrayList<String> pkgList = new ArrayList<String>(1);
11317                pkgList.add(deletedPackage.applicationInfo.packageName);
11318                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11319            }
11320
11321            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11322            try {
11323                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11324                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11325                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11326                        perUserInstalled, res, user);
11327                updatedSettings = true;
11328            } catch (PackageManagerException e) {
11329                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11330            }
11331        }
11332
11333        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11334            // remove package from internal structures.  Note that we want deletePackageX to
11335            // delete the package data and cache directories that it created in
11336            // scanPackageLocked, unless those directories existed before we even tried to
11337            // install.
11338            if(updatedSettings) {
11339                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11340                deletePackageLI(
11341                        pkgName, null, true, allUsers, perUserInstalled,
11342                        PackageManager.DELETE_KEEP_DATA,
11343                                res.removedInfo, true);
11344            }
11345            // Since we failed to install the new package we need to restore the old
11346            // package that we deleted.
11347            if (deletedPkg) {
11348                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11349                File restoreFile = new File(deletedPackage.codePath);
11350                // Parse old package
11351                boolean oldExternal = isExternal(deletedPackage);
11352                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11353                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11354                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11355                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11356                try {
11357                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11358                } catch (PackageManagerException e) {
11359                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11360                            + e.getMessage());
11361                    return;
11362                }
11363                // Restore of old package succeeded. Update permissions.
11364                // writer
11365                synchronized (mPackages) {
11366                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11367                            UPDATE_PERMISSIONS_ALL);
11368                    // can downgrade to reader
11369                    mSettings.writeLPr();
11370                }
11371                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11372            }
11373        }
11374    }
11375
11376    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11377            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11378            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11379            String volumeUuid, PackageInstalledInfo res) {
11380        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11381                + ", old=" + deletedPackage);
11382        boolean disabledSystem = false;
11383        boolean updatedSettings = false;
11384        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11385        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11386                != 0) {
11387            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11388        }
11389        String packageName = deletedPackage.packageName;
11390        if (packageName == null) {
11391            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11392                    "Attempt to delete null packageName.");
11393            return;
11394        }
11395        PackageParser.Package oldPkg;
11396        PackageSetting oldPkgSetting;
11397        // reader
11398        synchronized (mPackages) {
11399            oldPkg = mPackages.get(packageName);
11400            oldPkgSetting = mSettings.mPackages.get(packageName);
11401            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11402                    (oldPkgSetting == null)) {
11403                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11404                        "Couldn't find package:" + packageName + " information");
11405                return;
11406            }
11407        }
11408
11409        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11410        res.removedInfo.removedPackage = packageName;
11411        // Remove existing system package
11412        removePackageLI(oldPkgSetting, true);
11413        // writer
11414        synchronized (mPackages) {
11415            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11416            if (!disabledSystem && deletedPackage != null) {
11417                // We didn't need to disable the .apk as a current system package,
11418                // which means we are replacing another update that is already
11419                // installed.  We need to make sure to delete the older one's .apk.
11420                res.removedInfo.args = createInstallArgsForExisting(0,
11421                        deletedPackage.applicationInfo.getCodePath(),
11422                        deletedPackage.applicationInfo.getResourcePath(),
11423                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11424            } else {
11425                res.removedInfo.args = null;
11426            }
11427        }
11428
11429        // Successfully disabled the old package. Now proceed with re-installation
11430        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11431
11432        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11433        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11434
11435        PackageParser.Package newPackage = null;
11436        try {
11437            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11438            if (newPackage.mExtras != null) {
11439                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11440                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11441                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11442
11443                // is the update attempting to change shared user? that isn't going to work...
11444                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11445                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11446                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11447                            + " to " + newPkgSetting.sharedUser);
11448                    updatedSettings = true;
11449                }
11450            }
11451
11452            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11453                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11454                        perUserInstalled, res, user);
11455                updatedSettings = true;
11456            }
11457
11458        } catch (PackageManagerException e) {
11459            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11460        }
11461
11462        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11463            // Re installation failed. Restore old information
11464            // Remove new pkg information
11465            if (newPackage != null) {
11466                removeInstalledPackageLI(newPackage, true);
11467            }
11468            // Add back the old system package
11469            try {
11470                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11471            } catch (PackageManagerException e) {
11472                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11473            }
11474            // Restore the old system information in Settings
11475            synchronized (mPackages) {
11476                if (disabledSystem) {
11477                    mSettings.enableSystemPackageLPw(packageName);
11478                }
11479                if (updatedSettings) {
11480                    mSettings.setInstallerPackageName(packageName,
11481                            oldPkgSetting.installerPackageName);
11482                }
11483                mSettings.writeLPr();
11484            }
11485        }
11486    }
11487
11488    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11489            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11490            UserHandle user) {
11491        String pkgName = newPackage.packageName;
11492        synchronized (mPackages) {
11493            //write settings. the installStatus will be incomplete at this stage.
11494            //note that the new package setting would have already been
11495            //added to mPackages. It hasn't been persisted yet.
11496            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11497            mSettings.writeLPr();
11498        }
11499
11500        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11501
11502        synchronized (mPackages) {
11503            updatePermissionsLPw(newPackage.packageName, newPackage,
11504                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11505                            ? UPDATE_PERMISSIONS_ALL : 0));
11506            // For system-bundled packages, we assume that installing an upgraded version
11507            // of the package implies that the user actually wants to run that new code,
11508            // so we enable the package.
11509            PackageSetting ps = mSettings.mPackages.get(pkgName);
11510            if (ps != null) {
11511                if (isSystemApp(newPackage)) {
11512                    // NB: implicit assumption that system package upgrades apply to all users
11513                    if (DEBUG_INSTALL) {
11514                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11515                    }
11516                    if (res.origUsers != null) {
11517                        for (int userHandle : res.origUsers) {
11518                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11519                                    userHandle, installerPackageName);
11520                        }
11521                    }
11522                    // Also convey the prior install/uninstall state
11523                    if (allUsers != null && perUserInstalled != null) {
11524                        for (int i = 0; i < allUsers.length; i++) {
11525                            if (DEBUG_INSTALL) {
11526                                Slog.d(TAG, "    user " + allUsers[i]
11527                                        + " => " + perUserInstalled[i]);
11528                            }
11529                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11530                        }
11531                        // these install state changes will be persisted in the
11532                        // upcoming call to mSettings.writeLPr().
11533                    }
11534                }
11535                // It's implied that when a user requests installation, they want the app to be
11536                // installed and enabled.
11537                int userId = user.getIdentifier();
11538                if (userId != UserHandle.USER_ALL) {
11539                    ps.setInstalled(true, userId);
11540                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11541                }
11542            }
11543            res.name = pkgName;
11544            res.uid = newPackage.applicationInfo.uid;
11545            res.pkg = newPackage;
11546            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11547            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11548            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11549            //to update install status
11550            mSettings.writeLPr();
11551        }
11552    }
11553
11554    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11555        final int installFlags = args.installFlags;
11556        final String installerPackageName = args.installerPackageName;
11557        final String volumeUuid = args.volumeUuid;
11558        final File tmpPackageFile = new File(args.getCodePath());
11559        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11560        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11561                || (args.volumeUuid != null));
11562        boolean replace = false;
11563        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11564        // Result object to be returned
11565        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11566
11567        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11568        // Retrieve PackageSettings and parse package
11569        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11570                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11571                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11572        PackageParser pp = new PackageParser();
11573        pp.setSeparateProcesses(mSeparateProcesses);
11574        pp.setDisplayMetrics(mMetrics);
11575
11576        final PackageParser.Package pkg;
11577        try {
11578            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11579        } catch (PackageParserException e) {
11580            res.setError("Failed parse during installPackageLI", e);
11581            return;
11582        }
11583
11584        // Mark that we have an install time CPU ABI override.
11585        pkg.cpuAbiOverride = args.abiOverride;
11586
11587        String pkgName = res.name = pkg.packageName;
11588        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11589            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11590                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11591                return;
11592            }
11593        }
11594
11595        try {
11596            pp.collectCertificates(pkg, parseFlags);
11597            pp.collectManifestDigest(pkg);
11598        } catch (PackageParserException e) {
11599            res.setError("Failed collect during installPackageLI", e);
11600            return;
11601        }
11602
11603        /* If the installer passed in a manifest digest, compare it now. */
11604        if (args.manifestDigest != null) {
11605            if (DEBUG_INSTALL) {
11606                final String parsedManifest = pkg.manifestDigest == null ? "null"
11607                        : pkg.manifestDigest.toString();
11608                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11609                        + parsedManifest);
11610            }
11611
11612            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11613                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11614                return;
11615            }
11616        } else if (DEBUG_INSTALL) {
11617            final String parsedManifest = pkg.manifestDigest == null
11618                    ? "null" : pkg.manifestDigest.toString();
11619            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11620        }
11621
11622        // Get rid of all references to package scan path via parser.
11623        pp = null;
11624        String oldCodePath = null;
11625        boolean systemApp = false;
11626        synchronized (mPackages) {
11627            // Check if installing already existing package
11628            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11629                String oldName = mSettings.mRenamedPackages.get(pkgName);
11630                if (pkg.mOriginalPackages != null
11631                        && pkg.mOriginalPackages.contains(oldName)
11632                        && mPackages.containsKey(oldName)) {
11633                    // This package is derived from an original package,
11634                    // and this device has been updating from that original
11635                    // name.  We must continue using the original name, so
11636                    // rename the new package here.
11637                    pkg.setPackageName(oldName);
11638                    pkgName = pkg.packageName;
11639                    replace = true;
11640                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11641                            + oldName + " pkgName=" + pkgName);
11642                } else if (mPackages.containsKey(pkgName)) {
11643                    // This package, under its official name, already exists
11644                    // on the device; we should replace it.
11645                    replace = true;
11646                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11647                }
11648
11649                // Prevent apps opting out from runtime permissions
11650                if (replace) {
11651                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11652                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11653                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11654                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11655                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11656                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11657                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11658                                        + " doesn't support runtime permissions but the old"
11659                                        + " target SDK " + oldTargetSdk + " does.");
11660                        return;
11661                    }
11662                }
11663            }
11664
11665            PackageSetting ps = mSettings.mPackages.get(pkgName);
11666            if (ps != null) {
11667                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11668
11669                // Quick sanity check that we're signed correctly if updating;
11670                // we'll check this again later when scanning, but we want to
11671                // bail early here before tripping over redefined permissions.
11672                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11673                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11674                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11675                                + pkg.packageName + " upgrade keys do not match the "
11676                                + "previously installed version");
11677                        return;
11678                    }
11679                } else {
11680                    try {
11681                        verifySignaturesLP(ps, pkg);
11682                    } catch (PackageManagerException e) {
11683                        res.setError(e.error, e.getMessage());
11684                        return;
11685                    }
11686                }
11687
11688                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11689                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11690                    systemApp = (ps.pkg.applicationInfo.flags &
11691                            ApplicationInfo.FLAG_SYSTEM) != 0;
11692                }
11693                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11694            }
11695
11696            // Check whether the newly-scanned package wants to define an already-defined perm
11697            int N = pkg.permissions.size();
11698            for (int i = N-1; i >= 0; i--) {
11699                PackageParser.Permission perm = pkg.permissions.get(i);
11700                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11701                if (bp != null) {
11702                    // If the defining package is signed with our cert, it's okay.  This
11703                    // also includes the "updating the same package" case, of course.
11704                    // "updating same package" could also involve key-rotation.
11705                    final boolean sigsOk;
11706                    if (bp.sourcePackage.equals(pkg.packageName)
11707                            && (bp.packageSetting instanceof PackageSetting)
11708                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
11709                                    scanFlags))) {
11710                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11711                    } else {
11712                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11713                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11714                    }
11715                    if (!sigsOk) {
11716                        // If the owning package is the system itself, we log but allow
11717                        // install to proceed; we fail the install on all other permission
11718                        // redefinitions.
11719                        if (!bp.sourcePackage.equals("android")) {
11720                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11721                                    + pkg.packageName + " attempting to redeclare permission "
11722                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11723                            res.origPermission = perm.info.name;
11724                            res.origPackage = bp.sourcePackage;
11725                            return;
11726                        } else {
11727                            Slog.w(TAG, "Package " + pkg.packageName
11728                                    + " attempting to redeclare system permission "
11729                                    + perm.info.name + "; ignoring new declaration");
11730                            pkg.permissions.remove(i);
11731                        }
11732                    }
11733                }
11734            }
11735
11736        }
11737
11738        if (systemApp && onExternal) {
11739            // Disable updates to system apps on sdcard
11740            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11741                    "Cannot install updates to system apps on sdcard");
11742            return;
11743        }
11744
11745        if (args.move != null) {
11746            // We did an in-place move, so dex is ready to roll
11747            scanFlags |= SCAN_NO_DEX;
11748            scanFlags |= SCAN_MOVE;
11749        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
11750            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
11751            scanFlags |= SCAN_NO_DEX;
11752
11753            try {
11754                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
11755                        true /* extract libs */);
11756            } catch (PackageManagerException pme) {
11757                Slog.e(TAG, "Error deriving application ABI", pme);
11758                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
11759                return;
11760            }
11761
11762            // Run dexopt before old package gets removed, to minimize time when app is unavailable
11763            int result = mPackageDexOptimizer
11764                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
11765                            false /* defer */, false /* inclDependencies */);
11766            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11767                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11768                return;
11769            }
11770        }
11771
11772        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11773            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11774            return;
11775        }
11776
11777        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
11778
11779        if (replace) {
11780            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
11781                    installerPackageName, volumeUuid, res);
11782        } else {
11783            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11784                    args.user, installerPackageName, volumeUuid, res);
11785        }
11786        synchronized (mPackages) {
11787            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11788            if (ps != null) {
11789                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11790            }
11791        }
11792    }
11793
11794    private void startIntentFilterVerifications(int userId, boolean replacing,
11795            PackageParser.Package pkg) {
11796        if (mIntentFilterVerifierComponent == null) {
11797            Slog.w(TAG, "No IntentFilter verification will not be done as "
11798                    + "there is no IntentFilterVerifier available!");
11799            return;
11800        }
11801
11802        final int verifierUid = getPackageUid(
11803                mIntentFilterVerifierComponent.getPackageName(),
11804                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11805
11806        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11807        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11808        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
11809        mHandler.sendMessage(msg);
11810    }
11811
11812    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
11813            PackageParser.Package pkg) {
11814        int size = pkg.activities.size();
11815        if (size == 0) {
11816            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11817                    "No activity, so no need to verify any IntentFilter!");
11818            return;
11819        }
11820
11821        final boolean hasDomainURLs = hasDomainURLs(pkg);
11822        if (!hasDomainURLs) {
11823            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11824                    "No domain URLs, so no need to verify any IntentFilter!");
11825            return;
11826        }
11827
11828        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
11829                + " if any IntentFilter from the " + size
11830                + " Activities needs verification ...");
11831
11832        int count = 0;
11833        final String packageName = pkg.packageName;
11834
11835        synchronized (mPackages) {
11836            // If this is a new install and we see that we've already run verification for this
11837            // package, we have nothing to do: it means the state was restored from backup.
11838            if (!replacing) {
11839                IntentFilterVerificationInfo ivi =
11840                        mSettings.getIntentFilterVerificationLPr(packageName);
11841                if (ivi != null) {
11842                    if (DEBUG_DOMAIN_VERIFICATION) {
11843                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
11844                                + ivi.getStatusString());
11845                    }
11846                    return;
11847                }
11848            }
11849
11850            // If any filters need to be verified, then all need to be.
11851            boolean needToVerify = false;
11852            for (PackageParser.Activity a : pkg.activities) {
11853                for (ActivityIntentInfo filter : a.intents) {
11854                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
11855                        if (DEBUG_DOMAIN_VERIFICATION) {
11856                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
11857                        }
11858                        needToVerify = true;
11859                        break;
11860                    }
11861                }
11862            }
11863
11864            if (needToVerify) {
11865                final int verificationId = mIntentFilterVerificationToken++;
11866                for (PackageParser.Activity a : pkg.activities) {
11867                    for (ActivityIntentInfo filter : a.intents) {
11868                        boolean needsFilterVerification = filter.hasWebDataURI();
11869                        if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11870                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11871                                    "Verification needed for IntentFilter:" + filter.toString());
11872                            mIntentFilterVerifier.addOneIntentFilterVerification(
11873                                    verifierUid, userId, verificationId, filter, packageName);
11874                            count++;
11875                        }
11876                    }
11877                }
11878            }
11879        }
11880
11881        if (count > 0) {
11882            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
11883                    + " IntentFilter verification" + (count > 1 ? "s" : "")
11884                    +  " for userId:" + userId);
11885            mIntentFilterVerifier.startVerifications(userId);
11886        } else {
11887            if (DEBUG_DOMAIN_VERIFICATION) {
11888                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
11889            }
11890        }
11891    }
11892
11893    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11894        final ComponentName cn  = filter.activity.getComponentName();
11895        final String packageName = cn.getPackageName();
11896
11897        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11898                packageName);
11899        if (ivi == null) {
11900            return true;
11901        }
11902        int status = ivi.getStatus();
11903        switch (status) {
11904            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11905            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11906                return true;
11907
11908            default:
11909                // Nothing to do
11910                return false;
11911        }
11912    }
11913
11914    private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) {
11915        return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID
11916                || ((pkg.applicationInfo.privateFlags
11917                        & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0
11918                && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0);
11919    }
11920
11921    private static boolean isMultiArch(PackageSetting ps) {
11922        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11923    }
11924
11925    private static boolean isMultiArch(ApplicationInfo info) {
11926        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11927    }
11928
11929    private static boolean isExternal(PackageParser.Package pkg) {
11930        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11931    }
11932
11933    private static boolean isExternal(PackageSetting ps) {
11934        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11935    }
11936
11937    private static boolean isExternal(ApplicationInfo info) {
11938        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11939    }
11940
11941    private static boolean isSystemApp(PackageParser.Package pkg) {
11942        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11943    }
11944
11945    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
11946        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
11947    }
11948
11949    private static boolean hasDomainURLs(PackageParser.Package pkg) {
11950        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
11951    }
11952
11953    private static boolean isSystemApp(PackageSetting ps) {
11954        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
11955    }
11956
11957    private static boolean isUpdatedSystemApp(PackageSetting ps) {
11958        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
11959    }
11960
11961    private int packageFlagsToInstallFlags(PackageSetting ps) {
11962        int installFlags = 0;
11963        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
11964            // This existing package was an external ASEC install when we have
11965            // the external flag without a UUID
11966            installFlags |= PackageManager.INSTALL_EXTERNAL;
11967        }
11968        if (ps.isForwardLocked()) {
11969            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11970        }
11971        return installFlags;
11972    }
11973
11974    private void deleteTempPackageFiles() {
11975        final FilenameFilter filter = new FilenameFilter() {
11976            public boolean accept(File dir, String name) {
11977                return name.startsWith("vmdl") && name.endsWith(".tmp");
11978            }
11979        };
11980        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
11981            file.delete();
11982        }
11983    }
11984
11985    @Override
11986    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
11987            int flags) {
11988        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
11989                flags);
11990    }
11991
11992    @Override
11993    public void deletePackage(final String packageName,
11994            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
11995        mContext.enforceCallingOrSelfPermission(
11996                android.Manifest.permission.DELETE_PACKAGES, null);
11997        final int uid = Binder.getCallingUid();
11998        if (UserHandle.getUserId(uid) != userId) {
11999            mContext.enforceCallingPermission(
12000                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12001                    "deletePackage for user " + userId);
12002        }
12003        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12004            try {
12005                observer.onPackageDeleted(packageName,
12006                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12007            } catch (RemoteException re) {
12008            }
12009            return;
12010        }
12011
12012        boolean uninstallBlocked = false;
12013        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12014            int[] users = sUserManager.getUserIds();
12015            for (int i = 0; i < users.length; ++i) {
12016                if (getBlockUninstallForUser(packageName, users[i])) {
12017                    uninstallBlocked = true;
12018                    break;
12019                }
12020            }
12021        } else {
12022            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12023        }
12024        if (uninstallBlocked) {
12025            try {
12026                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12027                        null);
12028            } catch (RemoteException re) {
12029            }
12030            return;
12031        }
12032
12033        if (DEBUG_REMOVE) {
12034            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12035        }
12036        // Queue up an async operation since the package deletion may take a little while.
12037        mHandler.post(new Runnable() {
12038            public void run() {
12039                mHandler.removeCallbacks(this);
12040                final int returnCode = deletePackageX(packageName, userId, flags);
12041                if (observer != null) {
12042                    try {
12043                        observer.onPackageDeleted(packageName, returnCode, null);
12044                    } catch (RemoteException e) {
12045                        Log.i(TAG, "Observer no longer exists.");
12046                    } //end catch
12047                } //end if
12048            } //end run
12049        });
12050    }
12051
12052    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12053        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12054                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12055        try {
12056            if (dpm != null) {
12057                if (dpm.isDeviceOwner(packageName)) {
12058                    return true;
12059                }
12060                int[] users;
12061                if (userId == UserHandle.USER_ALL) {
12062                    users = sUserManager.getUserIds();
12063                } else {
12064                    users = new int[]{userId};
12065                }
12066                for (int i = 0; i < users.length; ++i) {
12067                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12068                        return true;
12069                    }
12070                }
12071            }
12072        } catch (RemoteException e) {
12073        }
12074        return false;
12075    }
12076
12077    /**
12078     *  This method is an internal method that could be get invoked either
12079     *  to delete an installed package or to clean up a failed installation.
12080     *  After deleting an installed package, a broadcast is sent to notify any
12081     *  listeners that the package has been installed. For cleaning up a failed
12082     *  installation, the broadcast is not necessary since the package's
12083     *  installation wouldn't have sent the initial broadcast either
12084     *  The key steps in deleting a package are
12085     *  deleting the package information in internal structures like mPackages,
12086     *  deleting the packages base directories through installd
12087     *  updating mSettings to reflect current status
12088     *  persisting settings for later use
12089     *  sending a broadcast if necessary
12090     */
12091    private int deletePackageX(String packageName, int userId, int flags) {
12092        final PackageRemovedInfo info = new PackageRemovedInfo();
12093        final boolean res;
12094
12095        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12096                ? UserHandle.ALL : new UserHandle(userId);
12097
12098        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12099            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12100            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12101        }
12102
12103        boolean removedForAllUsers = false;
12104        boolean systemUpdate = false;
12105
12106        // for the uninstall-updates case and restricted profiles, remember the per-
12107        // userhandle installed state
12108        int[] allUsers;
12109        boolean[] perUserInstalled;
12110        synchronized (mPackages) {
12111            PackageSetting ps = mSettings.mPackages.get(packageName);
12112            allUsers = sUserManager.getUserIds();
12113            perUserInstalled = new boolean[allUsers.length];
12114            for (int i = 0; i < allUsers.length; i++) {
12115                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12116            }
12117        }
12118
12119        synchronized (mInstallLock) {
12120            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12121            res = deletePackageLI(packageName, removeForUser,
12122                    true, allUsers, perUserInstalled,
12123                    flags | REMOVE_CHATTY, info, true);
12124            systemUpdate = info.isRemovedPackageSystemUpdate;
12125            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12126                removedForAllUsers = true;
12127            }
12128            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12129                    + " removedForAllUsers=" + removedForAllUsers);
12130        }
12131
12132        if (res) {
12133            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12134
12135            // If the removed package was a system update, the old system package
12136            // was re-enabled; we need to broadcast this information
12137            if (systemUpdate) {
12138                Bundle extras = new Bundle(1);
12139                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12140                        ? info.removedAppId : info.uid);
12141                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12142
12143                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12144                        extras, null, null, null);
12145                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12146                        extras, null, null, null);
12147                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12148                        null, packageName, null, null);
12149            }
12150        }
12151        // Force a gc here.
12152        Runtime.getRuntime().gc();
12153        // Delete the resources here after sending the broadcast to let
12154        // other processes clean up before deleting resources.
12155        if (info.args != null) {
12156            synchronized (mInstallLock) {
12157                info.args.doPostDeleteLI(true);
12158            }
12159        }
12160
12161        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12162    }
12163
12164    class PackageRemovedInfo {
12165        String removedPackage;
12166        int uid = -1;
12167        int removedAppId = -1;
12168        int[] removedUsers = null;
12169        boolean isRemovedPackageSystemUpdate = false;
12170        // Clean up resources deleted packages.
12171        InstallArgs args = null;
12172
12173        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12174            Bundle extras = new Bundle(1);
12175            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12176            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12177            if (replacing) {
12178                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12179            }
12180            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12181            if (removedPackage != null) {
12182                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12183                        extras, null, null, removedUsers);
12184                if (fullRemove && !replacing) {
12185                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12186                            extras, null, null, removedUsers);
12187                }
12188            }
12189            if (removedAppId >= 0) {
12190                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12191                        removedUsers);
12192            }
12193        }
12194    }
12195
12196    /*
12197     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12198     * flag is not set, the data directory is removed as well.
12199     * make sure this flag is set for partially installed apps. If not its meaningless to
12200     * delete a partially installed application.
12201     */
12202    private void removePackageDataLI(PackageSetting ps,
12203            int[] allUserHandles, boolean[] perUserInstalled,
12204            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12205        String packageName = ps.name;
12206        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12207        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12208        // Retrieve object to delete permissions for shared user later on
12209        final PackageSetting deletedPs;
12210        // reader
12211        synchronized (mPackages) {
12212            deletedPs = mSettings.mPackages.get(packageName);
12213            if (outInfo != null) {
12214                outInfo.removedPackage = packageName;
12215                outInfo.removedUsers = deletedPs != null
12216                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12217                        : null;
12218            }
12219        }
12220        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12221            removeDataDirsLI(ps.volumeUuid, packageName);
12222            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12223        }
12224        // writer
12225        synchronized (mPackages) {
12226            if (deletedPs != null) {
12227                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12228                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12229                    clearDefaultBrowserIfNeeded(packageName);
12230                    if (outInfo != null) {
12231                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12232                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12233                    }
12234                    updatePermissionsLPw(deletedPs.name, null, 0);
12235                    if (deletedPs.sharedUser != null) {
12236                        // Remove permissions associated with package. Since runtime
12237                        // permissions are per user we have to kill the removed package
12238                        // or packages running under the shared user of the removed
12239                        // package if revoking the permissions requested only by the removed
12240                        // package is successful and this causes a change in gids.
12241                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12242                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12243                                    userId);
12244                            if (userIdToKill == UserHandle.USER_ALL
12245                                    || userIdToKill >= UserHandle.USER_OWNER) {
12246                                // If gids changed for this user, kill all affected packages.
12247                                mHandler.post(new Runnable() {
12248                                    @Override
12249                                    public void run() {
12250                                        // This has to happen with no lock held.
12251                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12252                                                KILL_APP_REASON_GIDS_CHANGED);
12253                                    }
12254                                });
12255                            break;
12256                            }
12257                        }
12258                    }
12259                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12260                }
12261                // make sure to preserve per-user disabled state if this removal was just
12262                // a downgrade of a system app to the factory package
12263                if (allUserHandles != null && perUserInstalled != null) {
12264                    if (DEBUG_REMOVE) {
12265                        Slog.d(TAG, "Propagating install state across downgrade");
12266                    }
12267                    for (int i = 0; i < allUserHandles.length; i++) {
12268                        if (DEBUG_REMOVE) {
12269                            Slog.d(TAG, "    user " + allUserHandles[i]
12270                                    + " => " + perUserInstalled[i]);
12271                        }
12272                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12273                    }
12274                }
12275            }
12276            // can downgrade to reader
12277            if (writeSettings) {
12278                // Save settings now
12279                mSettings.writeLPr();
12280            }
12281        }
12282        if (outInfo != null) {
12283            // A user ID was deleted here. Go through all users and remove it
12284            // from KeyStore.
12285            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12286        }
12287    }
12288
12289    static boolean locationIsPrivileged(File path) {
12290        try {
12291            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12292                    .getCanonicalPath();
12293            return path.getCanonicalPath().startsWith(privilegedAppDir);
12294        } catch (IOException e) {
12295            Slog.e(TAG, "Unable to access code path " + path);
12296        }
12297        return false;
12298    }
12299
12300    /*
12301     * Tries to delete system package.
12302     */
12303    private boolean deleteSystemPackageLI(PackageSetting newPs,
12304            int[] allUserHandles, boolean[] perUserInstalled,
12305            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12306        final boolean applyUserRestrictions
12307                = (allUserHandles != null) && (perUserInstalled != null);
12308        PackageSetting disabledPs = null;
12309        // Confirm if the system package has been updated
12310        // An updated system app can be deleted. This will also have to restore
12311        // the system pkg from system partition
12312        // reader
12313        synchronized (mPackages) {
12314            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12315        }
12316        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12317                + " disabledPs=" + disabledPs);
12318        if (disabledPs == null) {
12319            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12320            return false;
12321        } else if (DEBUG_REMOVE) {
12322            Slog.d(TAG, "Deleting system pkg from data partition");
12323        }
12324        if (DEBUG_REMOVE) {
12325            if (applyUserRestrictions) {
12326                Slog.d(TAG, "Remembering install states:");
12327                for (int i = 0; i < allUserHandles.length; i++) {
12328                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12329                }
12330            }
12331        }
12332        // Delete the updated package
12333        outInfo.isRemovedPackageSystemUpdate = true;
12334        if (disabledPs.versionCode < newPs.versionCode) {
12335            // Delete data for downgrades
12336            flags &= ~PackageManager.DELETE_KEEP_DATA;
12337        } else {
12338            // Preserve data by setting flag
12339            flags |= PackageManager.DELETE_KEEP_DATA;
12340        }
12341        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12342                allUserHandles, perUserInstalled, outInfo, writeSettings);
12343        if (!ret) {
12344            return false;
12345        }
12346        // writer
12347        synchronized (mPackages) {
12348            // Reinstate the old system package
12349            mSettings.enableSystemPackageLPw(newPs.name);
12350            // Remove any native libraries from the upgraded package.
12351            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12352        }
12353        // Install the system package
12354        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12355        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12356        if (locationIsPrivileged(disabledPs.codePath)) {
12357            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12358        }
12359
12360        final PackageParser.Package newPkg;
12361        try {
12362            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12363        } catch (PackageManagerException e) {
12364            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12365            return false;
12366        }
12367
12368        // writer
12369        synchronized (mPackages) {
12370            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12371            updatePermissionsLPw(newPkg.packageName, newPkg,
12372                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12373            if (applyUserRestrictions) {
12374                if (DEBUG_REMOVE) {
12375                    Slog.d(TAG, "Propagating install state across reinstall");
12376                }
12377                for (int i = 0; i < allUserHandles.length; i++) {
12378                    if (DEBUG_REMOVE) {
12379                        Slog.d(TAG, "    user " + allUserHandles[i]
12380                                + " => " + perUserInstalled[i]);
12381                    }
12382                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12383                }
12384                // Regardless of writeSettings we need to ensure that this restriction
12385                // state propagation is persisted
12386                mSettings.writeAllUsersPackageRestrictionsLPr();
12387            }
12388            // can downgrade to reader here
12389            if (writeSettings) {
12390                mSettings.writeLPr();
12391            }
12392        }
12393        return true;
12394    }
12395
12396    private boolean deleteInstalledPackageLI(PackageSetting ps,
12397            boolean deleteCodeAndResources, int flags,
12398            int[] allUserHandles, boolean[] perUserInstalled,
12399            PackageRemovedInfo outInfo, boolean writeSettings) {
12400        if (outInfo != null) {
12401            outInfo.uid = ps.appId;
12402        }
12403
12404        // Delete package data from internal structures and also remove data if flag is set
12405        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12406
12407        // Delete application code and resources
12408        if (deleteCodeAndResources && (outInfo != null)) {
12409            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12410                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12411            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12412        }
12413        return true;
12414    }
12415
12416    @Override
12417    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12418            int userId) {
12419        mContext.enforceCallingOrSelfPermission(
12420                android.Manifest.permission.DELETE_PACKAGES, null);
12421        synchronized (mPackages) {
12422            PackageSetting ps = mSettings.mPackages.get(packageName);
12423            if (ps == null) {
12424                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12425                return false;
12426            }
12427            if (!ps.getInstalled(userId)) {
12428                // Can't block uninstall for an app that is not installed or enabled.
12429                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12430                return false;
12431            }
12432            ps.setBlockUninstall(blockUninstall, userId);
12433            mSettings.writePackageRestrictionsLPr(userId);
12434        }
12435        return true;
12436    }
12437
12438    @Override
12439    public boolean getBlockUninstallForUser(String packageName, int userId) {
12440        synchronized (mPackages) {
12441            PackageSetting ps = mSettings.mPackages.get(packageName);
12442            if (ps == null) {
12443                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12444                return false;
12445            }
12446            return ps.getBlockUninstall(userId);
12447        }
12448    }
12449
12450    /*
12451     * This method handles package deletion in general
12452     */
12453    private boolean deletePackageLI(String packageName, UserHandle user,
12454            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12455            int flags, PackageRemovedInfo outInfo,
12456            boolean writeSettings) {
12457        if (packageName == null) {
12458            Slog.w(TAG, "Attempt to delete null packageName.");
12459            return false;
12460        }
12461        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12462        PackageSetting ps;
12463        boolean dataOnly = false;
12464        int removeUser = -1;
12465        int appId = -1;
12466        synchronized (mPackages) {
12467            ps = mSettings.mPackages.get(packageName);
12468            if (ps == null) {
12469                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12470                return false;
12471            }
12472            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12473                    && user.getIdentifier() != UserHandle.USER_ALL) {
12474                // The caller is asking that the package only be deleted for a single
12475                // user.  To do this, we just mark its uninstalled state and delete
12476                // its data.  If this is a system app, we only allow this to happen if
12477                // they have set the special DELETE_SYSTEM_APP which requests different
12478                // semantics than normal for uninstalling system apps.
12479                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12480                ps.setUserState(user.getIdentifier(),
12481                        COMPONENT_ENABLED_STATE_DEFAULT,
12482                        false, //installed
12483                        true,  //stopped
12484                        true,  //notLaunched
12485                        false, //hidden
12486                        null, null, null,
12487                        false, // blockUninstall
12488                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12489                if (!isSystemApp(ps)) {
12490                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12491                        // Other user still have this package installed, so all
12492                        // we need to do is clear this user's data and save that
12493                        // it is uninstalled.
12494                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12495                        removeUser = user.getIdentifier();
12496                        appId = ps.appId;
12497                        scheduleWritePackageRestrictionsLocked(removeUser);
12498                    } else {
12499                        // We need to set it back to 'installed' so the uninstall
12500                        // broadcasts will be sent correctly.
12501                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12502                        ps.setInstalled(true, user.getIdentifier());
12503                    }
12504                } else {
12505                    // This is a system app, so we assume that the
12506                    // other users still have this package installed, so all
12507                    // we need to do is clear this user's data and save that
12508                    // it is uninstalled.
12509                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12510                    removeUser = user.getIdentifier();
12511                    appId = ps.appId;
12512                    scheduleWritePackageRestrictionsLocked(removeUser);
12513                }
12514            }
12515        }
12516
12517        if (removeUser >= 0) {
12518            // From above, we determined that we are deleting this only
12519            // for a single user.  Continue the work here.
12520            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12521            if (outInfo != null) {
12522                outInfo.removedPackage = packageName;
12523                outInfo.removedAppId = appId;
12524                outInfo.removedUsers = new int[] {removeUser};
12525            }
12526            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12527            removeKeystoreDataIfNeeded(removeUser, appId);
12528            schedulePackageCleaning(packageName, removeUser, false);
12529            synchronized (mPackages) {
12530                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12531                    scheduleWritePackageRestrictionsLocked(removeUser);
12532                }
12533                revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(),
12534                        removeUser);
12535            }
12536            return true;
12537        }
12538
12539        if (dataOnly) {
12540            // Delete application data first
12541            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12542            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12543            return true;
12544        }
12545
12546        boolean ret = false;
12547        if (isSystemApp(ps)) {
12548            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12549            // When an updated system application is deleted we delete the existing resources as well and
12550            // fall back to existing code in system partition
12551            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12552                    flags, outInfo, writeSettings);
12553        } else {
12554            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12555            // Kill application pre-emptively especially for apps on sd.
12556            killApplication(packageName, ps.appId, "uninstall pkg");
12557            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12558                    allUserHandles, perUserInstalled,
12559                    outInfo, writeSettings);
12560        }
12561
12562        return ret;
12563    }
12564
12565    private final class ClearStorageConnection implements ServiceConnection {
12566        IMediaContainerService mContainerService;
12567
12568        @Override
12569        public void onServiceConnected(ComponentName name, IBinder service) {
12570            synchronized (this) {
12571                mContainerService = IMediaContainerService.Stub.asInterface(service);
12572                notifyAll();
12573            }
12574        }
12575
12576        @Override
12577        public void onServiceDisconnected(ComponentName name) {
12578        }
12579    }
12580
12581    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12582        final boolean mounted;
12583        if (Environment.isExternalStorageEmulated()) {
12584            mounted = true;
12585        } else {
12586            final String status = Environment.getExternalStorageState();
12587
12588            mounted = status.equals(Environment.MEDIA_MOUNTED)
12589                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12590        }
12591
12592        if (!mounted) {
12593            return;
12594        }
12595
12596        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12597        int[] users;
12598        if (userId == UserHandle.USER_ALL) {
12599            users = sUserManager.getUserIds();
12600        } else {
12601            users = new int[] { userId };
12602        }
12603        final ClearStorageConnection conn = new ClearStorageConnection();
12604        if (mContext.bindServiceAsUser(
12605                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12606            try {
12607                for (int curUser : users) {
12608                    long timeout = SystemClock.uptimeMillis() + 5000;
12609                    synchronized (conn) {
12610                        long now = SystemClock.uptimeMillis();
12611                        while (conn.mContainerService == null && now < timeout) {
12612                            try {
12613                                conn.wait(timeout - now);
12614                            } catch (InterruptedException e) {
12615                            }
12616                        }
12617                    }
12618                    if (conn.mContainerService == null) {
12619                        return;
12620                    }
12621
12622                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12623                    clearDirectory(conn.mContainerService,
12624                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12625                    if (allData) {
12626                        clearDirectory(conn.mContainerService,
12627                                userEnv.buildExternalStorageAppDataDirs(packageName));
12628                        clearDirectory(conn.mContainerService,
12629                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12630                    }
12631                }
12632            } finally {
12633                mContext.unbindService(conn);
12634            }
12635        }
12636    }
12637
12638    @Override
12639    public void clearApplicationUserData(final String packageName,
12640            final IPackageDataObserver observer, final int userId) {
12641        mContext.enforceCallingOrSelfPermission(
12642                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12643        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12644        // Queue up an async operation since the package deletion may take a little while.
12645        mHandler.post(new Runnable() {
12646            public void run() {
12647                mHandler.removeCallbacks(this);
12648                final boolean succeeded;
12649                synchronized (mInstallLock) {
12650                    succeeded = clearApplicationUserDataLI(packageName, userId);
12651                }
12652                clearExternalStorageDataSync(packageName, userId, true);
12653                if (succeeded) {
12654                    // invoke DeviceStorageMonitor's update method to clear any notifications
12655                    DeviceStorageMonitorInternal
12656                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12657                    if (dsm != null) {
12658                        dsm.checkMemory();
12659                    }
12660                }
12661                if(observer != null) {
12662                    try {
12663                        observer.onRemoveCompleted(packageName, succeeded);
12664                    } catch (RemoteException e) {
12665                        Log.i(TAG, "Observer no longer exists.");
12666                    }
12667                } //end if observer
12668            } //end run
12669        });
12670    }
12671
12672    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12673        if (packageName == null) {
12674            Slog.w(TAG, "Attempt to delete null packageName.");
12675            return false;
12676        }
12677
12678        // Try finding details about the requested package
12679        PackageParser.Package pkg;
12680        synchronized (mPackages) {
12681            pkg = mPackages.get(packageName);
12682            if (pkg == null) {
12683                final PackageSetting ps = mSettings.mPackages.get(packageName);
12684                if (ps != null) {
12685                    pkg = ps.pkg;
12686                }
12687            }
12688
12689            if (pkg == null) {
12690                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12691                return false;
12692            }
12693
12694            PackageSetting ps = (PackageSetting) pkg.mExtras;
12695            PermissionsState permissionsState = ps.getPermissionsState();
12696            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
12697        }
12698
12699        // Always delete data directories for package, even if we found no other
12700        // record of app. This helps users recover from UID mismatches without
12701        // resorting to a full data wipe.
12702        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12703        if (retCode < 0) {
12704            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12705            return false;
12706        }
12707
12708        final int appId = pkg.applicationInfo.uid;
12709        removeKeystoreDataIfNeeded(userId, appId);
12710
12711        // Create a native library symlink only if we have native libraries
12712        // and if the native libraries are 32 bit libraries. We do not provide
12713        // this symlink for 64 bit libraries.
12714        if (pkg.applicationInfo.primaryCpuAbi != null &&
12715                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12716            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12717            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12718                    nativeLibPath, userId) < 0) {
12719                Slog.w(TAG, "Failed linking native library dir");
12720                return false;
12721            }
12722        }
12723
12724        return true;
12725    }
12726
12727
12728    /**
12729     * Revokes granted runtime permissions and clears resettable flags
12730     * which are flags that can be set by a user interaction.
12731     *
12732     * @param permissionsState The permission state to reset.
12733     * @param userId The device user for which to do a reset.
12734     */
12735    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
12736            PermissionsState permissionsState, int userId) {
12737        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
12738                | PackageManager.FLAG_PERMISSION_USER_FIXED
12739                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12740
12741        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags);
12742    }
12743
12744    /**
12745     * Revokes granted runtime permissions and clears all flags.
12746     *
12747     * @param permissionsState The permission state to reset.
12748     * @param userId The device user for which to do a reset.
12749     */
12750    private void revokeRuntimePermissionsAndClearAllFlagsLocked(
12751            PermissionsState permissionsState, int userId) {
12752        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId,
12753                PackageManager.MASK_PERMISSION_FLAGS);
12754    }
12755
12756    /**
12757     * Revokes granted runtime permissions and clears certain flags.
12758     *
12759     * @param permissionsState The permission state to reset.
12760     * @param userId The device user for which to do a reset.
12761     * @param flags The flags that is going to be reset.
12762     */
12763    private void revokeRuntimePermissionsAndClearFlagsLocked(
12764            PermissionsState permissionsState, int userId, int flags) {
12765        boolean needsWrite = false;
12766
12767        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
12768            BasePermission bp = mSettings.mPermissions.get(state.getName());
12769            if (bp != null) {
12770                permissionsState.revokeRuntimePermission(bp, userId);
12771                permissionsState.updatePermissionFlags(bp, userId, flags, 0);
12772                needsWrite = true;
12773            }
12774        }
12775
12776        if (needsWrite) {
12777            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
12778        }
12779    }
12780
12781    /**
12782     * Remove entries from the keystore daemon. Will only remove it if the
12783     * {@code appId} is valid.
12784     */
12785    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12786        if (appId < 0) {
12787            return;
12788        }
12789
12790        final KeyStore keyStore = KeyStore.getInstance();
12791        if (keyStore != null) {
12792            if (userId == UserHandle.USER_ALL) {
12793                for (final int individual : sUserManager.getUserIds()) {
12794                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12795                }
12796            } else {
12797                keyStore.clearUid(UserHandle.getUid(userId, appId));
12798            }
12799        } else {
12800            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12801        }
12802    }
12803
12804    @Override
12805    public void deleteApplicationCacheFiles(final String packageName,
12806            final IPackageDataObserver observer) {
12807        mContext.enforceCallingOrSelfPermission(
12808                android.Manifest.permission.DELETE_CACHE_FILES, null);
12809        // Queue up an async operation since the package deletion may take a little while.
12810        final int userId = UserHandle.getCallingUserId();
12811        mHandler.post(new Runnable() {
12812            public void run() {
12813                mHandler.removeCallbacks(this);
12814                final boolean succeded;
12815                synchronized (mInstallLock) {
12816                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12817                }
12818                clearExternalStorageDataSync(packageName, userId, false);
12819                if (observer != null) {
12820                    try {
12821                        observer.onRemoveCompleted(packageName, succeded);
12822                    } catch (RemoteException e) {
12823                        Log.i(TAG, "Observer no longer exists.");
12824                    }
12825                } //end if observer
12826            } //end run
12827        });
12828    }
12829
12830    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12831        if (packageName == null) {
12832            Slog.w(TAG, "Attempt to delete null packageName.");
12833            return false;
12834        }
12835        PackageParser.Package p;
12836        synchronized (mPackages) {
12837            p = mPackages.get(packageName);
12838        }
12839        if (p == null) {
12840            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12841            return false;
12842        }
12843        final ApplicationInfo applicationInfo = p.applicationInfo;
12844        if (applicationInfo == null) {
12845            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12846            return false;
12847        }
12848        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
12849        if (retCode < 0) {
12850            Slog.w(TAG, "Couldn't remove cache files for package: "
12851                       + packageName + " u" + userId);
12852            return false;
12853        }
12854        return true;
12855    }
12856
12857    @Override
12858    public void getPackageSizeInfo(final String packageName, int userHandle,
12859            final IPackageStatsObserver observer) {
12860        mContext.enforceCallingOrSelfPermission(
12861                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12862        if (packageName == null) {
12863            throw new IllegalArgumentException("Attempt to get size of null packageName");
12864        }
12865
12866        PackageStats stats = new PackageStats(packageName, userHandle);
12867
12868        /*
12869         * Queue up an async operation since the package measurement may take a
12870         * little while.
12871         */
12872        Message msg = mHandler.obtainMessage(INIT_COPY);
12873        msg.obj = new MeasureParams(stats, observer);
12874        mHandler.sendMessage(msg);
12875    }
12876
12877    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12878            PackageStats pStats) {
12879        if (packageName == null) {
12880            Slog.w(TAG, "Attempt to get size of null packageName.");
12881            return false;
12882        }
12883        PackageParser.Package p;
12884        boolean dataOnly = false;
12885        String libDirRoot = null;
12886        String asecPath = null;
12887        PackageSetting ps = null;
12888        synchronized (mPackages) {
12889            p = mPackages.get(packageName);
12890            ps = mSettings.mPackages.get(packageName);
12891            if(p == null) {
12892                dataOnly = true;
12893                if((ps == null) || (ps.pkg == null)) {
12894                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12895                    return false;
12896                }
12897                p = ps.pkg;
12898            }
12899            if (ps != null) {
12900                libDirRoot = ps.legacyNativeLibraryPathString;
12901            }
12902            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12903                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12904                if (secureContainerId != null) {
12905                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12906                }
12907            }
12908        }
12909        String publicSrcDir = null;
12910        if(!dataOnly) {
12911            final ApplicationInfo applicationInfo = p.applicationInfo;
12912            if (applicationInfo == null) {
12913                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12914                return false;
12915            }
12916            if (p.isForwardLocked()) {
12917                publicSrcDir = applicationInfo.getBaseResourcePath();
12918            }
12919        }
12920        // TODO: extend to measure size of split APKs
12921        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12922        // not just the first level.
12923        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12924        // just the primary.
12925        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12926        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
12927                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12928        if (res < 0) {
12929            return false;
12930        }
12931
12932        // Fix-up for forward-locked applications in ASEC containers.
12933        if (!isExternal(p)) {
12934            pStats.codeSize += pStats.externalCodeSize;
12935            pStats.externalCodeSize = 0L;
12936        }
12937
12938        return true;
12939    }
12940
12941
12942    @Override
12943    public void addPackageToPreferred(String packageName) {
12944        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
12945    }
12946
12947    @Override
12948    public void removePackageFromPreferred(String packageName) {
12949        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
12950    }
12951
12952    @Override
12953    public List<PackageInfo> getPreferredPackages(int flags) {
12954        return new ArrayList<PackageInfo>();
12955    }
12956
12957    private int getUidTargetSdkVersionLockedLPr(int uid) {
12958        Object obj = mSettings.getUserIdLPr(uid);
12959        if (obj instanceof SharedUserSetting) {
12960            final SharedUserSetting sus = (SharedUserSetting) obj;
12961            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
12962            final Iterator<PackageSetting> it = sus.packages.iterator();
12963            while (it.hasNext()) {
12964                final PackageSetting ps = it.next();
12965                if (ps.pkg != null) {
12966                    int v = ps.pkg.applicationInfo.targetSdkVersion;
12967                    if (v < vers) vers = v;
12968                }
12969            }
12970            return vers;
12971        } else if (obj instanceof PackageSetting) {
12972            final PackageSetting ps = (PackageSetting) obj;
12973            if (ps.pkg != null) {
12974                return ps.pkg.applicationInfo.targetSdkVersion;
12975            }
12976        }
12977        return Build.VERSION_CODES.CUR_DEVELOPMENT;
12978    }
12979
12980    @Override
12981    public void addPreferredActivity(IntentFilter filter, int match,
12982            ComponentName[] set, ComponentName activity, int userId) {
12983        addPreferredActivityInternal(filter, match, set, activity, true, userId,
12984                "Adding preferred");
12985    }
12986
12987    private void addPreferredActivityInternal(IntentFilter filter, int match,
12988            ComponentName[] set, ComponentName activity, boolean always, int userId,
12989            String opname) {
12990        // writer
12991        int callingUid = Binder.getCallingUid();
12992        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
12993        if (filter.countActions() == 0) {
12994            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12995            return;
12996        }
12997        synchronized (mPackages) {
12998            if (mContext.checkCallingOrSelfPermission(
12999                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13000                    != PackageManager.PERMISSION_GRANTED) {
13001                if (getUidTargetSdkVersionLockedLPr(callingUid)
13002                        < Build.VERSION_CODES.FROYO) {
13003                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13004                            + callingUid);
13005                    return;
13006                }
13007                mContext.enforceCallingOrSelfPermission(
13008                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13009            }
13010
13011            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13012            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13013                    + userId + ":");
13014            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13015            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13016            scheduleWritePackageRestrictionsLocked(userId);
13017        }
13018    }
13019
13020    @Override
13021    public void replacePreferredActivity(IntentFilter filter, int match,
13022            ComponentName[] set, ComponentName activity, int userId) {
13023        if (filter.countActions() != 1) {
13024            throw new IllegalArgumentException(
13025                    "replacePreferredActivity expects filter to have only 1 action.");
13026        }
13027        if (filter.countDataAuthorities() != 0
13028                || filter.countDataPaths() != 0
13029                || filter.countDataSchemes() > 1
13030                || filter.countDataTypes() != 0) {
13031            throw new IllegalArgumentException(
13032                    "replacePreferredActivity expects filter to have no data authorities, " +
13033                    "paths, or types; and at most one scheme.");
13034        }
13035
13036        final int callingUid = Binder.getCallingUid();
13037        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13038        synchronized (mPackages) {
13039            if (mContext.checkCallingOrSelfPermission(
13040                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13041                    != PackageManager.PERMISSION_GRANTED) {
13042                if (getUidTargetSdkVersionLockedLPr(callingUid)
13043                        < Build.VERSION_CODES.FROYO) {
13044                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13045                            + Binder.getCallingUid());
13046                    return;
13047                }
13048                mContext.enforceCallingOrSelfPermission(
13049                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13050            }
13051
13052            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13053            if (pir != null) {
13054                // Get all of the existing entries that exactly match this filter.
13055                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13056                if (existing != null && existing.size() == 1) {
13057                    PreferredActivity cur = existing.get(0);
13058                    if (DEBUG_PREFERRED) {
13059                        Slog.i(TAG, "Checking replace of preferred:");
13060                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13061                        if (!cur.mPref.mAlways) {
13062                            Slog.i(TAG, "  -- CUR; not mAlways!");
13063                        } else {
13064                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13065                            Slog.i(TAG, "  -- CUR: mSet="
13066                                    + Arrays.toString(cur.mPref.mSetComponents));
13067                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13068                            Slog.i(TAG, "  -- NEW: mMatch="
13069                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13070                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13071                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13072                        }
13073                    }
13074                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13075                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13076                            && cur.mPref.sameSet(set)) {
13077                        // Setting the preferred activity to what it happens to be already
13078                        if (DEBUG_PREFERRED) {
13079                            Slog.i(TAG, "Replacing with same preferred activity "
13080                                    + cur.mPref.mShortComponent + " for user "
13081                                    + userId + ":");
13082                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13083                        }
13084                        return;
13085                    }
13086                }
13087
13088                if (existing != null) {
13089                    if (DEBUG_PREFERRED) {
13090                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13091                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13092                    }
13093                    for (int i = 0; i < existing.size(); i++) {
13094                        PreferredActivity pa = existing.get(i);
13095                        if (DEBUG_PREFERRED) {
13096                            Slog.i(TAG, "Removing existing preferred activity "
13097                                    + pa.mPref.mComponent + ":");
13098                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13099                        }
13100                        pir.removeFilter(pa);
13101                    }
13102                }
13103            }
13104            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13105                    "Replacing preferred");
13106        }
13107    }
13108
13109    @Override
13110    public void clearPackagePreferredActivities(String packageName) {
13111        final int uid = Binder.getCallingUid();
13112        // writer
13113        synchronized (mPackages) {
13114            PackageParser.Package pkg = mPackages.get(packageName);
13115            if (pkg == null || pkg.applicationInfo.uid != uid) {
13116                if (mContext.checkCallingOrSelfPermission(
13117                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13118                        != PackageManager.PERMISSION_GRANTED) {
13119                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13120                            < Build.VERSION_CODES.FROYO) {
13121                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13122                                + Binder.getCallingUid());
13123                        return;
13124                    }
13125                    mContext.enforceCallingOrSelfPermission(
13126                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13127                }
13128            }
13129
13130            int user = UserHandle.getCallingUserId();
13131            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13132                scheduleWritePackageRestrictionsLocked(user);
13133            }
13134        }
13135    }
13136
13137    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13138    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13139        ArrayList<PreferredActivity> removed = null;
13140        boolean changed = false;
13141        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13142            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13143            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13144            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13145                continue;
13146            }
13147            Iterator<PreferredActivity> it = pir.filterIterator();
13148            while (it.hasNext()) {
13149                PreferredActivity pa = it.next();
13150                // Mark entry for removal only if it matches the package name
13151                // and the entry is of type "always".
13152                if (packageName == null ||
13153                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13154                                && pa.mPref.mAlways)) {
13155                    if (removed == null) {
13156                        removed = new ArrayList<PreferredActivity>();
13157                    }
13158                    removed.add(pa);
13159                }
13160            }
13161            if (removed != null) {
13162                for (int j=0; j<removed.size(); j++) {
13163                    PreferredActivity pa = removed.get(j);
13164                    pir.removeFilter(pa);
13165                }
13166                changed = true;
13167            }
13168        }
13169        return changed;
13170    }
13171
13172    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13173    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13174        if (userId == UserHandle.USER_ALL) {
13175            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13176                    sUserManager.getUserIds())) {
13177                for (int oneUserId : sUserManager.getUserIds()) {
13178                    scheduleWritePackageRestrictionsLocked(oneUserId);
13179                }
13180            }
13181        } else {
13182            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13183                scheduleWritePackageRestrictionsLocked(userId);
13184            }
13185        }
13186    }
13187
13188
13189    void clearDefaultBrowserIfNeeded(String packageName) {
13190        for (int oneUserId : sUserManager.getUserIds()) {
13191            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13192            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13193            if (packageName.equals(defaultBrowserPackageName)) {
13194                setDefaultBrowserPackageName(null, oneUserId);
13195            }
13196        }
13197    }
13198
13199    @Override
13200    public void resetPreferredActivities(int userId) {
13201        /* TODO: Actually use userId. Why is it being passed in? */
13202        mContext.enforceCallingOrSelfPermission(
13203                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13204        // writer
13205        synchronized (mPackages) {
13206            int user = UserHandle.getCallingUserId();
13207            clearPackagePreferredActivitiesLPw(null, user);
13208            mSettings.readDefaultPreferredAppsLPw(this, user);
13209            scheduleWritePackageRestrictionsLocked(user);
13210        }
13211    }
13212
13213    @Override
13214    public int getPreferredActivities(List<IntentFilter> outFilters,
13215            List<ComponentName> outActivities, String packageName) {
13216
13217        int num = 0;
13218        final int userId = UserHandle.getCallingUserId();
13219        // reader
13220        synchronized (mPackages) {
13221            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13222            if (pir != null) {
13223                final Iterator<PreferredActivity> it = pir.filterIterator();
13224                while (it.hasNext()) {
13225                    final PreferredActivity pa = it.next();
13226                    if (packageName == null
13227                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13228                                    && pa.mPref.mAlways)) {
13229                        if (outFilters != null) {
13230                            outFilters.add(new IntentFilter(pa));
13231                        }
13232                        if (outActivities != null) {
13233                            outActivities.add(pa.mPref.mComponent);
13234                        }
13235                    }
13236                }
13237            }
13238        }
13239
13240        return num;
13241    }
13242
13243    @Override
13244    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13245            int userId) {
13246        int callingUid = Binder.getCallingUid();
13247        if (callingUid != Process.SYSTEM_UID) {
13248            throw new SecurityException(
13249                    "addPersistentPreferredActivity can only be run by the system");
13250        }
13251        if (filter.countActions() == 0) {
13252            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13253            return;
13254        }
13255        synchronized (mPackages) {
13256            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13257                    " :");
13258            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13259            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13260                    new PersistentPreferredActivity(filter, activity));
13261            scheduleWritePackageRestrictionsLocked(userId);
13262        }
13263    }
13264
13265    @Override
13266    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13267        int callingUid = Binder.getCallingUid();
13268        if (callingUid != Process.SYSTEM_UID) {
13269            throw new SecurityException(
13270                    "clearPackagePersistentPreferredActivities can only be run by the system");
13271        }
13272        ArrayList<PersistentPreferredActivity> removed = null;
13273        boolean changed = false;
13274        synchronized (mPackages) {
13275            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13276                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13277                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13278                        .valueAt(i);
13279                if (userId != thisUserId) {
13280                    continue;
13281                }
13282                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13283                while (it.hasNext()) {
13284                    PersistentPreferredActivity ppa = it.next();
13285                    // Mark entry for removal only if it matches the package name.
13286                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13287                        if (removed == null) {
13288                            removed = new ArrayList<PersistentPreferredActivity>();
13289                        }
13290                        removed.add(ppa);
13291                    }
13292                }
13293                if (removed != null) {
13294                    for (int j=0; j<removed.size(); j++) {
13295                        PersistentPreferredActivity ppa = removed.get(j);
13296                        ppir.removeFilter(ppa);
13297                    }
13298                    changed = true;
13299                }
13300            }
13301
13302            if (changed) {
13303                scheduleWritePackageRestrictionsLocked(userId);
13304            }
13305        }
13306    }
13307
13308    /**
13309     * Common machinery for picking apart a restored XML blob and passing
13310     * it to a caller-supplied functor to be applied to the running system.
13311     */
13312    private void restoreFromXml(XmlPullParser parser, int userId,
13313            String expectedStartTag, BlobXmlRestorer functor)
13314            throws IOException, XmlPullParserException {
13315        int type;
13316        while ((type = parser.next()) != XmlPullParser.START_TAG
13317                && type != XmlPullParser.END_DOCUMENT) {
13318        }
13319        if (type != XmlPullParser.START_TAG) {
13320            // oops didn't find a start tag?!
13321            if (DEBUG_BACKUP) {
13322                Slog.e(TAG, "Didn't find start tag during restore");
13323            }
13324            return;
13325        }
13326
13327        // this is supposed to be TAG_PREFERRED_BACKUP
13328        if (!expectedStartTag.equals(parser.getName())) {
13329            if (DEBUG_BACKUP) {
13330                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13331            }
13332            return;
13333        }
13334
13335        // skip interfering stuff, then we're aligned with the backing implementation
13336        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13337        functor.apply(parser, userId);
13338    }
13339
13340    private interface BlobXmlRestorer {
13341        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13342    }
13343
13344    /**
13345     * Non-Binder method, support for the backup/restore mechanism: write the
13346     * full set of preferred activities in its canonical XML format.  Returns the
13347     * XML output as a byte array, or null if there is none.
13348     */
13349    @Override
13350    public byte[] getPreferredActivityBackup(int userId) {
13351        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13352            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13353        }
13354
13355        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13356        try {
13357            final XmlSerializer serializer = new FastXmlSerializer();
13358            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13359            serializer.startDocument(null, true);
13360            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13361
13362            synchronized (mPackages) {
13363                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13364            }
13365
13366            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13367            serializer.endDocument();
13368            serializer.flush();
13369        } catch (Exception e) {
13370            if (DEBUG_BACKUP) {
13371                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13372            }
13373            return null;
13374        }
13375
13376        return dataStream.toByteArray();
13377    }
13378
13379    @Override
13380    public void restorePreferredActivities(byte[] backup, int userId) {
13381        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13382            throw new SecurityException("Only the system may call restorePreferredActivities()");
13383        }
13384
13385        try {
13386            final XmlPullParser parser = Xml.newPullParser();
13387            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13388            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13389                    new BlobXmlRestorer() {
13390                        @Override
13391                        public void apply(XmlPullParser parser, int userId)
13392                                throws XmlPullParserException, IOException {
13393                            synchronized (mPackages) {
13394                                mSettings.readPreferredActivitiesLPw(parser, userId);
13395                            }
13396                        }
13397                    } );
13398        } catch (Exception e) {
13399            if (DEBUG_BACKUP) {
13400                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13401            }
13402        }
13403    }
13404
13405    /**
13406     * Non-Binder method, support for the backup/restore mechanism: write the
13407     * default browser (etc) settings in its canonical XML format.  Returns the default
13408     * browser XML representation as a byte array, or null if there is none.
13409     */
13410    @Override
13411    public byte[] getDefaultAppsBackup(int userId) {
13412        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13413            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13414        }
13415
13416        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13417        try {
13418            final XmlSerializer serializer = new FastXmlSerializer();
13419            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13420            serializer.startDocument(null, true);
13421            serializer.startTag(null, TAG_DEFAULT_APPS);
13422
13423            synchronized (mPackages) {
13424                mSettings.writeDefaultAppsLPr(serializer, userId);
13425            }
13426
13427            serializer.endTag(null, TAG_DEFAULT_APPS);
13428            serializer.endDocument();
13429            serializer.flush();
13430        } catch (Exception e) {
13431            if (DEBUG_BACKUP) {
13432                Slog.e(TAG, "Unable to write default apps for backup", e);
13433            }
13434            return null;
13435        }
13436
13437        return dataStream.toByteArray();
13438    }
13439
13440    @Override
13441    public void restoreDefaultApps(byte[] backup, int userId) {
13442        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13443            throw new SecurityException("Only the system may call restoreDefaultApps()");
13444        }
13445
13446        try {
13447            final XmlPullParser parser = Xml.newPullParser();
13448            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13449            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13450                    new BlobXmlRestorer() {
13451                        @Override
13452                        public void apply(XmlPullParser parser, int userId)
13453                                throws XmlPullParserException, IOException {
13454                            synchronized (mPackages) {
13455                                mSettings.readDefaultAppsLPw(parser, userId);
13456                            }
13457                        }
13458                    } );
13459        } catch (Exception e) {
13460            if (DEBUG_BACKUP) {
13461                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13462            }
13463        }
13464    }
13465
13466    @Override
13467    public byte[] getIntentFilterVerificationBackup(int userId) {
13468        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13469            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
13470        }
13471
13472        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13473        try {
13474            final XmlSerializer serializer = new FastXmlSerializer();
13475            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13476            serializer.startDocument(null, true);
13477            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
13478
13479            synchronized (mPackages) {
13480                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
13481            }
13482
13483            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
13484            serializer.endDocument();
13485            serializer.flush();
13486        } catch (Exception e) {
13487            if (DEBUG_BACKUP) {
13488                Slog.e(TAG, "Unable to write default apps for backup", e);
13489            }
13490            return null;
13491        }
13492
13493        return dataStream.toByteArray();
13494    }
13495
13496    @Override
13497    public void restoreIntentFilterVerification(byte[] backup, int userId) {
13498        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13499            throw new SecurityException("Only the system may call restorePreferredActivities()");
13500        }
13501
13502        try {
13503            final XmlPullParser parser = Xml.newPullParser();
13504            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13505            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
13506                    new BlobXmlRestorer() {
13507                        @Override
13508                        public void apply(XmlPullParser parser, int userId)
13509                                throws XmlPullParserException, IOException {
13510                            synchronized (mPackages) {
13511                                mSettings.readAllDomainVerificationsLPr(parser, userId);
13512                                mSettings.writeLPr();
13513                            }
13514                        }
13515                    } );
13516        } catch (Exception e) {
13517            if (DEBUG_BACKUP) {
13518                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13519            }
13520        }
13521    }
13522
13523    @Override
13524    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13525            int sourceUserId, int targetUserId, int flags) {
13526        mContext.enforceCallingOrSelfPermission(
13527                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13528        int callingUid = Binder.getCallingUid();
13529        enforceOwnerRights(ownerPackage, callingUid);
13530        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13531        if (intentFilter.countActions() == 0) {
13532            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13533            return;
13534        }
13535        synchronized (mPackages) {
13536            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13537                    ownerPackage, targetUserId, flags);
13538            CrossProfileIntentResolver resolver =
13539                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13540            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13541            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13542            if (existing != null) {
13543                int size = existing.size();
13544                for (int i = 0; i < size; i++) {
13545                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13546                        return;
13547                    }
13548                }
13549            }
13550            resolver.addFilter(newFilter);
13551            scheduleWritePackageRestrictionsLocked(sourceUserId);
13552        }
13553    }
13554
13555    @Override
13556    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13557        mContext.enforceCallingOrSelfPermission(
13558                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13559        int callingUid = Binder.getCallingUid();
13560        enforceOwnerRights(ownerPackage, callingUid);
13561        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13562        synchronized (mPackages) {
13563            CrossProfileIntentResolver resolver =
13564                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13565            ArraySet<CrossProfileIntentFilter> set =
13566                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13567            for (CrossProfileIntentFilter filter : set) {
13568                if (filter.getOwnerPackage().equals(ownerPackage)) {
13569                    resolver.removeFilter(filter);
13570                }
13571            }
13572            scheduleWritePackageRestrictionsLocked(sourceUserId);
13573        }
13574    }
13575
13576    // Enforcing that callingUid is owning pkg on userId
13577    private void enforceOwnerRights(String pkg, int callingUid) {
13578        // The system owns everything.
13579        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13580            return;
13581        }
13582        int callingUserId = UserHandle.getUserId(callingUid);
13583        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13584        if (pi == null) {
13585            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13586                    + callingUserId);
13587        }
13588        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13589            throw new SecurityException("Calling uid " + callingUid
13590                    + " does not own package " + pkg);
13591        }
13592    }
13593
13594    @Override
13595    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13596        Intent intent = new Intent(Intent.ACTION_MAIN);
13597        intent.addCategory(Intent.CATEGORY_HOME);
13598
13599        final int callingUserId = UserHandle.getCallingUserId();
13600        List<ResolveInfo> list = queryIntentActivities(intent, null,
13601                PackageManager.GET_META_DATA, callingUserId);
13602        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13603                true, false, false, callingUserId);
13604
13605        allHomeCandidates.clear();
13606        if (list != null) {
13607            for (ResolveInfo ri : list) {
13608                allHomeCandidates.add(ri);
13609            }
13610        }
13611        return (preferred == null || preferred.activityInfo == null)
13612                ? null
13613                : new ComponentName(preferred.activityInfo.packageName,
13614                        preferred.activityInfo.name);
13615    }
13616
13617    @Override
13618    public void setApplicationEnabledSetting(String appPackageName,
13619            int newState, int flags, int userId, String callingPackage) {
13620        if (!sUserManager.exists(userId)) return;
13621        if (callingPackage == null) {
13622            callingPackage = Integer.toString(Binder.getCallingUid());
13623        }
13624        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13625    }
13626
13627    @Override
13628    public void setComponentEnabledSetting(ComponentName componentName,
13629            int newState, int flags, int userId) {
13630        if (!sUserManager.exists(userId)) return;
13631        setEnabledSetting(componentName.getPackageName(),
13632                componentName.getClassName(), newState, flags, userId, null);
13633    }
13634
13635    private void setEnabledSetting(final String packageName, String className, int newState,
13636            final int flags, int userId, String callingPackage) {
13637        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13638              || newState == COMPONENT_ENABLED_STATE_ENABLED
13639              || newState == COMPONENT_ENABLED_STATE_DISABLED
13640              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13641              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13642            throw new IllegalArgumentException("Invalid new component state: "
13643                    + newState);
13644        }
13645        PackageSetting pkgSetting;
13646        final int uid = Binder.getCallingUid();
13647        final int permission = mContext.checkCallingOrSelfPermission(
13648                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13649        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13650        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13651        boolean sendNow = false;
13652        boolean isApp = (className == null);
13653        String componentName = isApp ? packageName : className;
13654        int packageUid = -1;
13655        ArrayList<String> components;
13656
13657        // writer
13658        synchronized (mPackages) {
13659            pkgSetting = mSettings.mPackages.get(packageName);
13660            if (pkgSetting == null) {
13661                if (className == null) {
13662                    throw new IllegalArgumentException(
13663                            "Unknown package: " + packageName);
13664                }
13665                throw new IllegalArgumentException(
13666                        "Unknown component: " + packageName
13667                        + "/" + className);
13668            }
13669            // Allow root and verify that userId is not being specified by a different user
13670            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13671                throw new SecurityException(
13672                        "Permission Denial: attempt to change component state from pid="
13673                        + Binder.getCallingPid()
13674                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13675            }
13676            if (className == null) {
13677                // We're dealing with an application/package level state change
13678                if (pkgSetting.getEnabled(userId) == newState) {
13679                    // Nothing to do
13680                    return;
13681                }
13682                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13683                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13684                    // Don't care about who enables an app.
13685                    callingPackage = null;
13686                }
13687                pkgSetting.setEnabled(newState, userId, callingPackage);
13688                // pkgSetting.pkg.mSetEnabled = newState;
13689            } else {
13690                // We're dealing with a component level state change
13691                // First, verify that this is a valid class name.
13692                PackageParser.Package pkg = pkgSetting.pkg;
13693                if (pkg == null || !pkg.hasComponentClassName(className)) {
13694                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13695                        throw new IllegalArgumentException("Component class " + className
13696                                + " does not exist in " + packageName);
13697                    } else {
13698                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13699                                + className + " does not exist in " + packageName);
13700                    }
13701                }
13702                switch (newState) {
13703                case COMPONENT_ENABLED_STATE_ENABLED:
13704                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13705                        return;
13706                    }
13707                    break;
13708                case COMPONENT_ENABLED_STATE_DISABLED:
13709                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13710                        return;
13711                    }
13712                    break;
13713                case COMPONENT_ENABLED_STATE_DEFAULT:
13714                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13715                        return;
13716                    }
13717                    break;
13718                default:
13719                    Slog.e(TAG, "Invalid new component state: " + newState);
13720                    return;
13721                }
13722            }
13723            scheduleWritePackageRestrictionsLocked(userId);
13724            components = mPendingBroadcasts.get(userId, packageName);
13725            final boolean newPackage = components == null;
13726            if (newPackage) {
13727                components = new ArrayList<String>();
13728            }
13729            if (!components.contains(componentName)) {
13730                components.add(componentName);
13731            }
13732            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
13733                sendNow = true;
13734                // Purge entry from pending broadcast list if another one exists already
13735                // since we are sending one right away.
13736                mPendingBroadcasts.remove(userId, packageName);
13737            } else {
13738                if (newPackage) {
13739                    mPendingBroadcasts.put(userId, packageName, components);
13740                }
13741                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
13742                    // Schedule a message
13743                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
13744                }
13745            }
13746        }
13747
13748        long callingId = Binder.clearCallingIdentity();
13749        try {
13750            if (sendNow) {
13751                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13752                sendPackageChangedBroadcast(packageName,
13753                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13754            }
13755        } finally {
13756            Binder.restoreCallingIdentity(callingId);
13757        }
13758    }
13759
13760    private void sendPackageChangedBroadcast(String packageName,
13761            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13762        if (DEBUG_INSTALL)
13763            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13764                    + componentNames);
13765        Bundle extras = new Bundle(4);
13766        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13767        String nameList[] = new String[componentNames.size()];
13768        componentNames.toArray(nameList);
13769        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13770        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13771        extras.putInt(Intent.EXTRA_UID, packageUid);
13772        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13773                new int[] {UserHandle.getUserId(packageUid)});
13774    }
13775
13776    @Override
13777    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13778        if (!sUserManager.exists(userId)) return;
13779        final int uid = Binder.getCallingUid();
13780        final int permission = mContext.checkCallingOrSelfPermission(
13781                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13782        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13783        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13784        // writer
13785        synchronized (mPackages) {
13786            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
13787                    allowedByPermission, uid, userId)) {
13788                scheduleWritePackageRestrictionsLocked(userId);
13789            }
13790        }
13791    }
13792
13793    @Override
13794    public String getInstallerPackageName(String packageName) {
13795        // reader
13796        synchronized (mPackages) {
13797            return mSettings.getInstallerPackageNameLPr(packageName);
13798        }
13799    }
13800
13801    @Override
13802    public int getApplicationEnabledSetting(String packageName, int userId) {
13803        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13804        int uid = Binder.getCallingUid();
13805        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13806        // reader
13807        synchronized (mPackages) {
13808            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13809        }
13810    }
13811
13812    @Override
13813    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13814        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13815        int uid = Binder.getCallingUid();
13816        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13817        // reader
13818        synchronized (mPackages) {
13819            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13820        }
13821    }
13822
13823    @Override
13824    public void enterSafeMode() {
13825        enforceSystemOrRoot("Only the system can request entering safe mode");
13826
13827        if (!mSystemReady) {
13828            mSafeMode = true;
13829        }
13830    }
13831
13832    @Override
13833    public void systemReady() {
13834        mSystemReady = true;
13835
13836        // Read the compatibilty setting when the system is ready.
13837        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13838                mContext.getContentResolver(),
13839                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13840        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13841        if (DEBUG_SETTINGS) {
13842            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13843        }
13844
13845        synchronized (mPackages) {
13846            // Verify that all of the preferred activity components actually
13847            // exist.  It is possible for applications to be updated and at
13848            // that point remove a previously declared activity component that
13849            // had been set as a preferred activity.  We try to clean this up
13850            // the next time we encounter that preferred activity, but it is
13851            // possible for the user flow to never be able to return to that
13852            // situation so here we do a sanity check to make sure we haven't
13853            // left any junk around.
13854            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13855            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13856                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13857                removed.clear();
13858                for (PreferredActivity pa : pir.filterSet()) {
13859                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13860                        removed.add(pa);
13861                    }
13862                }
13863                if (removed.size() > 0) {
13864                    for (int r=0; r<removed.size(); r++) {
13865                        PreferredActivity pa = removed.get(r);
13866                        Slog.w(TAG, "Removing dangling preferred activity: "
13867                                + pa.mPref.mComponent);
13868                        pir.removeFilter(pa);
13869                    }
13870                    mSettings.writePackageRestrictionsLPr(
13871                            mSettings.mPreferredActivities.keyAt(i));
13872                }
13873            }
13874        }
13875        sUserManager.systemReady();
13876
13877        // Kick off any messages waiting for system ready
13878        if (mPostSystemReadyMessages != null) {
13879            for (Message msg : mPostSystemReadyMessages) {
13880                msg.sendToTarget();
13881            }
13882            mPostSystemReadyMessages = null;
13883        }
13884
13885        // Watch for external volumes that come and go over time
13886        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13887        storage.registerListener(mStorageListener);
13888
13889        mInstallerService.systemReady();
13890        mPackageDexOptimizer.systemReady();
13891    }
13892
13893    @Override
13894    public boolean isSafeMode() {
13895        return mSafeMode;
13896    }
13897
13898    @Override
13899    public boolean hasSystemUidErrors() {
13900        return mHasSystemUidErrors;
13901    }
13902
13903    static String arrayToString(int[] array) {
13904        StringBuffer buf = new StringBuffer(128);
13905        buf.append('[');
13906        if (array != null) {
13907            for (int i=0; i<array.length; i++) {
13908                if (i > 0) buf.append(", ");
13909                buf.append(array[i]);
13910            }
13911        }
13912        buf.append(']');
13913        return buf.toString();
13914    }
13915
13916    static class DumpState {
13917        public static final int DUMP_LIBS = 1 << 0;
13918        public static final int DUMP_FEATURES = 1 << 1;
13919        public static final int DUMP_RESOLVERS = 1 << 2;
13920        public static final int DUMP_PERMISSIONS = 1 << 3;
13921        public static final int DUMP_PACKAGES = 1 << 4;
13922        public static final int DUMP_SHARED_USERS = 1 << 5;
13923        public static final int DUMP_MESSAGES = 1 << 6;
13924        public static final int DUMP_PROVIDERS = 1 << 7;
13925        public static final int DUMP_VERIFIERS = 1 << 8;
13926        public static final int DUMP_PREFERRED = 1 << 9;
13927        public static final int DUMP_PREFERRED_XML = 1 << 10;
13928        public static final int DUMP_KEYSETS = 1 << 11;
13929        public static final int DUMP_VERSION = 1 << 12;
13930        public static final int DUMP_INSTALLS = 1 << 13;
13931        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13932        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13933
13934        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13935
13936        private int mTypes;
13937
13938        private int mOptions;
13939
13940        private boolean mTitlePrinted;
13941
13942        private SharedUserSetting mSharedUser;
13943
13944        public boolean isDumping(int type) {
13945            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13946                return true;
13947            }
13948
13949            return (mTypes & type) != 0;
13950        }
13951
13952        public void setDump(int type) {
13953            mTypes |= type;
13954        }
13955
13956        public boolean isOptionEnabled(int option) {
13957            return (mOptions & option) != 0;
13958        }
13959
13960        public void setOptionEnabled(int option) {
13961            mOptions |= option;
13962        }
13963
13964        public boolean onTitlePrinted() {
13965            final boolean printed = mTitlePrinted;
13966            mTitlePrinted = true;
13967            return printed;
13968        }
13969
13970        public boolean getTitlePrinted() {
13971            return mTitlePrinted;
13972        }
13973
13974        public void setTitlePrinted(boolean enabled) {
13975            mTitlePrinted = enabled;
13976        }
13977
13978        public SharedUserSetting getSharedUser() {
13979            return mSharedUser;
13980        }
13981
13982        public void setSharedUser(SharedUserSetting user) {
13983            mSharedUser = user;
13984        }
13985    }
13986
13987    @Override
13988    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13989        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13990                != PackageManager.PERMISSION_GRANTED) {
13991            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13992                    + Binder.getCallingPid()
13993                    + ", uid=" + Binder.getCallingUid()
13994                    + " without permission "
13995                    + android.Manifest.permission.DUMP);
13996            return;
13997        }
13998
13999        DumpState dumpState = new DumpState();
14000        boolean fullPreferred = false;
14001        boolean checkin = false;
14002
14003        String packageName = null;
14004
14005        int opti = 0;
14006        while (opti < args.length) {
14007            String opt = args[opti];
14008            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14009                break;
14010            }
14011            opti++;
14012
14013            if ("-a".equals(opt)) {
14014                // Right now we only know how to print all.
14015            } else if ("-h".equals(opt)) {
14016                pw.println("Package manager dump options:");
14017                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14018                pw.println("    --checkin: dump for a checkin");
14019                pw.println("    -f: print details of intent filters");
14020                pw.println("    -h: print this help");
14021                pw.println("  cmd may be one of:");
14022                pw.println("    l[ibraries]: list known shared libraries");
14023                pw.println("    f[ibraries]: list device features");
14024                pw.println("    k[eysets]: print known keysets");
14025                pw.println("    r[esolvers]: dump intent resolvers");
14026                pw.println("    perm[issions]: dump permissions");
14027                pw.println("    pref[erred]: print preferred package settings");
14028                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14029                pw.println("    prov[iders]: dump content providers");
14030                pw.println("    p[ackages]: dump installed packages");
14031                pw.println("    s[hared-users]: dump shared user IDs");
14032                pw.println("    m[essages]: print collected runtime messages");
14033                pw.println("    v[erifiers]: print package verifier info");
14034                pw.println("    version: print database version info");
14035                pw.println("    write: write current settings now");
14036                pw.println("    <package.name>: info about given package");
14037                pw.println("    installs: details about install sessions");
14038                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14039                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14040                return;
14041            } else if ("--checkin".equals(opt)) {
14042                checkin = true;
14043            } else if ("-f".equals(opt)) {
14044                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14045            } else {
14046                pw.println("Unknown argument: " + opt + "; use -h for help");
14047            }
14048        }
14049
14050        // Is the caller requesting to dump a particular piece of data?
14051        if (opti < args.length) {
14052            String cmd = args[opti];
14053            opti++;
14054            // Is this a package name?
14055            if ("android".equals(cmd) || cmd.contains(".")) {
14056                packageName = cmd;
14057                // When dumping a single package, we always dump all of its
14058                // filter information since the amount of data will be reasonable.
14059                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14060            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14061                dumpState.setDump(DumpState.DUMP_LIBS);
14062            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14063                dumpState.setDump(DumpState.DUMP_FEATURES);
14064            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14065                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14066            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14067                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14068            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14069                dumpState.setDump(DumpState.DUMP_PREFERRED);
14070            } else if ("preferred-xml".equals(cmd)) {
14071                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14072                if (opti < args.length && "--full".equals(args[opti])) {
14073                    fullPreferred = true;
14074                    opti++;
14075                }
14076            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14077                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14078            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14079                dumpState.setDump(DumpState.DUMP_PACKAGES);
14080            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14081                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14082            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14083                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14084            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14085                dumpState.setDump(DumpState.DUMP_MESSAGES);
14086            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14087                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14088            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14089                    || "intent-filter-verifiers".equals(cmd)) {
14090                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14091            } else if ("version".equals(cmd)) {
14092                dumpState.setDump(DumpState.DUMP_VERSION);
14093            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14094                dumpState.setDump(DumpState.DUMP_KEYSETS);
14095            } else if ("installs".equals(cmd)) {
14096                dumpState.setDump(DumpState.DUMP_INSTALLS);
14097            } else if ("write".equals(cmd)) {
14098                synchronized (mPackages) {
14099                    mSettings.writeLPr();
14100                    pw.println("Settings written.");
14101                    return;
14102                }
14103            }
14104        }
14105
14106        if (checkin) {
14107            pw.println("vers,1");
14108        }
14109
14110        // reader
14111        synchronized (mPackages) {
14112            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14113                if (!checkin) {
14114                    if (dumpState.onTitlePrinted())
14115                        pw.println();
14116                    pw.println("Database versions:");
14117                    pw.print("  SDK Version:");
14118                    pw.print(" internal=");
14119                    pw.print(mSettings.mInternalSdkPlatform);
14120                    pw.print(" external=");
14121                    pw.println(mSettings.mExternalSdkPlatform);
14122                    pw.print("  DB Version:");
14123                    pw.print(" internal=");
14124                    pw.print(mSettings.mInternalDatabaseVersion);
14125                    pw.print(" external=");
14126                    pw.println(mSettings.mExternalDatabaseVersion);
14127                }
14128            }
14129
14130            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14131                if (!checkin) {
14132                    if (dumpState.onTitlePrinted())
14133                        pw.println();
14134                    pw.println("Verifiers:");
14135                    pw.print("  Required: ");
14136                    pw.print(mRequiredVerifierPackage);
14137                    pw.print(" (uid=");
14138                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14139                    pw.println(")");
14140                } else if (mRequiredVerifierPackage != null) {
14141                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14142                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14143                }
14144            }
14145
14146            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14147                    packageName == null) {
14148                if (mIntentFilterVerifierComponent != null) {
14149                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14150                    if (!checkin) {
14151                        if (dumpState.onTitlePrinted())
14152                            pw.println();
14153                        pw.println("Intent Filter Verifier:");
14154                        pw.print("  Using: ");
14155                        pw.print(verifierPackageName);
14156                        pw.print(" (uid=");
14157                        pw.print(getPackageUid(verifierPackageName, 0));
14158                        pw.println(")");
14159                    } else if (verifierPackageName != null) {
14160                        pw.print("ifv,"); pw.print(verifierPackageName);
14161                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14162                    }
14163                } else {
14164                    pw.println();
14165                    pw.println("No Intent Filter Verifier available!");
14166                }
14167            }
14168
14169            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14170                boolean printedHeader = false;
14171                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14172                while (it.hasNext()) {
14173                    String name = it.next();
14174                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14175                    if (!checkin) {
14176                        if (!printedHeader) {
14177                            if (dumpState.onTitlePrinted())
14178                                pw.println();
14179                            pw.println("Libraries:");
14180                            printedHeader = true;
14181                        }
14182                        pw.print("  ");
14183                    } else {
14184                        pw.print("lib,");
14185                    }
14186                    pw.print(name);
14187                    if (!checkin) {
14188                        pw.print(" -> ");
14189                    }
14190                    if (ent.path != null) {
14191                        if (!checkin) {
14192                            pw.print("(jar) ");
14193                            pw.print(ent.path);
14194                        } else {
14195                            pw.print(",jar,");
14196                            pw.print(ent.path);
14197                        }
14198                    } else {
14199                        if (!checkin) {
14200                            pw.print("(apk) ");
14201                            pw.print(ent.apk);
14202                        } else {
14203                            pw.print(",apk,");
14204                            pw.print(ent.apk);
14205                        }
14206                    }
14207                    pw.println();
14208                }
14209            }
14210
14211            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14212                if (dumpState.onTitlePrinted())
14213                    pw.println();
14214                if (!checkin) {
14215                    pw.println("Features:");
14216                }
14217                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14218                while (it.hasNext()) {
14219                    String name = it.next();
14220                    if (!checkin) {
14221                        pw.print("  ");
14222                    } else {
14223                        pw.print("feat,");
14224                    }
14225                    pw.println(name);
14226                }
14227            }
14228
14229            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14230                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14231                        : "Activity Resolver Table:", "  ", packageName,
14232                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14233                    dumpState.setTitlePrinted(true);
14234                }
14235                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14236                        : "Receiver Resolver Table:", "  ", packageName,
14237                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14238                    dumpState.setTitlePrinted(true);
14239                }
14240                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14241                        : "Service Resolver Table:", "  ", packageName,
14242                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14243                    dumpState.setTitlePrinted(true);
14244                }
14245                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14246                        : "Provider Resolver Table:", "  ", packageName,
14247                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14248                    dumpState.setTitlePrinted(true);
14249                }
14250            }
14251
14252            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14253                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14254                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14255                    int user = mSettings.mPreferredActivities.keyAt(i);
14256                    if (pir.dump(pw,
14257                            dumpState.getTitlePrinted()
14258                                ? "\nPreferred Activities User " + user + ":"
14259                                : "Preferred Activities User " + user + ":", "  ",
14260                            packageName, true, false)) {
14261                        dumpState.setTitlePrinted(true);
14262                    }
14263                }
14264            }
14265
14266            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14267                pw.flush();
14268                FileOutputStream fout = new FileOutputStream(fd);
14269                BufferedOutputStream str = new BufferedOutputStream(fout);
14270                XmlSerializer serializer = new FastXmlSerializer();
14271                try {
14272                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14273                    serializer.startDocument(null, true);
14274                    serializer.setFeature(
14275                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14276                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14277                    serializer.endDocument();
14278                    serializer.flush();
14279                } catch (IllegalArgumentException e) {
14280                    pw.println("Failed writing: " + e);
14281                } catch (IllegalStateException e) {
14282                    pw.println("Failed writing: " + e);
14283                } catch (IOException e) {
14284                    pw.println("Failed writing: " + e);
14285                }
14286            }
14287
14288            if (!checkin
14289                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14290                    && packageName == null) {
14291                pw.println();
14292                int count = mSettings.mPackages.size();
14293                if (count == 0) {
14294                    pw.println("No domain preferred apps!");
14295                    pw.println();
14296                } else {
14297                    final String prefix = "  ";
14298                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14299                    if (allPackageSettings.size() == 0) {
14300                        pw.println("No domain preferred apps!");
14301                        pw.println();
14302                    } else {
14303                        pw.println("Domain preferred apps status:");
14304                        pw.println();
14305                        count = 0;
14306                        for (PackageSetting ps : allPackageSettings) {
14307                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14308                            if (ivi == null || ivi.getPackageName() == null) continue;
14309                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14310                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14311                            pw.println(prefix + "Status: " + ivi.getStatusString());
14312                            pw.println();
14313                            count++;
14314                        }
14315                        if (count == 0) {
14316                            pw.println(prefix + "No domain preferred app status!");
14317                            pw.println();
14318                        }
14319                        for (int userId : sUserManager.getUserIds()) {
14320                            pw.println("Domain preferred apps for User " + userId + ":");
14321                            pw.println();
14322                            count = 0;
14323                            for (PackageSetting ps : allPackageSettings) {
14324                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14325                                if (ivi == null || ivi.getPackageName() == null) {
14326                                    continue;
14327                                }
14328                                final int status = ps.getDomainVerificationStatusForUser(userId);
14329                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14330                                    continue;
14331                                }
14332                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14333                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14334                                String statusStr = IntentFilterVerificationInfo.
14335                                        getStatusStringFromValue(status);
14336                                pw.println(prefix + "Status: " + statusStr);
14337                                pw.println();
14338                                count++;
14339                            }
14340                            if (count == 0) {
14341                                pw.println(prefix + "No domain preferred apps!");
14342                                pw.println();
14343                            }
14344                        }
14345                    }
14346                }
14347            }
14348
14349            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14350                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
14351                if (packageName == null) {
14352                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14353                        if (iperm == 0) {
14354                            if (dumpState.onTitlePrinted())
14355                                pw.println();
14356                            pw.println("AppOp Permissions:");
14357                        }
14358                        pw.print("  AppOp Permission ");
14359                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14360                        pw.println(":");
14361                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14362                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14363                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14364                        }
14365                    }
14366                }
14367            }
14368
14369            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14370                boolean printedSomething = false;
14371                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14372                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14373                        continue;
14374                    }
14375                    if (!printedSomething) {
14376                        if (dumpState.onTitlePrinted())
14377                            pw.println();
14378                        pw.println("Registered ContentProviders:");
14379                        printedSomething = true;
14380                    }
14381                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14382                    pw.print("    "); pw.println(p.toString());
14383                }
14384                printedSomething = false;
14385                for (Map.Entry<String, PackageParser.Provider> entry :
14386                        mProvidersByAuthority.entrySet()) {
14387                    PackageParser.Provider p = entry.getValue();
14388                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14389                        continue;
14390                    }
14391                    if (!printedSomething) {
14392                        if (dumpState.onTitlePrinted())
14393                            pw.println();
14394                        pw.println("ContentProvider Authorities:");
14395                        printedSomething = true;
14396                    }
14397                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14398                    pw.print("    "); pw.println(p.toString());
14399                    if (p.info != null && p.info.applicationInfo != null) {
14400                        final String appInfo = p.info.applicationInfo.toString();
14401                        pw.print("      applicationInfo="); pw.println(appInfo);
14402                    }
14403                }
14404            }
14405
14406            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14407                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14408            }
14409
14410            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14411                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
14412            }
14413
14414            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14415                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
14416            }
14417
14418            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14419                // XXX should handle packageName != null by dumping only install data that
14420                // the given package is involved with.
14421                if (dumpState.onTitlePrinted()) pw.println();
14422                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14423            }
14424
14425            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14426                if (dumpState.onTitlePrinted()) pw.println();
14427                mSettings.dumpReadMessagesLPr(pw, dumpState);
14428
14429                pw.println();
14430                pw.println("Package warning messages:");
14431                BufferedReader in = null;
14432                String line = null;
14433                try {
14434                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14435                    while ((line = in.readLine()) != null) {
14436                        if (line.contains("ignored: updated version")) continue;
14437                        pw.println(line);
14438                    }
14439                } catch (IOException ignored) {
14440                } finally {
14441                    IoUtils.closeQuietly(in);
14442                }
14443            }
14444
14445            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14446                BufferedReader in = null;
14447                String line = null;
14448                try {
14449                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14450                    while ((line = in.readLine()) != null) {
14451                        if (line.contains("ignored: updated version")) continue;
14452                        pw.print("msg,");
14453                        pw.println(line);
14454                    }
14455                } catch (IOException ignored) {
14456                } finally {
14457                    IoUtils.closeQuietly(in);
14458                }
14459            }
14460        }
14461    }
14462
14463    // ------- apps on sdcard specific code -------
14464    static final boolean DEBUG_SD_INSTALL = false;
14465
14466    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14467
14468    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14469
14470    private boolean mMediaMounted = false;
14471
14472    static String getEncryptKey() {
14473        try {
14474            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14475                    SD_ENCRYPTION_KEYSTORE_NAME);
14476            if (sdEncKey == null) {
14477                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14478                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14479                if (sdEncKey == null) {
14480                    Slog.e(TAG, "Failed to create encryption keys");
14481                    return null;
14482                }
14483            }
14484            return sdEncKey;
14485        } catch (NoSuchAlgorithmException nsae) {
14486            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14487            return null;
14488        } catch (IOException ioe) {
14489            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14490            return null;
14491        }
14492    }
14493
14494    /*
14495     * Update media status on PackageManager.
14496     */
14497    @Override
14498    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14499        int callingUid = Binder.getCallingUid();
14500        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14501            throw new SecurityException("Media status can only be updated by the system");
14502        }
14503        // reader; this apparently protects mMediaMounted, but should probably
14504        // be a different lock in that case.
14505        synchronized (mPackages) {
14506            Log.i(TAG, "Updating external media status from "
14507                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14508                    + (mediaStatus ? "mounted" : "unmounted"));
14509            if (DEBUG_SD_INSTALL)
14510                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14511                        + ", mMediaMounted=" + mMediaMounted);
14512            if (mediaStatus == mMediaMounted) {
14513                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14514                        : 0, -1);
14515                mHandler.sendMessage(msg);
14516                return;
14517            }
14518            mMediaMounted = mediaStatus;
14519        }
14520        // Queue up an async operation since the package installation may take a
14521        // little while.
14522        mHandler.post(new Runnable() {
14523            public void run() {
14524                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14525            }
14526        });
14527    }
14528
14529    /**
14530     * Called by MountService when the initial ASECs to scan are available.
14531     * Should block until all the ASEC containers are finished being scanned.
14532     */
14533    public void scanAvailableAsecs() {
14534        updateExternalMediaStatusInner(true, false, false);
14535        if (mShouldRestoreconData) {
14536            SELinuxMMAC.setRestoreconDone();
14537            mShouldRestoreconData = false;
14538        }
14539    }
14540
14541    /*
14542     * Collect information of applications on external media, map them against
14543     * existing containers and update information based on current mount status.
14544     * Please note that we always have to report status if reportStatus has been
14545     * set to true especially when unloading packages.
14546     */
14547    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14548            boolean externalStorage) {
14549        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14550        int[] uidArr = EmptyArray.INT;
14551
14552        final String[] list = PackageHelper.getSecureContainerList();
14553        if (ArrayUtils.isEmpty(list)) {
14554            Log.i(TAG, "No secure containers found");
14555        } else {
14556            // Process list of secure containers and categorize them
14557            // as active or stale based on their package internal state.
14558
14559            // reader
14560            synchronized (mPackages) {
14561                for (String cid : list) {
14562                    // Leave stages untouched for now; installer service owns them
14563                    if (PackageInstallerService.isStageName(cid)) continue;
14564
14565                    if (DEBUG_SD_INSTALL)
14566                        Log.i(TAG, "Processing container " + cid);
14567                    String pkgName = getAsecPackageName(cid);
14568                    if (pkgName == null) {
14569                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14570                        continue;
14571                    }
14572                    if (DEBUG_SD_INSTALL)
14573                        Log.i(TAG, "Looking for pkg : " + pkgName);
14574
14575                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14576                    if (ps == null) {
14577                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14578                        continue;
14579                    }
14580
14581                    /*
14582                     * Skip packages that are not external if we're unmounting
14583                     * external storage.
14584                     */
14585                    if (externalStorage && !isMounted && !isExternal(ps)) {
14586                        continue;
14587                    }
14588
14589                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14590                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14591                    // The package status is changed only if the code path
14592                    // matches between settings and the container id.
14593                    if (ps.codePathString != null
14594                            && ps.codePathString.startsWith(args.getCodePath())) {
14595                        if (DEBUG_SD_INSTALL) {
14596                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14597                                    + " at code path: " + ps.codePathString);
14598                        }
14599
14600                        // We do have a valid package installed on sdcard
14601                        processCids.put(args, ps.codePathString);
14602                        final int uid = ps.appId;
14603                        if (uid != -1) {
14604                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14605                        }
14606                    } else {
14607                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14608                                + ps.codePathString);
14609                    }
14610                }
14611            }
14612
14613            Arrays.sort(uidArr);
14614        }
14615
14616        // Process packages with valid entries.
14617        if (isMounted) {
14618            if (DEBUG_SD_INSTALL)
14619                Log.i(TAG, "Loading packages");
14620            loadMediaPackages(processCids, uidArr);
14621            startCleaningPackages();
14622            mInstallerService.onSecureContainersAvailable();
14623        } else {
14624            if (DEBUG_SD_INSTALL)
14625                Log.i(TAG, "Unloading packages");
14626            unloadMediaPackages(processCids, uidArr, reportStatus);
14627        }
14628    }
14629
14630    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14631            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14632        final int size = infos.size();
14633        final String[] packageNames = new String[size];
14634        final int[] packageUids = new int[size];
14635        for (int i = 0; i < size; i++) {
14636            final ApplicationInfo info = infos.get(i);
14637            packageNames[i] = info.packageName;
14638            packageUids[i] = info.uid;
14639        }
14640        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14641                finishedReceiver);
14642    }
14643
14644    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14645            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14646        sendResourcesChangedBroadcast(mediaStatus, replacing,
14647                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14648    }
14649
14650    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14651            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14652        int size = pkgList.length;
14653        if (size > 0) {
14654            // Send broadcasts here
14655            Bundle extras = new Bundle();
14656            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14657            if (uidArr != null) {
14658                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14659            }
14660            if (replacing) {
14661                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14662            }
14663            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14664                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14665            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14666        }
14667    }
14668
14669   /*
14670     * Look at potentially valid container ids from processCids If package
14671     * information doesn't match the one on record or package scanning fails,
14672     * the cid is added to list of removeCids. We currently don't delete stale
14673     * containers.
14674     */
14675    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14676        ArrayList<String> pkgList = new ArrayList<String>();
14677        Set<AsecInstallArgs> keys = processCids.keySet();
14678
14679        for (AsecInstallArgs args : keys) {
14680            String codePath = processCids.get(args);
14681            if (DEBUG_SD_INSTALL)
14682                Log.i(TAG, "Loading container : " + args.cid);
14683            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14684            try {
14685                // Make sure there are no container errors first.
14686                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14687                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14688                            + " when installing from sdcard");
14689                    continue;
14690                }
14691                // Check code path here.
14692                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14693                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14694                            + " does not match one in settings " + codePath);
14695                    continue;
14696                }
14697                // Parse package
14698                int parseFlags = mDefParseFlags;
14699                if (args.isExternalAsec()) {
14700                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
14701                }
14702                if (args.isFwdLocked()) {
14703                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
14704                }
14705
14706                synchronized (mInstallLock) {
14707                    PackageParser.Package pkg = null;
14708                    try {
14709                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
14710                    } catch (PackageManagerException e) {
14711                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
14712                    }
14713                    // Scan the package
14714                    if (pkg != null) {
14715                        /*
14716                         * TODO why is the lock being held? doPostInstall is
14717                         * called in other places without the lock. This needs
14718                         * to be straightened out.
14719                         */
14720                        // writer
14721                        synchronized (mPackages) {
14722                            retCode = PackageManager.INSTALL_SUCCEEDED;
14723                            pkgList.add(pkg.packageName);
14724                            // Post process args
14725                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
14726                                    pkg.applicationInfo.uid);
14727                        }
14728                    } else {
14729                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
14730                    }
14731                }
14732
14733            } finally {
14734                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
14735                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
14736                }
14737            }
14738        }
14739        // writer
14740        synchronized (mPackages) {
14741            // If the platform SDK has changed since the last time we booted,
14742            // we need to re-grant app permission to catch any new ones that
14743            // appear. This is really a hack, and means that apps can in some
14744            // cases get permissions that the user didn't initially explicitly
14745            // allow... it would be nice to have some better way to handle
14746            // this situation.
14747            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
14748            if (regrantPermissions)
14749                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
14750                        + mSdkVersion + "; regranting permissions for external storage");
14751            mSettings.mExternalSdkPlatform = mSdkVersion;
14752
14753            // Make sure group IDs have been assigned, and any permission
14754            // changes in other apps are accounted for
14755            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14756                    | (regrantPermissions
14757                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14758                            : 0));
14759
14760            mSettings.updateExternalDatabaseVersion();
14761
14762            // can downgrade to reader
14763            // Persist settings
14764            mSettings.writeLPr();
14765        }
14766        // Send a broadcast to let everyone know we are done processing
14767        if (pkgList.size() > 0) {
14768            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14769        }
14770    }
14771
14772   /*
14773     * Utility method to unload a list of specified containers
14774     */
14775    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14776        // Just unmount all valid containers.
14777        for (AsecInstallArgs arg : cidArgs) {
14778            synchronized (mInstallLock) {
14779                arg.doPostDeleteLI(false);
14780           }
14781       }
14782   }
14783
14784    /*
14785     * Unload packages mounted on external media. This involves deleting package
14786     * data from internal structures, sending broadcasts about diabled packages,
14787     * gc'ing to free up references, unmounting all secure containers
14788     * corresponding to packages on external media, and posting a
14789     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14790     * that we always have to post this message if status has been requested no
14791     * matter what.
14792     */
14793    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14794            final boolean reportStatus) {
14795        if (DEBUG_SD_INSTALL)
14796            Log.i(TAG, "unloading media packages");
14797        ArrayList<String> pkgList = new ArrayList<String>();
14798        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14799        final Set<AsecInstallArgs> keys = processCids.keySet();
14800        for (AsecInstallArgs args : keys) {
14801            String pkgName = args.getPackageName();
14802            if (DEBUG_SD_INSTALL)
14803                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14804            // Delete package internally
14805            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14806            synchronized (mInstallLock) {
14807                boolean res = deletePackageLI(pkgName, null, false, null, null,
14808                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14809                if (res) {
14810                    pkgList.add(pkgName);
14811                } else {
14812                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14813                    failedList.add(args);
14814                }
14815            }
14816        }
14817
14818        // reader
14819        synchronized (mPackages) {
14820            // We didn't update the settings after removing each package;
14821            // write them now for all packages.
14822            mSettings.writeLPr();
14823        }
14824
14825        // We have to absolutely send UPDATED_MEDIA_STATUS only
14826        // after confirming that all the receivers processed the ordered
14827        // broadcast when packages get disabled, force a gc to clean things up.
14828        // and unload all the containers.
14829        if (pkgList.size() > 0) {
14830            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14831                    new IIntentReceiver.Stub() {
14832                public void performReceive(Intent intent, int resultCode, String data,
14833                        Bundle extras, boolean ordered, boolean sticky,
14834                        int sendingUser) throws RemoteException {
14835                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14836                            reportStatus ? 1 : 0, 1, keys);
14837                    mHandler.sendMessage(msg);
14838                }
14839            });
14840        } else {
14841            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14842                    keys);
14843            mHandler.sendMessage(msg);
14844        }
14845    }
14846
14847    private void loadPrivatePackages(VolumeInfo vol) {
14848        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14849        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14850        synchronized (mInstallLock) {
14851        synchronized (mPackages) {
14852            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14853            for (PackageSetting ps : packages) {
14854                final PackageParser.Package pkg;
14855                try {
14856                    pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14857                    loaded.add(pkg.applicationInfo);
14858                } catch (PackageManagerException e) {
14859                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14860                }
14861            }
14862
14863            // TODO: regrant any permissions that changed based since original install
14864
14865            mSettings.writeLPr();
14866        }
14867        }
14868
14869        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
14870        sendResourcesChangedBroadcast(true, false, loaded, null);
14871    }
14872
14873    private void unloadPrivatePackages(VolumeInfo vol) {
14874        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14875        synchronized (mInstallLock) {
14876        synchronized (mPackages) {
14877            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14878            for (PackageSetting ps : packages) {
14879                if (ps.pkg == null) continue;
14880
14881                final ApplicationInfo info = ps.pkg.applicationInfo;
14882                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14883                if (deletePackageLI(ps.name, null, false, null, null,
14884                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14885                    unloaded.add(info);
14886                } else {
14887                    Slog.w(TAG, "Failed to unload " + ps.codePath);
14888                }
14889            }
14890
14891            mSettings.writeLPr();
14892        }
14893        }
14894
14895        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
14896        sendResourcesChangedBroadcast(false, false, unloaded, null);
14897    }
14898
14899    private void unfreezePackage(String packageName) {
14900        synchronized (mPackages) {
14901            final PackageSetting ps = mSettings.mPackages.get(packageName);
14902            if (ps != null) {
14903                ps.frozen = false;
14904            }
14905        }
14906    }
14907
14908    @Override
14909    public int movePackage(final String packageName, final String volumeUuid) {
14910        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14911
14912        final int moveId = mNextMoveId.getAndIncrement();
14913        try {
14914            movePackageInternal(packageName, volumeUuid, moveId);
14915        } catch (PackageManagerException e) {
14916            Slog.w(TAG, "Failed to move " + packageName, e);
14917            mMoveCallbacks.notifyStatusChanged(moveId,
14918                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14919        }
14920        return moveId;
14921    }
14922
14923    private void movePackageInternal(final String packageName, final String volumeUuid,
14924            final int moveId) throws PackageManagerException {
14925        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14926        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14927        final PackageManager pm = mContext.getPackageManager();
14928
14929        final boolean currentAsec;
14930        final String currentVolumeUuid;
14931        final File codeFile;
14932        final String installerPackageName;
14933        final String packageAbiOverride;
14934        final int appId;
14935        final String seinfo;
14936        final String label;
14937
14938        // reader
14939        synchronized (mPackages) {
14940            final PackageParser.Package pkg = mPackages.get(packageName);
14941            final PackageSetting ps = mSettings.mPackages.get(packageName);
14942            if (pkg == null || ps == null) {
14943                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14944            }
14945
14946            if (pkg.applicationInfo.isSystemApp()) {
14947                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14948                        "Cannot move system application");
14949            }
14950
14951            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
14952                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14953                        "Package already moved to " + volumeUuid);
14954            }
14955
14956            final File probe = new File(pkg.codePath);
14957            final File probeOat = new File(probe, "oat");
14958            if (!probe.isDirectory() || !probeOat.isDirectory()) {
14959                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14960                        "Move only supported for modern cluster style installs");
14961            }
14962
14963            if (ps.frozen) {
14964                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14965                        "Failed to move already frozen package");
14966            }
14967            ps.frozen = true;
14968
14969            currentAsec = pkg.applicationInfo.isForwardLocked()
14970                    || pkg.applicationInfo.isExternalAsec();
14971            currentVolumeUuid = ps.volumeUuid;
14972            codeFile = new File(pkg.codePath);
14973            installerPackageName = ps.installerPackageName;
14974            packageAbiOverride = ps.cpuAbiOverrideString;
14975            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14976            seinfo = pkg.applicationInfo.seinfo;
14977            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
14978        }
14979
14980        // Now that we're guarded by frozen state, kill app during move
14981        killApplication(packageName, appId, "move pkg");
14982
14983        final Bundle extras = new Bundle();
14984        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
14985        extras.putString(Intent.EXTRA_TITLE, label);
14986        mMoveCallbacks.notifyCreated(moveId, extras);
14987
14988        int installFlags;
14989        final boolean moveCompleteApp;
14990        final File measurePath;
14991
14992        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
14993            installFlags = INSTALL_INTERNAL;
14994            moveCompleteApp = !currentAsec;
14995            measurePath = Environment.getDataAppDirectory(volumeUuid);
14996        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
14997            installFlags = INSTALL_EXTERNAL;
14998            moveCompleteApp = false;
14999            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15000        } else {
15001            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15002            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15003                    || !volume.isMountedWritable()) {
15004                unfreezePackage(packageName);
15005                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15006                        "Move location not mounted private volume");
15007            }
15008
15009            Preconditions.checkState(!currentAsec);
15010
15011            installFlags = INSTALL_INTERNAL;
15012            moveCompleteApp = true;
15013            measurePath = Environment.getDataAppDirectory(volumeUuid);
15014        }
15015
15016        final PackageStats stats = new PackageStats(null, -1);
15017        synchronized (mInstaller) {
15018            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15019                unfreezePackage(packageName);
15020                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15021                        "Failed to measure package size");
15022            }
15023        }
15024
15025        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15026                + stats.dataSize);
15027
15028        final long startFreeBytes = measurePath.getFreeSpace();
15029        final long sizeBytes;
15030        if (moveCompleteApp) {
15031            sizeBytes = stats.codeSize + stats.dataSize;
15032        } else {
15033            sizeBytes = stats.codeSize;
15034        }
15035
15036        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15037            unfreezePackage(packageName);
15038            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15039                    "Not enough free space to move");
15040        }
15041
15042        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15043
15044        final CountDownLatch installedLatch = new CountDownLatch(1);
15045        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15046            @Override
15047            public void onUserActionRequired(Intent intent) throws RemoteException {
15048                throw new IllegalStateException();
15049            }
15050
15051            @Override
15052            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15053                    Bundle extras) throws RemoteException {
15054                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15055                        + PackageManager.installStatusToString(returnCode, msg));
15056
15057                installedLatch.countDown();
15058
15059                // Regardless of success or failure of the move operation,
15060                // always unfreeze the package
15061                unfreezePackage(packageName);
15062
15063                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15064                switch (status) {
15065                    case PackageInstaller.STATUS_SUCCESS:
15066                        mMoveCallbacks.notifyStatusChanged(moveId,
15067                                PackageManager.MOVE_SUCCEEDED);
15068                        break;
15069                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15070                        mMoveCallbacks.notifyStatusChanged(moveId,
15071                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15072                        break;
15073                    default:
15074                        mMoveCallbacks.notifyStatusChanged(moveId,
15075                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15076                        break;
15077                }
15078            }
15079        };
15080
15081        final MoveInfo move;
15082        if (moveCompleteApp) {
15083            // Kick off a thread to report progress estimates
15084            new Thread() {
15085                @Override
15086                public void run() {
15087                    while (true) {
15088                        try {
15089                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15090                                break;
15091                            }
15092                        } catch (InterruptedException ignored) {
15093                        }
15094
15095                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15096                        final int progress = 10 + (int) MathUtils.constrain(
15097                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15098                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15099                    }
15100                }
15101            }.start();
15102
15103            final String dataAppName = codeFile.getName();
15104            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15105                    dataAppName, appId, seinfo);
15106        } else {
15107            move = null;
15108        }
15109
15110        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15111
15112        final Message msg = mHandler.obtainMessage(INIT_COPY);
15113        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15114        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15115                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15116        mHandler.sendMessage(msg);
15117    }
15118
15119    @Override
15120    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15121        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15122
15123        final int realMoveId = mNextMoveId.getAndIncrement();
15124        final Bundle extras = new Bundle();
15125        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15126        mMoveCallbacks.notifyCreated(realMoveId, extras);
15127
15128        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15129            @Override
15130            public void onCreated(int moveId, Bundle extras) {
15131                // Ignored
15132            }
15133
15134            @Override
15135            public void onStatusChanged(int moveId, int status, long estMillis) {
15136                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15137            }
15138        };
15139
15140        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15141        storage.setPrimaryStorageUuid(volumeUuid, callback);
15142        return realMoveId;
15143    }
15144
15145    @Override
15146    public int getMoveStatus(int moveId) {
15147        mContext.enforceCallingOrSelfPermission(
15148                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15149        return mMoveCallbacks.mLastStatus.get(moveId);
15150    }
15151
15152    @Override
15153    public void registerMoveCallback(IPackageMoveObserver callback) {
15154        mContext.enforceCallingOrSelfPermission(
15155                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15156        mMoveCallbacks.register(callback);
15157    }
15158
15159    @Override
15160    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15161        mContext.enforceCallingOrSelfPermission(
15162                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15163        mMoveCallbacks.unregister(callback);
15164    }
15165
15166    @Override
15167    public boolean setInstallLocation(int loc) {
15168        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15169                null);
15170        if (getInstallLocation() == loc) {
15171            return true;
15172        }
15173        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15174                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15175            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15176                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15177            return true;
15178        }
15179        return false;
15180   }
15181
15182    @Override
15183    public int getInstallLocation() {
15184        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15185                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15186                PackageHelper.APP_INSTALL_AUTO);
15187    }
15188
15189    /** Called by UserManagerService */
15190    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15191        mDirtyUsers.remove(userHandle);
15192        mSettings.removeUserLPw(userHandle);
15193        mPendingBroadcasts.remove(userHandle);
15194        if (mInstaller != null) {
15195            // Technically, we shouldn't be doing this with the package lock
15196            // held.  However, this is very rare, and there is already so much
15197            // other disk I/O going on, that we'll let it slide for now.
15198            final StorageManager storage = StorageManager.from(mContext);
15199            final List<VolumeInfo> vols = storage.getVolumes();
15200            for (VolumeInfo vol : vols) {
15201                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
15202                    final String volumeUuid = vol.getFsUuid();
15203                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15204                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15205                }
15206            }
15207        }
15208        mUserNeedsBadging.delete(userHandle);
15209        removeUnusedPackagesLILPw(userManager, userHandle);
15210    }
15211
15212    /**
15213     * We're removing userHandle and would like to remove any downloaded packages
15214     * that are no longer in use by any other user.
15215     * @param userHandle the user being removed
15216     */
15217    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15218        final boolean DEBUG_CLEAN_APKS = false;
15219        int [] users = userManager.getUserIdsLPr();
15220        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15221        while (psit.hasNext()) {
15222            PackageSetting ps = psit.next();
15223            if (ps.pkg == null) {
15224                continue;
15225            }
15226            final String packageName = ps.pkg.packageName;
15227            // Skip over if system app
15228            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15229                continue;
15230            }
15231            if (DEBUG_CLEAN_APKS) {
15232                Slog.i(TAG, "Checking package " + packageName);
15233            }
15234            boolean keep = false;
15235            for (int i = 0; i < users.length; i++) {
15236                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15237                    keep = true;
15238                    if (DEBUG_CLEAN_APKS) {
15239                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15240                                + users[i]);
15241                    }
15242                    break;
15243                }
15244            }
15245            if (!keep) {
15246                if (DEBUG_CLEAN_APKS) {
15247                    Slog.i(TAG, "  Removing package " + packageName);
15248                }
15249                mHandler.post(new Runnable() {
15250                    public void run() {
15251                        deletePackageX(packageName, userHandle, 0);
15252                    } //end run
15253                });
15254            }
15255        }
15256    }
15257
15258    /** Called by UserManagerService */
15259    void createNewUserLILPw(int userHandle, File path) {
15260        if (mInstaller != null) {
15261            mInstaller.createUserConfig(userHandle);
15262            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
15263        }
15264    }
15265
15266    void newUserCreatedLILPw(int userHandle) {
15267        // Adding a user requires updating runtime permissions for system apps.
15268        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
15269    }
15270
15271    @Override
15272    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15273        mContext.enforceCallingOrSelfPermission(
15274                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15275                "Only package verification agents can read the verifier device identity");
15276
15277        synchronized (mPackages) {
15278            return mSettings.getVerifierDeviceIdentityLPw();
15279        }
15280    }
15281
15282    @Override
15283    public void setPermissionEnforced(String permission, boolean enforced) {
15284        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15285        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15286            synchronized (mPackages) {
15287                if (mSettings.mReadExternalStorageEnforced == null
15288                        || mSettings.mReadExternalStorageEnforced != enforced) {
15289                    mSettings.mReadExternalStorageEnforced = enforced;
15290                    mSettings.writeLPr();
15291                }
15292            }
15293            // kill any non-foreground processes so we restart them and
15294            // grant/revoke the GID.
15295            final IActivityManager am = ActivityManagerNative.getDefault();
15296            if (am != null) {
15297                final long token = Binder.clearCallingIdentity();
15298                try {
15299                    am.killProcessesBelowForeground("setPermissionEnforcement");
15300                } catch (RemoteException e) {
15301                } finally {
15302                    Binder.restoreCallingIdentity(token);
15303                }
15304            }
15305        } else {
15306            throw new IllegalArgumentException("No selective enforcement for " + permission);
15307        }
15308    }
15309
15310    @Override
15311    @Deprecated
15312    public boolean isPermissionEnforced(String permission) {
15313        return true;
15314    }
15315
15316    @Override
15317    public boolean isStorageLow() {
15318        final long token = Binder.clearCallingIdentity();
15319        try {
15320            final DeviceStorageMonitorInternal
15321                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15322            if (dsm != null) {
15323                return dsm.isMemoryLow();
15324            } else {
15325                return false;
15326            }
15327        } finally {
15328            Binder.restoreCallingIdentity(token);
15329        }
15330    }
15331
15332    @Override
15333    public IPackageInstaller getPackageInstaller() {
15334        return mInstallerService;
15335    }
15336
15337    private boolean userNeedsBadging(int userId) {
15338        int index = mUserNeedsBadging.indexOfKey(userId);
15339        if (index < 0) {
15340            final UserInfo userInfo;
15341            final long token = Binder.clearCallingIdentity();
15342            try {
15343                userInfo = sUserManager.getUserInfo(userId);
15344            } finally {
15345                Binder.restoreCallingIdentity(token);
15346            }
15347            final boolean b;
15348            if (userInfo != null && userInfo.isManagedProfile()) {
15349                b = true;
15350            } else {
15351                b = false;
15352            }
15353            mUserNeedsBadging.put(userId, b);
15354            return b;
15355        }
15356        return mUserNeedsBadging.valueAt(index);
15357    }
15358
15359    @Override
15360    public KeySet getKeySetByAlias(String packageName, String alias) {
15361        if (packageName == null || alias == null) {
15362            return null;
15363        }
15364        synchronized(mPackages) {
15365            final PackageParser.Package pkg = mPackages.get(packageName);
15366            if (pkg == null) {
15367                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15368                throw new IllegalArgumentException("Unknown package: " + packageName);
15369            }
15370            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15371            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15372        }
15373    }
15374
15375    @Override
15376    public KeySet getSigningKeySet(String packageName) {
15377        if (packageName == null) {
15378            return null;
15379        }
15380        synchronized(mPackages) {
15381            final PackageParser.Package pkg = mPackages.get(packageName);
15382            if (pkg == null) {
15383                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15384                throw new IllegalArgumentException("Unknown package: " + packageName);
15385            }
15386            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15387                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15388                throw new SecurityException("May not access signing KeySet of other apps.");
15389            }
15390            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15391            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15392        }
15393    }
15394
15395    @Override
15396    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15397        if (packageName == null || ks == null) {
15398            return false;
15399        }
15400        synchronized(mPackages) {
15401            final PackageParser.Package pkg = mPackages.get(packageName);
15402            if (pkg == null) {
15403                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15404                throw new IllegalArgumentException("Unknown package: " + packageName);
15405            }
15406            IBinder ksh = ks.getToken();
15407            if (ksh instanceof KeySetHandle) {
15408                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15409                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15410            }
15411            return false;
15412        }
15413    }
15414
15415    @Override
15416    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15417        if (packageName == null || ks == null) {
15418            return false;
15419        }
15420        synchronized(mPackages) {
15421            final PackageParser.Package pkg = mPackages.get(packageName);
15422            if (pkg == null) {
15423                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15424                throw new IllegalArgumentException("Unknown package: " + packageName);
15425            }
15426            IBinder ksh = ks.getToken();
15427            if (ksh instanceof KeySetHandle) {
15428                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15429                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15430            }
15431            return false;
15432        }
15433    }
15434
15435    public void getUsageStatsIfNoPackageUsageInfo() {
15436        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15437            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15438            if (usm == null) {
15439                throw new IllegalStateException("UsageStatsManager must be initialized");
15440            }
15441            long now = System.currentTimeMillis();
15442            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15443            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15444                String packageName = entry.getKey();
15445                PackageParser.Package pkg = mPackages.get(packageName);
15446                if (pkg == null) {
15447                    continue;
15448                }
15449                UsageStats usage = entry.getValue();
15450                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15451                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15452            }
15453        }
15454    }
15455
15456    /**
15457     * Check and throw if the given before/after packages would be considered a
15458     * downgrade.
15459     */
15460    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15461            throws PackageManagerException {
15462        if (after.versionCode < before.mVersionCode) {
15463            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15464                    "Update version code " + after.versionCode + " is older than current "
15465                    + before.mVersionCode);
15466        } else if (after.versionCode == before.mVersionCode) {
15467            if (after.baseRevisionCode < before.baseRevisionCode) {
15468                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15469                        "Update base revision code " + after.baseRevisionCode
15470                        + " is older than current " + before.baseRevisionCode);
15471            }
15472
15473            if (!ArrayUtils.isEmpty(after.splitNames)) {
15474                for (int i = 0; i < after.splitNames.length; i++) {
15475                    final String splitName = after.splitNames[i];
15476                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15477                    if (j != -1) {
15478                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15479                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15480                                    "Update split " + splitName + " revision code "
15481                                    + after.splitRevisionCodes[i] + " is older than current "
15482                                    + before.splitRevisionCodes[j]);
15483                        }
15484                    }
15485                }
15486            }
15487        }
15488    }
15489
15490    private static class MoveCallbacks extends Handler {
15491        private static final int MSG_CREATED = 1;
15492        private static final int MSG_STATUS_CHANGED = 2;
15493
15494        private final RemoteCallbackList<IPackageMoveObserver>
15495                mCallbacks = new RemoteCallbackList<>();
15496
15497        private final SparseIntArray mLastStatus = new SparseIntArray();
15498
15499        public MoveCallbacks(Looper looper) {
15500            super(looper);
15501        }
15502
15503        public void register(IPackageMoveObserver callback) {
15504            mCallbacks.register(callback);
15505        }
15506
15507        public void unregister(IPackageMoveObserver callback) {
15508            mCallbacks.unregister(callback);
15509        }
15510
15511        @Override
15512        public void handleMessage(Message msg) {
15513            final SomeArgs args = (SomeArgs) msg.obj;
15514            final int n = mCallbacks.beginBroadcast();
15515            for (int i = 0; i < n; i++) {
15516                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15517                try {
15518                    invokeCallback(callback, msg.what, args);
15519                } catch (RemoteException ignored) {
15520                }
15521            }
15522            mCallbacks.finishBroadcast();
15523            args.recycle();
15524        }
15525
15526        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15527                throws RemoteException {
15528            switch (what) {
15529                case MSG_CREATED: {
15530                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15531                    break;
15532                }
15533                case MSG_STATUS_CHANGED: {
15534                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15535                    break;
15536                }
15537            }
15538        }
15539
15540        private void notifyCreated(int moveId, Bundle extras) {
15541            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15542
15543            final SomeArgs args = SomeArgs.obtain();
15544            args.argi1 = moveId;
15545            args.arg2 = extras;
15546            obtainMessage(MSG_CREATED, args).sendToTarget();
15547        }
15548
15549        private void notifyStatusChanged(int moveId, int status) {
15550            notifyStatusChanged(moveId, status, -1);
15551        }
15552
15553        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15554            Slog.v(TAG, "Move " + moveId + " status " + status);
15555
15556            final SomeArgs args = SomeArgs.obtain();
15557            args.argi1 = moveId;
15558            args.argi2 = status;
15559            args.arg3 = estMillis;
15560            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15561
15562            synchronized (mLastStatus) {
15563                mLastStatus.put(moveId, status);
15564            }
15565        }
15566    }
15567
15568    private final class OnPermissionChangeListeners extends Handler {
15569        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
15570
15571        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
15572                new RemoteCallbackList<>();
15573
15574        public OnPermissionChangeListeners(Looper looper) {
15575            super(looper);
15576        }
15577
15578        @Override
15579        public void handleMessage(Message msg) {
15580            switch (msg.what) {
15581                case MSG_ON_PERMISSIONS_CHANGED: {
15582                    final int uid = msg.arg1;
15583                    handleOnPermissionsChanged(uid);
15584                } break;
15585            }
15586        }
15587
15588        public void addListenerLocked(IOnPermissionsChangeListener listener) {
15589            mPermissionListeners.register(listener);
15590
15591        }
15592
15593        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
15594            mPermissionListeners.unregister(listener);
15595        }
15596
15597        public void onPermissionsChanged(int uid) {
15598            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
15599                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
15600            }
15601        }
15602
15603        private void handleOnPermissionsChanged(int uid) {
15604            final int count = mPermissionListeners.beginBroadcast();
15605            try {
15606                for (int i = 0; i < count; i++) {
15607                    IOnPermissionsChangeListener callback = mPermissionListeners
15608                            .getBroadcastItem(i);
15609                    try {
15610                        callback.onPermissionsChanged(uid);
15611                    } catch (RemoteException e) {
15612                        Log.e(TAG, "Permission listener is dead", e);
15613                    }
15614                }
15615            } finally {
15616                mPermissionListeners.finishBroadcast();
15617            }
15618        }
15619    }
15620}
15621