PackageManagerService.java revision af6052f5464844ba6242a514cdaacc7e259f190b
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.PACKAGE_INFO_GID;
59import static android.os.Process.SYSTEM_UID;
60import static android.system.OsConstants.O_CREAT;
61import static android.system.OsConstants.O_RDWR;
62import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
64import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
65import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
66import static com.android.internal.util.ArrayUtils.appendInt;
67import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
68import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
70import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
71import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
72
73import android.Manifest;
74import android.app.ActivityManager;
75import android.app.ActivityManagerNative;
76import android.app.AppGlobals;
77import android.app.IActivityManager;
78import android.app.admin.IDevicePolicyManager;
79import android.app.backup.IBackupManager;
80import android.app.usage.UsageStats;
81import android.app.usage.UsageStatsManager;
82import android.content.BroadcastReceiver;
83import android.content.ComponentName;
84import android.content.Context;
85import android.content.IIntentReceiver;
86import android.content.Intent;
87import android.content.IntentFilter;
88import android.content.IntentSender;
89import android.content.IntentSender.SendIntentException;
90import android.content.ServiceConnection;
91import android.content.pm.ActivityInfo;
92import android.content.pm.ApplicationInfo;
93import android.content.pm.FeatureInfo;
94import android.content.pm.IOnPermissionsChangeListener;
95import android.content.pm.IPackageDataObserver;
96import android.content.pm.IPackageDeleteObserver;
97import android.content.pm.IPackageDeleteObserver2;
98import android.content.pm.IPackageInstallObserver2;
99import android.content.pm.IPackageInstaller;
100import android.content.pm.IPackageManager;
101import android.content.pm.IPackageMoveObserver;
102import android.content.pm.IPackageStatsObserver;
103import android.content.pm.InstrumentationInfo;
104import android.content.pm.IntentFilterVerificationInfo;
105import android.content.pm.KeySet;
106import android.content.pm.ManifestDigest;
107import android.content.pm.PackageCleanItem;
108import android.content.pm.PackageInfo;
109import android.content.pm.PackageInfoLite;
110import android.content.pm.PackageInstaller;
111import android.content.pm.PackageManager;
112import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
113import android.content.pm.PackageManagerInternal;
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 *
261runtest -c android.content.pm.PackageManagerTests frameworks-core
262 *
263 * {@hide}
264 */
265public class PackageManagerService extends IPackageManager.Stub {
266    static final String TAG = "PackageManager";
267    static final boolean DEBUG_SETTINGS = false;
268    static final boolean DEBUG_PREFERRED = false;
269    static final boolean DEBUG_UPGRADE = false;
270    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
271    private static final boolean DEBUG_BACKUP = true;
272    private static final boolean DEBUG_INSTALL = false;
273    private static final boolean DEBUG_REMOVE = false;
274    private static final boolean DEBUG_BROADCASTS = false;
275    private static final boolean DEBUG_SHOW_INFO = false;
276    private static final boolean DEBUG_PACKAGE_INFO = false;
277    private static final boolean DEBUG_INTENT_MATCHING = false;
278    private static final boolean DEBUG_PACKAGE_SCANNING = false;
279    private static final boolean DEBUG_VERIFY = false;
280    private static final boolean DEBUG_DEXOPT = false;
281    private static final boolean DEBUG_ABI_SELECTION = false;
282
283    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
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    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
556            new DefaultPermissionGrantPolicy(this);
557
558    private static class IFVerificationParams {
559        PackageParser.Package pkg;
560        boolean replacing;
561        int userId;
562        int verifierUid;
563
564        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
565                int _userId, int _verifierUid) {
566            pkg = _pkg;
567            replacing = _replacing;
568            userId = _userId;
569            replacing = _replacing;
570            verifierUid = _verifierUid;
571        }
572    }
573
574    private interface IntentFilterVerifier<T extends IntentFilter> {
575        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
576                                               T filter, String packageName);
577        void startVerifications(int userId);
578        void receiveVerificationResponse(int verificationId);
579    }
580
581    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
582        private Context mContext;
583        private ComponentName mIntentFilterVerifierComponent;
584        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
585
586        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
587            mContext = context;
588            mIntentFilterVerifierComponent = verifierComponent;
589        }
590
591        private String getDefaultScheme() {
592            return IntentFilter.SCHEME_HTTPS;
593        }
594
595        @Override
596        public void startVerifications(int userId) {
597            // Launch verifications requests
598            int count = mCurrentIntentFilterVerifications.size();
599            for (int n=0; n<count; n++) {
600                int verificationId = mCurrentIntentFilterVerifications.get(n);
601                final IntentFilterVerificationState ivs =
602                        mIntentFilterVerificationStates.get(verificationId);
603
604                String packageName = ivs.getPackageName();
605
606                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
607                final int filterCount = filters.size();
608                ArraySet<String> domainsSet = new ArraySet<>();
609                for (int m=0; m<filterCount; m++) {
610                    PackageParser.ActivityIntentInfo filter = filters.get(m);
611                    domainsSet.addAll(filter.getHostsList());
612                }
613                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
614                synchronized (mPackages) {
615                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
616                            packageName, domainsList) != null) {
617                        scheduleWriteSettingsLocked();
618                    }
619                }
620                sendVerificationRequest(userId, verificationId, ivs);
621            }
622            mCurrentIntentFilterVerifications.clear();
623        }
624
625        private void sendVerificationRequest(int userId, int verificationId,
626                IntentFilterVerificationState ivs) {
627
628            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
629            verificationIntent.putExtra(
630                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
631                    verificationId);
632            verificationIntent.putExtra(
633                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
634                    getDefaultScheme());
635            verificationIntent.putExtra(
636                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
637                    ivs.getHostsString());
638            verificationIntent.putExtra(
639                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
640                    ivs.getPackageName());
641            verificationIntent.setComponent(mIntentFilterVerifierComponent);
642            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
643
644            UserHandle user = new UserHandle(userId);
645            mContext.sendBroadcastAsUser(verificationIntent, user);
646            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
647                    "Sending IntentFilter verification broadcast");
648        }
649
650        public void receiveVerificationResponse(int verificationId) {
651            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
652
653            final boolean verified = ivs.isVerified();
654
655            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
656            final int count = filters.size();
657            if (DEBUG_DOMAIN_VERIFICATION) {
658                Slog.i(TAG, "Received verification response " + verificationId
659                        + " for " + count + " filters, verified=" + verified);
660            }
661            for (int n=0; n<count; n++) {
662                PackageParser.ActivityIntentInfo filter = filters.get(n);
663                filter.setVerified(verified);
664
665                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
666                        + " verified with result:" + verified + " and hosts:"
667                        + ivs.getHostsString());
668            }
669
670            mIntentFilterVerificationStates.remove(verificationId);
671
672            final String packageName = ivs.getPackageName();
673            IntentFilterVerificationInfo ivi = null;
674
675            synchronized (mPackages) {
676                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
677            }
678            if (ivi == null) {
679                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
680                        + verificationId + " packageName:" + packageName);
681                return;
682            }
683            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
684                    "Updating IntentFilterVerificationInfo for verificationId:" + verificationId);
685
686            synchronized (mPackages) {
687                if (verified) {
688                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
689                } else {
690                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
691                }
692                scheduleWriteSettingsLocked();
693
694                final int userId = ivs.getUserId();
695                if (userId != UserHandle.USER_ALL) {
696                    final int userStatus =
697                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
698
699                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
700                    boolean needUpdate = false;
701
702                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
703                    // already been set by the User thru the Disambiguation dialog
704                    switch (userStatus) {
705                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
706                            if (verified) {
707                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
708                            } else {
709                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
710                            }
711                            needUpdate = true;
712                            break;
713
714                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
715                            if (verified) {
716                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
717                                needUpdate = true;
718                            }
719                            break;
720
721                        default:
722                            // Nothing to do
723                    }
724
725                    if (needUpdate) {
726                        mSettings.updateIntentFilterVerificationStatusLPw(
727                                packageName, updatedStatus, userId);
728                        scheduleWritePackageRestrictionsLocked(userId);
729                    }
730                }
731            }
732        }
733
734        @Override
735        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
736                    ActivityIntentInfo filter, String packageName) {
737            if (!hasValidDomains(filter)) {
738                return false;
739            }
740            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
741            if (ivs == null) {
742                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
743                        packageName);
744            }
745            if (DEBUG_DOMAIN_VERIFICATION) {
746                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
747            }
748            ivs.addFilter(filter);
749            return true;
750        }
751
752        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
753                int userId, int verificationId, String packageName) {
754            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
755                    verifierUid, userId, packageName);
756            ivs.setPendingState();
757            synchronized (mPackages) {
758                mIntentFilterVerificationStates.append(verificationId, ivs);
759                mCurrentIntentFilterVerifications.add(verificationId);
760            }
761            return ivs;
762        }
763    }
764
765    private static boolean hasValidDomains(ActivityIntentInfo filter) {
766        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
767                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
768        if (!hasHTTPorHTTPS) {
769            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
770                    "IntentFilter does not contain any HTTP or HTTPS data scheme");
771            return false;
772        }
773        return true;
774    }
775
776    private IntentFilterVerifier mIntentFilterVerifier;
777
778    // Set of pending broadcasts for aggregating enable/disable of components.
779    static class PendingPackageBroadcasts {
780        // for each user id, a map of <package name -> components within that package>
781        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
782
783        public PendingPackageBroadcasts() {
784            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
785        }
786
787        public ArrayList<String> get(int userId, String packageName) {
788            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
789            return packages.get(packageName);
790        }
791
792        public void put(int userId, String packageName, ArrayList<String> components) {
793            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
794            packages.put(packageName, components);
795        }
796
797        public void remove(int userId, String packageName) {
798            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
799            if (packages != null) {
800                packages.remove(packageName);
801            }
802        }
803
804        public void remove(int userId) {
805            mUidMap.remove(userId);
806        }
807
808        public int userIdCount() {
809            return mUidMap.size();
810        }
811
812        public int userIdAt(int n) {
813            return mUidMap.keyAt(n);
814        }
815
816        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
817            return mUidMap.get(userId);
818        }
819
820        public int size() {
821            // total number of pending broadcast entries across all userIds
822            int num = 0;
823            for (int i = 0; i< mUidMap.size(); i++) {
824                num += mUidMap.valueAt(i).size();
825            }
826            return num;
827        }
828
829        public void clear() {
830            mUidMap.clear();
831        }
832
833        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
834            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
835            if (map == null) {
836                map = new ArrayMap<String, ArrayList<String>>();
837                mUidMap.put(userId, map);
838            }
839            return map;
840        }
841    }
842    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
843
844    // Service Connection to remote media container service to copy
845    // package uri's from external media onto secure containers
846    // or internal storage.
847    private IMediaContainerService mContainerService = null;
848
849    static final int SEND_PENDING_BROADCAST = 1;
850    static final int MCS_BOUND = 3;
851    static final int END_COPY = 4;
852    static final int INIT_COPY = 5;
853    static final int MCS_UNBIND = 6;
854    static final int START_CLEANING_PACKAGE = 7;
855    static final int FIND_INSTALL_LOC = 8;
856    static final int POST_INSTALL = 9;
857    static final int MCS_RECONNECT = 10;
858    static final int MCS_GIVE_UP = 11;
859    static final int UPDATED_MEDIA_STATUS = 12;
860    static final int WRITE_SETTINGS = 13;
861    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
862    static final int PACKAGE_VERIFIED = 15;
863    static final int CHECK_PENDING_VERIFICATION = 16;
864    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
865    static final int INTENT_FILTER_VERIFIED = 18;
866
867    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
868
869    // Delay time in millisecs
870    static final int BROADCAST_DELAY = 10 * 1000;
871
872    static UserManagerService sUserManager;
873
874    // Stores a list of users whose package restrictions file needs to be updated
875    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
876
877    final private DefaultContainerConnection mDefContainerConn =
878            new DefaultContainerConnection();
879    class DefaultContainerConnection implements ServiceConnection {
880        public void onServiceConnected(ComponentName name, IBinder service) {
881            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
882            IMediaContainerService imcs =
883                IMediaContainerService.Stub.asInterface(service);
884            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
885        }
886
887        public void onServiceDisconnected(ComponentName name) {
888            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
889        }
890    }
891
892    // Recordkeeping of restore-after-install operations that are currently in flight
893    // between the Package Manager and the Backup Manager
894    class PostInstallData {
895        public InstallArgs args;
896        public PackageInstalledInfo res;
897
898        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
899            args = _a;
900            res = _r;
901        }
902    }
903
904    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
905    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
906
907    // XML tags for backup/restore of various bits of state
908    private static final String TAG_PREFERRED_BACKUP = "pa";
909    private static final String TAG_DEFAULT_APPS = "da";
910    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
911
912    private final String mRequiredVerifierPackage;
913
914    private final PackageUsage mPackageUsage = new PackageUsage();
915
916    private class PackageUsage {
917        private static final int WRITE_INTERVAL
918            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
919
920        private final Object mFileLock = new Object();
921        private final AtomicLong mLastWritten = new AtomicLong(0);
922        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
923
924        private boolean mIsHistoricalPackageUsageAvailable = true;
925
926        boolean isHistoricalPackageUsageAvailable() {
927            return mIsHistoricalPackageUsageAvailable;
928        }
929
930        void write(boolean force) {
931            if (force) {
932                writeInternal();
933                return;
934            }
935            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
936                && !DEBUG_DEXOPT) {
937                return;
938            }
939            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
940                new Thread("PackageUsage_DiskWriter") {
941                    @Override
942                    public void run() {
943                        try {
944                            writeInternal();
945                        } finally {
946                            mBackgroundWriteRunning.set(false);
947                        }
948                    }
949                }.start();
950            }
951        }
952
953        private void writeInternal() {
954            synchronized (mPackages) {
955                synchronized (mFileLock) {
956                    AtomicFile file = getFile();
957                    FileOutputStream f = null;
958                    try {
959                        f = file.startWrite();
960                        BufferedOutputStream out = new BufferedOutputStream(f);
961                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
962                        StringBuilder sb = new StringBuilder();
963                        for (PackageParser.Package pkg : mPackages.values()) {
964                            if (pkg.mLastPackageUsageTimeInMills == 0) {
965                                continue;
966                            }
967                            sb.setLength(0);
968                            sb.append(pkg.packageName);
969                            sb.append(' ');
970                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
971                            sb.append('\n');
972                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
973                        }
974                        out.flush();
975                        file.finishWrite(f);
976                    } catch (IOException e) {
977                        if (f != null) {
978                            file.failWrite(f);
979                        }
980                        Log.e(TAG, "Failed to write package usage times", e);
981                    }
982                }
983            }
984            mLastWritten.set(SystemClock.elapsedRealtime());
985        }
986
987        void readLP() {
988            synchronized (mFileLock) {
989                AtomicFile file = getFile();
990                BufferedInputStream in = null;
991                try {
992                    in = new BufferedInputStream(file.openRead());
993                    StringBuffer sb = new StringBuffer();
994                    while (true) {
995                        String packageName = readToken(in, sb, ' ');
996                        if (packageName == null) {
997                            break;
998                        }
999                        String timeInMillisString = readToken(in, sb, '\n');
1000                        if (timeInMillisString == null) {
1001                            throw new IOException("Failed to find last usage time for package "
1002                                                  + packageName);
1003                        }
1004                        PackageParser.Package pkg = mPackages.get(packageName);
1005                        if (pkg == null) {
1006                            continue;
1007                        }
1008                        long timeInMillis;
1009                        try {
1010                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1011                        } catch (NumberFormatException e) {
1012                            throw new IOException("Failed to parse " + timeInMillisString
1013                                                  + " as a long.", e);
1014                        }
1015                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1016                    }
1017                } catch (FileNotFoundException expected) {
1018                    mIsHistoricalPackageUsageAvailable = false;
1019                } catch (IOException e) {
1020                    Log.w(TAG, "Failed to read package usage times", e);
1021                } finally {
1022                    IoUtils.closeQuietly(in);
1023                }
1024            }
1025            mLastWritten.set(SystemClock.elapsedRealtime());
1026        }
1027
1028        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1029                throws IOException {
1030            sb.setLength(0);
1031            while (true) {
1032                int ch = in.read();
1033                if (ch == -1) {
1034                    if (sb.length() == 0) {
1035                        return null;
1036                    }
1037                    throw new IOException("Unexpected EOF");
1038                }
1039                if (ch == endOfToken) {
1040                    return sb.toString();
1041                }
1042                sb.append((char)ch);
1043            }
1044        }
1045
1046        private AtomicFile getFile() {
1047            File dataDir = Environment.getDataDirectory();
1048            File systemDir = new File(dataDir, "system");
1049            File fname = new File(systemDir, "package-usage.list");
1050            return new AtomicFile(fname);
1051        }
1052    }
1053
1054    class PackageHandler extends Handler {
1055        private boolean mBound = false;
1056        final ArrayList<HandlerParams> mPendingInstalls =
1057            new ArrayList<HandlerParams>();
1058
1059        private boolean connectToService() {
1060            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1061                    " DefaultContainerService");
1062            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1063            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1064            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1065                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1066                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1067                mBound = true;
1068                return true;
1069            }
1070            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1071            return false;
1072        }
1073
1074        private void disconnectService() {
1075            mContainerService = null;
1076            mBound = false;
1077            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1078            mContext.unbindService(mDefContainerConn);
1079            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1080        }
1081
1082        PackageHandler(Looper looper) {
1083            super(looper);
1084        }
1085
1086        public void handleMessage(Message msg) {
1087            try {
1088                doHandleMessage(msg);
1089            } finally {
1090                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1091            }
1092        }
1093
1094        void doHandleMessage(Message msg) {
1095            switch (msg.what) {
1096                case INIT_COPY: {
1097                    HandlerParams params = (HandlerParams) msg.obj;
1098                    int idx = mPendingInstalls.size();
1099                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1100                    // If a bind was already initiated we dont really
1101                    // need to do anything. The pending install
1102                    // will be processed later on.
1103                    if (!mBound) {
1104                        // If this is the only one pending we might
1105                        // have to bind to the service again.
1106                        if (!connectToService()) {
1107                            Slog.e(TAG, "Failed to bind to media container service");
1108                            params.serviceError();
1109                            return;
1110                        } else {
1111                            // Once we bind to the service, the first
1112                            // pending request will be processed.
1113                            mPendingInstalls.add(idx, params);
1114                        }
1115                    } else {
1116                        mPendingInstalls.add(idx, params);
1117                        // Already bound to the service. Just make
1118                        // sure we trigger off processing the first request.
1119                        if (idx == 0) {
1120                            mHandler.sendEmptyMessage(MCS_BOUND);
1121                        }
1122                    }
1123                    break;
1124                }
1125                case MCS_BOUND: {
1126                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1127                    if (msg.obj != null) {
1128                        mContainerService = (IMediaContainerService) msg.obj;
1129                    }
1130                    if (mContainerService == null) {
1131                        if (!mBound) {
1132                            // Something seriously wrong since we are not bound and we are not
1133                            // waiting for connection. Bail out.
1134                            Slog.e(TAG, "Cannot bind to media container service");
1135                            for (HandlerParams params : mPendingInstalls) {
1136                                // Indicate service bind error
1137                                params.serviceError();
1138                            }
1139                            mPendingInstalls.clear();
1140                        } else {
1141                            Slog.w(TAG, "Waiting to connect to media container service");
1142                        }
1143                    } else if (mPendingInstalls.size() > 0) {
1144                        HandlerParams params = mPendingInstalls.get(0);
1145                        if (params != null) {
1146                            if (params.startCopy()) {
1147                                // We are done...  look for more work or to
1148                                // go idle.
1149                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1150                                        "Checking for more work or unbind...");
1151                                // Delete pending install
1152                                if (mPendingInstalls.size() > 0) {
1153                                    mPendingInstalls.remove(0);
1154                                }
1155                                if (mPendingInstalls.size() == 0) {
1156                                    if (mBound) {
1157                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1158                                                "Posting delayed MCS_UNBIND");
1159                                        removeMessages(MCS_UNBIND);
1160                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1161                                        // Unbind after a little delay, to avoid
1162                                        // continual thrashing.
1163                                        sendMessageDelayed(ubmsg, 10000);
1164                                    }
1165                                } else {
1166                                    // There are more pending requests in queue.
1167                                    // Just post MCS_BOUND message to trigger processing
1168                                    // of next pending install.
1169                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1170                                            "Posting MCS_BOUND for next work");
1171                                    mHandler.sendEmptyMessage(MCS_BOUND);
1172                                }
1173                            }
1174                        }
1175                    } else {
1176                        // Should never happen ideally.
1177                        Slog.w(TAG, "Empty queue");
1178                    }
1179                    break;
1180                }
1181                case MCS_RECONNECT: {
1182                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1183                    if (mPendingInstalls.size() > 0) {
1184                        if (mBound) {
1185                            disconnectService();
1186                        }
1187                        if (!connectToService()) {
1188                            Slog.e(TAG, "Failed to bind to media container service");
1189                            for (HandlerParams params : mPendingInstalls) {
1190                                // Indicate service bind error
1191                                params.serviceError();
1192                            }
1193                            mPendingInstalls.clear();
1194                        }
1195                    }
1196                    break;
1197                }
1198                case MCS_UNBIND: {
1199                    // If there is no actual work left, then time to unbind.
1200                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1201
1202                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1203                        if (mBound) {
1204                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1205
1206                            disconnectService();
1207                        }
1208                    } else if (mPendingInstalls.size() > 0) {
1209                        // There are more pending requests in queue.
1210                        // Just post MCS_BOUND message to trigger processing
1211                        // of next pending install.
1212                        mHandler.sendEmptyMessage(MCS_BOUND);
1213                    }
1214
1215                    break;
1216                }
1217                case MCS_GIVE_UP: {
1218                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1219                    mPendingInstalls.remove(0);
1220                    break;
1221                }
1222                case SEND_PENDING_BROADCAST: {
1223                    String packages[];
1224                    ArrayList<String> components[];
1225                    int size = 0;
1226                    int uids[];
1227                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1228                    synchronized (mPackages) {
1229                        if (mPendingBroadcasts == null) {
1230                            return;
1231                        }
1232                        size = mPendingBroadcasts.size();
1233                        if (size <= 0) {
1234                            // Nothing to be done. Just return
1235                            return;
1236                        }
1237                        packages = new String[size];
1238                        components = new ArrayList[size];
1239                        uids = new int[size];
1240                        int i = 0;  // filling out the above arrays
1241
1242                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1243                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1244                            Iterator<Map.Entry<String, ArrayList<String>>> it
1245                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1246                                            .entrySet().iterator();
1247                            while (it.hasNext() && i < size) {
1248                                Map.Entry<String, ArrayList<String>> ent = it.next();
1249                                packages[i] = ent.getKey();
1250                                components[i] = ent.getValue();
1251                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1252                                uids[i] = (ps != null)
1253                                        ? UserHandle.getUid(packageUserId, ps.appId)
1254                                        : -1;
1255                                i++;
1256                            }
1257                        }
1258                        size = i;
1259                        mPendingBroadcasts.clear();
1260                    }
1261                    // Send broadcasts
1262                    for (int i = 0; i < size; i++) {
1263                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1264                    }
1265                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1266                    break;
1267                }
1268                case START_CLEANING_PACKAGE: {
1269                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1270                    final String packageName = (String)msg.obj;
1271                    final int userId = msg.arg1;
1272                    final boolean andCode = msg.arg2 != 0;
1273                    synchronized (mPackages) {
1274                        if (userId == UserHandle.USER_ALL) {
1275                            int[] users = sUserManager.getUserIds();
1276                            for (int user : users) {
1277                                mSettings.addPackageToCleanLPw(
1278                                        new PackageCleanItem(user, packageName, andCode));
1279                            }
1280                        } else {
1281                            mSettings.addPackageToCleanLPw(
1282                                    new PackageCleanItem(userId, packageName, andCode));
1283                        }
1284                    }
1285                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1286                    startCleaningPackages();
1287                } break;
1288                case POST_INSTALL: {
1289                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1290                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1291                    mRunningInstalls.delete(msg.arg1);
1292                    boolean deleteOld = false;
1293
1294                    if (data != null) {
1295                        InstallArgs args = data.args;
1296                        PackageInstalledInfo res = data.res;
1297
1298                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1299                            res.removedInfo.sendBroadcast(false, true, false);
1300                            Bundle extras = new Bundle(1);
1301                            extras.putInt(Intent.EXTRA_UID, res.uid);
1302
1303                            // Now that we successfully installed the package, grant runtime
1304                            // permissions if requested before broadcasting the install.
1305                            if ((args.installFlags
1306                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1307                                grantRequestedRuntimePermissions(res.pkg,
1308                                        args.user.getIdentifier());
1309                            }
1310
1311                            // Determine the set of users who are adding this
1312                            // package for the first time vs. those who are seeing
1313                            // an update.
1314                            int[] firstUsers;
1315                            int[] updateUsers = new int[0];
1316                            if (res.origUsers == null || res.origUsers.length == 0) {
1317                                firstUsers = res.newUsers;
1318                            } else {
1319                                firstUsers = new int[0];
1320                                for (int i=0; i<res.newUsers.length; i++) {
1321                                    int user = res.newUsers[i];
1322                                    boolean isNew = true;
1323                                    for (int j=0; j<res.origUsers.length; j++) {
1324                                        if (res.origUsers[j] == user) {
1325                                            isNew = false;
1326                                            break;
1327                                        }
1328                                    }
1329                                    if (isNew) {
1330                                        int[] newFirst = new int[firstUsers.length+1];
1331                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1332                                                firstUsers.length);
1333                                        newFirst[firstUsers.length] = user;
1334                                        firstUsers = newFirst;
1335                                    } else {
1336                                        int[] newUpdate = new int[updateUsers.length+1];
1337                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1338                                                updateUsers.length);
1339                                        newUpdate[updateUsers.length] = user;
1340                                        updateUsers = newUpdate;
1341                                    }
1342                                }
1343                            }
1344                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1345                                    res.pkg.applicationInfo.packageName,
1346                                    extras, null, null, firstUsers);
1347                            final boolean update = res.removedInfo.removedPackage != null;
1348                            if (update) {
1349                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1350                            }
1351                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1352                                    res.pkg.applicationInfo.packageName,
1353                                    extras, null, null, updateUsers);
1354                            if (update) {
1355                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1356                                        res.pkg.applicationInfo.packageName,
1357                                        extras, null, null, updateUsers);
1358                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1359                                        null, null,
1360                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1361
1362                                // treat asec-hosted packages like removable media on upgrade
1363                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1364                                    if (DEBUG_INSTALL) {
1365                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1366                                                + " is ASEC-hosted -> AVAILABLE");
1367                                    }
1368                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1369                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1370                                    pkgList.add(res.pkg.applicationInfo.packageName);
1371                                    sendResourcesChangedBroadcast(true, true,
1372                                            pkgList,uidArray, null);
1373                                }
1374                            }
1375                            if (res.removedInfo.args != null) {
1376                                // Remove the replaced package's older resources safely now
1377                                deleteOld = true;
1378                            }
1379
1380                            // Log current value of "unknown sources" setting
1381                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1382                                getUnknownSourcesSettings());
1383                        }
1384                        // Force a gc to clear up things
1385                        Runtime.getRuntime().gc();
1386                        // We delete after a gc for applications  on sdcard.
1387                        if (deleteOld) {
1388                            synchronized (mInstallLock) {
1389                                res.removedInfo.args.doPostDeleteLI(true);
1390                            }
1391                        }
1392                        if (args.observer != null) {
1393                            try {
1394                                Bundle extras = extrasForInstallResult(res);
1395                                args.observer.onPackageInstalled(res.name, res.returnCode,
1396                                        res.returnMsg, extras);
1397                            } catch (RemoteException e) {
1398                                Slog.i(TAG, "Observer no longer exists.");
1399                            }
1400                        }
1401                    } else {
1402                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1403                    }
1404                } break;
1405                case UPDATED_MEDIA_STATUS: {
1406                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1407                    boolean reportStatus = msg.arg1 == 1;
1408                    boolean doGc = msg.arg2 == 1;
1409                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1410                    if (doGc) {
1411                        // Force a gc to clear up stale containers.
1412                        Runtime.getRuntime().gc();
1413                    }
1414                    if (msg.obj != null) {
1415                        @SuppressWarnings("unchecked")
1416                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1417                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1418                        // Unload containers
1419                        unloadAllContainers(args);
1420                    }
1421                    if (reportStatus) {
1422                        try {
1423                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1424                            PackageHelper.getMountService().finishMediaUpdate();
1425                        } catch (RemoteException e) {
1426                            Log.e(TAG, "MountService not running?");
1427                        }
1428                    }
1429                } break;
1430                case WRITE_SETTINGS: {
1431                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1432                    synchronized (mPackages) {
1433                        removeMessages(WRITE_SETTINGS);
1434                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1435                        mSettings.writeLPr();
1436                        mDirtyUsers.clear();
1437                    }
1438                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1439                } break;
1440                case WRITE_PACKAGE_RESTRICTIONS: {
1441                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1442                    synchronized (mPackages) {
1443                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1444                        for (int userId : mDirtyUsers) {
1445                            mSettings.writePackageRestrictionsLPr(userId);
1446                        }
1447                        mDirtyUsers.clear();
1448                    }
1449                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1450                } break;
1451                case CHECK_PENDING_VERIFICATION: {
1452                    final int verificationId = msg.arg1;
1453                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1454
1455                    if ((state != null) && !state.timeoutExtended()) {
1456                        final InstallArgs args = state.getInstallArgs();
1457                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1458
1459                        Slog.i(TAG, "Verification timed out for " + originUri);
1460                        mPendingVerification.remove(verificationId);
1461
1462                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1463
1464                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1465                            Slog.i(TAG, "Continuing with installation of " + originUri);
1466                            state.setVerifierResponse(Binder.getCallingUid(),
1467                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1468                            broadcastPackageVerified(verificationId, originUri,
1469                                    PackageManager.VERIFICATION_ALLOW,
1470                                    state.getInstallArgs().getUser());
1471                            try {
1472                                ret = args.copyApk(mContainerService, true);
1473                            } catch (RemoteException e) {
1474                                Slog.e(TAG, "Could not contact the ContainerService");
1475                            }
1476                        } else {
1477                            broadcastPackageVerified(verificationId, originUri,
1478                                    PackageManager.VERIFICATION_REJECT,
1479                                    state.getInstallArgs().getUser());
1480                        }
1481
1482                        processPendingInstall(args, ret);
1483                        mHandler.sendEmptyMessage(MCS_UNBIND);
1484                    }
1485                    break;
1486                }
1487                case PACKAGE_VERIFIED: {
1488                    final int verificationId = msg.arg1;
1489
1490                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1491                    if (state == null) {
1492                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1493                        break;
1494                    }
1495
1496                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1497
1498                    state.setVerifierResponse(response.callerUid, response.code);
1499
1500                    if (state.isVerificationComplete()) {
1501                        mPendingVerification.remove(verificationId);
1502
1503                        final InstallArgs args = state.getInstallArgs();
1504                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1505
1506                        int ret;
1507                        if (state.isInstallAllowed()) {
1508                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1509                            broadcastPackageVerified(verificationId, originUri,
1510                                    response.code, state.getInstallArgs().getUser());
1511                            try {
1512                                ret = args.copyApk(mContainerService, true);
1513                            } catch (RemoteException e) {
1514                                Slog.e(TAG, "Could not contact the ContainerService");
1515                            }
1516                        } else {
1517                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1518                        }
1519
1520                        processPendingInstall(args, ret);
1521
1522                        mHandler.sendEmptyMessage(MCS_UNBIND);
1523                    }
1524
1525                    break;
1526                }
1527                case START_INTENT_FILTER_VERIFICATIONS: {
1528                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1529                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1530                            params.replacing, params.pkg);
1531                    break;
1532                }
1533                case INTENT_FILTER_VERIFIED: {
1534                    final int verificationId = msg.arg1;
1535
1536                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1537                            verificationId);
1538                    if (state == null) {
1539                        Slog.w(TAG, "Invalid IntentFilter verification token "
1540                                + verificationId + " received");
1541                        break;
1542                    }
1543
1544                    final int userId = state.getUserId();
1545
1546                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1547                            "Processing IntentFilter verification with token:"
1548                            + verificationId + " and userId:" + userId);
1549
1550                    final IntentFilterVerificationResponse response =
1551                            (IntentFilterVerificationResponse) msg.obj;
1552
1553                    state.setVerifierResponse(response.callerUid, response.code);
1554
1555                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1556                            "IntentFilter verification with token:" + verificationId
1557                            + " and userId:" + userId
1558                            + " is settings verifier response with response code:"
1559                            + response.code);
1560
1561                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1562                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1563                                + response.getFailedDomainsString());
1564                    }
1565
1566                    if (state.isVerificationComplete()) {
1567                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1568                    } else {
1569                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1570                                "IntentFilter verification with token:" + verificationId
1571                                + " was not said to be complete");
1572                    }
1573
1574                    break;
1575                }
1576            }
1577        }
1578    }
1579
1580    private StorageEventListener mStorageListener = new StorageEventListener() {
1581        @Override
1582        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1583            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1584                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1585                    // TODO: ensure that private directories exist for all active users
1586                    // TODO: remove user data whose serial number doesn't match
1587                    loadPrivatePackages(vol);
1588                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1589                    unloadPrivatePackages(vol);
1590                }
1591            }
1592
1593            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1594                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1595                    updateExternalMediaStatus(true, false);
1596                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1597                    updateExternalMediaStatus(false, false);
1598                }
1599            }
1600        }
1601
1602        @Override
1603        public void onVolumeForgotten(String fsUuid) {
1604            // TODO: remove all packages hosted on this uuid
1605        }
1606    };
1607
1608    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1609        if (userId >= UserHandle.USER_OWNER) {
1610            grantRequestedRuntimePermissionsForUser(pkg, userId);
1611        } else if (userId == UserHandle.USER_ALL) {
1612            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1613                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1614            }
1615        }
1616
1617        // We could have touched GID membership, so flush out packages.list
1618        synchronized (mPackages) {
1619            mSettings.writePackageListLPr();
1620        }
1621    }
1622
1623    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1624        SettingBase sb = (SettingBase) pkg.mExtras;
1625        if (sb == null) {
1626            return;
1627        }
1628
1629        PermissionsState permissionsState = sb.getPermissionsState();
1630
1631        for (String permission : pkg.requestedPermissions) {
1632            BasePermission bp = mSettings.mPermissions.get(permission);
1633            if (bp != null && bp.isRuntime()) {
1634                permissionsState.grantRuntimePermission(bp, userId);
1635            }
1636        }
1637    }
1638
1639    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1640        Bundle extras = null;
1641        switch (res.returnCode) {
1642            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1643                extras = new Bundle();
1644                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1645                        res.origPermission);
1646                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1647                        res.origPackage);
1648                break;
1649            }
1650            case PackageManager.INSTALL_SUCCEEDED: {
1651                extras = new Bundle();
1652                extras.putBoolean(Intent.EXTRA_REPLACING,
1653                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1654                break;
1655            }
1656        }
1657        return extras;
1658    }
1659
1660    void scheduleWriteSettingsLocked() {
1661        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1662            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1663        }
1664    }
1665
1666    void scheduleWritePackageRestrictionsLocked(int userId) {
1667        if (!sUserManager.exists(userId)) return;
1668        mDirtyUsers.add(userId);
1669        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1670            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1671        }
1672    }
1673
1674    public static PackageManagerService main(Context context, Installer installer,
1675            boolean factoryTest, boolean onlyCore) {
1676        PackageManagerService m = new PackageManagerService(context, installer,
1677                factoryTest, onlyCore);
1678        ServiceManager.addService("package", m);
1679        return m;
1680    }
1681
1682    static String[] splitString(String str, char sep) {
1683        int count = 1;
1684        int i = 0;
1685        while ((i=str.indexOf(sep, i)) >= 0) {
1686            count++;
1687            i++;
1688        }
1689
1690        String[] res = new String[count];
1691        i=0;
1692        count = 0;
1693        int lastI=0;
1694        while ((i=str.indexOf(sep, i)) >= 0) {
1695            res[count] = str.substring(lastI, i);
1696            count++;
1697            i++;
1698            lastI = i;
1699        }
1700        res[count] = str.substring(lastI, str.length());
1701        return res;
1702    }
1703
1704    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1705        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1706                Context.DISPLAY_SERVICE);
1707        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1708    }
1709
1710    public PackageManagerService(Context context, Installer installer,
1711            boolean factoryTest, boolean onlyCore) {
1712        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1713                SystemClock.uptimeMillis());
1714
1715        if (mSdkVersion <= 0) {
1716            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1717        }
1718
1719        mContext = context;
1720        mFactoryTest = factoryTest;
1721        mOnlyCore = onlyCore;
1722        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1723        mMetrics = new DisplayMetrics();
1724        mSettings = new Settings(mPackages);
1725        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1726                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1727        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1728                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1729        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1730                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1731        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1732                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1733        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1734                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1735        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1736                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1737
1738        // TODO: add a property to control this?
1739        long dexOptLRUThresholdInMinutes;
1740        if (mLazyDexOpt) {
1741            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1742        } else {
1743            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1744        }
1745        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1746
1747        String separateProcesses = SystemProperties.get("debug.separate_processes");
1748        if (separateProcesses != null && separateProcesses.length() > 0) {
1749            if ("*".equals(separateProcesses)) {
1750                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1751                mSeparateProcesses = null;
1752                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1753            } else {
1754                mDefParseFlags = 0;
1755                mSeparateProcesses = separateProcesses.split(",");
1756                Slog.w(TAG, "Running with debug.separate_processes: "
1757                        + separateProcesses);
1758            }
1759        } else {
1760            mDefParseFlags = 0;
1761            mSeparateProcesses = null;
1762        }
1763
1764        mInstaller = installer;
1765        mPackageDexOptimizer = new PackageDexOptimizer(this);
1766        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1767
1768        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1769                FgThread.get().getLooper());
1770
1771        getDefaultDisplayMetrics(context, mMetrics);
1772
1773        SystemConfig systemConfig = SystemConfig.getInstance();
1774        mGlobalGids = systemConfig.getGlobalGids();
1775        mSystemPermissions = systemConfig.getSystemPermissions();
1776        mAvailableFeatures = systemConfig.getAvailableFeatures();
1777
1778        synchronized (mInstallLock) {
1779        // writer
1780        synchronized (mPackages) {
1781            mHandlerThread = new ServiceThread(TAG,
1782                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1783            mHandlerThread.start();
1784            mHandler = new PackageHandler(mHandlerThread.getLooper());
1785            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1786
1787            File dataDir = Environment.getDataDirectory();
1788            mAppDataDir = new File(dataDir, "data");
1789            mAppInstallDir = new File(dataDir, "app");
1790            mAppLib32InstallDir = new File(dataDir, "app-lib");
1791            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1792            mUserAppDataDir = new File(dataDir, "user");
1793            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1794
1795            sUserManager = new UserManagerService(context, this,
1796                    mInstallLock, mPackages);
1797
1798            // Propagate permission configuration in to package manager.
1799            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1800                    = systemConfig.getPermissions();
1801            for (int i=0; i<permConfig.size(); i++) {
1802                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1803                BasePermission bp = mSettings.mPermissions.get(perm.name);
1804                if (bp == null) {
1805                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1806                    mSettings.mPermissions.put(perm.name, bp);
1807                }
1808                if (perm.gids != null) {
1809                    bp.setGids(perm.gids, perm.perUser);
1810                }
1811            }
1812
1813            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1814            for (int i=0; i<libConfig.size(); i++) {
1815                mSharedLibraries.put(libConfig.keyAt(i),
1816                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1817            }
1818
1819            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1820
1821            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1822                    mSdkVersion, mOnlyCore);
1823
1824            String customResolverActivity = Resources.getSystem().getString(
1825                    R.string.config_customResolverActivity);
1826            if (TextUtils.isEmpty(customResolverActivity)) {
1827                customResolverActivity = null;
1828            } else {
1829                mCustomResolverComponentName = ComponentName.unflattenFromString(
1830                        customResolverActivity);
1831            }
1832
1833            long startTime = SystemClock.uptimeMillis();
1834
1835            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1836                    startTime);
1837
1838            // Set flag to monitor and not change apk file paths when
1839            // scanning install directories.
1840            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1841
1842            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1843
1844            /**
1845             * Add everything in the in the boot class path to the
1846             * list of process files because dexopt will have been run
1847             * if necessary during zygote startup.
1848             */
1849            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1850            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1851
1852            if (bootClassPath != null) {
1853                String[] bootClassPathElements = splitString(bootClassPath, ':');
1854                for (String element : bootClassPathElements) {
1855                    alreadyDexOpted.add(element);
1856                }
1857            } else {
1858                Slog.w(TAG, "No BOOTCLASSPATH found!");
1859            }
1860
1861            if (systemServerClassPath != null) {
1862                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1863                for (String element : systemServerClassPathElements) {
1864                    alreadyDexOpted.add(element);
1865                }
1866            } else {
1867                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1868            }
1869
1870            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1871            final String[] dexCodeInstructionSets =
1872                    getDexCodeInstructionSets(
1873                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1874
1875            /**
1876             * Ensure all external libraries have had dexopt run on them.
1877             */
1878            if (mSharedLibraries.size() > 0) {
1879                // NOTE: For now, we're compiling these system "shared libraries"
1880                // (and framework jars) into all available architectures. It's possible
1881                // to compile them only when we come across an app that uses them (there's
1882                // already logic for that in scanPackageLI) but that adds some complexity.
1883                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1884                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1885                        final String lib = libEntry.path;
1886                        if (lib == null) {
1887                            continue;
1888                        }
1889
1890                        try {
1891                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1892                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1893                                alreadyDexOpted.add(lib);
1894                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1895                            }
1896                        } catch (FileNotFoundException e) {
1897                            Slog.w(TAG, "Library not found: " + lib);
1898                        } catch (IOException e) {
1899                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1900                                    + e.getMessage());
1901                        }
1902                    }
1903                }
1904            }
1905
1906            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1907
1908            // Gross hack for now: we know this file doesn't contain any
1909            // code, so don't dexopt it to avoid the resulting log spew.
1910            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1911
1912            // Gross hack for now: we know this file is only part of
1913            // the boot class path for art, so don't dexopt it to
1914            // avoid the resulting log spew.
1915            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1916
1917            /**
1918             * There are a number of commands implemented in Java, which
1919             * we currently need to do the dexopt on so that they can be
1920             * run from a non-root shell.
1921             */
1922            String[] frameworkFiles = frameworkDir.list();
1923            if (frameworkFiles != null) {
1924                // TODO: We could compile these only for the most preferred ABI. We should
1925                // first double check that the dex files for these commands are not referenced
1926                // by other system apps.
1927                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1928                    for (int i=0; i<frameworkFiles.length; i++) {
1929                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1930                        String path = libPath.getPath();
1931                        // Skip the file if we already did it.
1932                        if (alreadyDexOpted.contains(path)) {
1933                            continue;
1934                        }
1935                        // Skip the file if it is not a type we want to dexopt.
1936                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1937                            continue;
1938                        }
1939                        try {
1940                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1941                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1942                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1943                            }
1944                        } catch (FileNotFoundException e) {
1945                            Slog.w(TAG, "Jar not found: " + path);
1946                        } catch (IOException e) {
1947                            Slog.w(TAG, "Exception reading jar: " + path, e);
1948                        }
1949                    }
1950                }
1951            }
1952
1953            // Collect vendor overlay packages.
1954            // (Do this before scanning any apps.)
1955            // For security and version matching reason, only consider
1956            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1957            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1958            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1959                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1960
1961            // Find base frameworks (resource packages without code).
1962            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1963                    | PackageParser.PARSE_IS_SYSTEM_DIR
1964                    | PackageParser.PARSE_IS_PRIVILEGED,
1965                    scanFlags | SCAN_NO_DEX, 0);
1966
1967            // Collected privileged system packages.
1968            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1969            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1970                    | PackageParser.PARSE_IS_SYSTEM_DIR
1971                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1972
1973            // Collect ordinary system packages.
1974            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1975            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1976                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1977
1978            // Collect all vendor packages.
1979            File vendorAppDir = new File("/vendor/app");
1980            try {
1981                vendorAppDir = vendorAppDir.getCanonicalFile();
1982            } catch (IOException e) {
1983                // failed to look up canonical path, continue with original one
1984            }
1985            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1986                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1987
1988            // Collect all OEM packages.
1989            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1990            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1991                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1992
1993            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1994            mInstaller.moveFiles();
1995
1996            // Prune any system packages that no longer exist.
1997            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1998            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1999            if (!mOnlyCore) {
2000                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2001                while (psit.hasNext()) {
2002                    PackageSetting ps = psit.next();
2003
2004                    /*
2005                     * If this is not a system app, it can't be a
2006                     * disable system app.
2007                     */
2008                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2009                        continue;
2010                    }
2011
2012                    /*
2013                     * If the package is scanned, it's not erased.
2014                     */
2015                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2016                    if (scannedPkg != null) {
2017                        /*
2018                         * If the system app is both scanned and in the
2019                         * disabled packages list, then it must have been
2020                         * added via OTA. Remove it from the currently
2021                         * scanned package so the previously user-installed
2022                         * application can be scanned.
2023                         */
2024                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2025                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2026                                    + ps.name + "; removing system app.  Last known codePath="
2027                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2028                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2029                                    + scannedPkg.mVersionCode);
2030                            removePackageLI(ps, true);
2031                            expectingBetter.put(ps.name, ps.codePath);
2032                        }
2033
2034                        continue;
2035                    }
2036
2037                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2038                        psit.remove();
2039                        logCriticalInfo(Log.WARN, "System package " + ps.name
2040                                + " no longer exists; wiping its data");
2041                        removeDataDirsLI(null, ps.name);
2042                    } else {
2043                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2044                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2045                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2046                        }
2047                    }
2048                }
2049            }
2050
2051            //look for any incomplete package installations
2052            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2053            //clean up list
2054            for(int i = 0; i < deletePkgsList.size(); i++) {
2055                //clean up here
2056                cleanupInstallFailedPackage(deletePkgsList.get(i));
2057            }
2058            //delete tmp files
2059            deleteTempPackageFiles();
2060
2061            // Remove any shared userIDs that have no associated packages
2062            mSettings.pruneSharedUsersLPw();
2063
2064            if (!mOnlyCore) {
2065                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2066                        SystemClock.uptimeMillis());
2067                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2068
2069                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2070                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2071
2072                /**
2073                 * Remove disable package settings for any updated system
2074                 * apps that were removed via an OTA. If they're not a
2075                 * previously-updated app, remove them completely.
2076                 * Otherwise, just revoke their system-level permissions.
2077                 */
2078                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2079                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2080                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2081
2082                    String msg;
2083                    if (deletedPkg == null) {
2084                        msg = "Updated system package " + deletedAppName
2085                                + " no longer exists; wiping its data";
2086                        removeDataDirsLI(null, deletedAppName);
2087                    } else {
2088                        msg = "Updated system app + " + deletedAppName
2089                                + " no longer present; removing system privileges for "
2090                                + deletedAppName;
2091
2092                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2093
2094                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2095                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2096                    }
2097                    logCriticalInfo(Log.WARN, msg);
2098                }
2099
2100                /**
2101                 * Make sure all system apps that we expected to appear on
2102                 * the userdata partition actually showed up. If they never
2103                 * appeared, crawl back and revive the system version.
2104                 */
2105                for (int i = 0; i < expectingBetter.size(); i++) {
2106                    final String packageName = expectingBetter.keyAt(i);
2107                    if (!mPackages.containsKey(packageName)) {
2108                        final File scanFile = expectingBetter.valueAt(i);
2109
2110                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2111                                + " but never showed up; reverting to system");
2112
2113                        final int reparseFlags;
2114                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2115                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2116                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2117                                    | PackageParser.PARSE_IS_PRIVILEGED;
2118                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2119                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2120                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2121                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2122                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2123                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2124                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2125                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2126                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2127                        } else {
2128                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2129                            continue;
2130                        }
2131
2132                        mSettings.enableSystemPackageLPw(packageName);
2133
2134                        try {
2135                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2136                        } catch (PackageManagerException e) {
2137                            Slog.e(TAG, "Failed to parse original system package: "
2138                                    + e.getMessage());
2139                        }
2140                    }
2141                }
2142            }
2143
2144            // Now that we know all of the shared libraries, update all clients to have
2145            // the correct library paths.
2146            updateAllSharedLibrariesLPw();
2147
2148            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2149                // NOTE: We ignore potential failures here during a system scan (like
2150                // the rest of the commands above) because there's precious little we
2151                // can do about it. A settings error is reported, though.
2152                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2153                        false /* force dexopt */, false /* defer dexopt */);
2154            }
2155
2156            // Now that we know all the packages we are keeping,
2157            // read and update their last usage times.
2158            mPackageUsage.readLP();
2159
2160            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2161                    SystemClock.uptimeMillis());
2162            Slog.i(TAG, "Time to scan packages: "
2163                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2164                    + " seconds");
2165
2166            // If the platform SDK has changed since the last time we booted,
2167            // we need to re-grant app permission to catch any new ones that
2168            // appear.  This is really a hack, and means that apps can in some
2169            // cases get permissions that the user didn't initially explicitly
2170            // allow...  it would be nice to have some better way to handle
2171            // this situation.
2172            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2173                    != mSdkVersion;
2174            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2175                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2176                    + "; regranting permissions for internal storage");
2177            mSettings.mInternalSdkPlatform = mSdkVersion;
2178
2179            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2180                    | (regrantPermissions
2181                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2182                            : 0));
2183
2184            // If this is the first boot, and it is a normal boot, then
2185            // we need to initialize the default preferred apps.
2186            if (!mRestoredSettings && !onlyCore) {
2187                mSettings.readDefaultPreferredAppsLPw(this, 0);
2188            }
2189
2190            // If this is first boot after an OTA, and a normal boot, then
2191            // we need to clear code cache directories.
2192            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2193            if (mIsUpgrade && !onlyCore) {
2194                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2195                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2196                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2197                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2198                }
2199                mSettings.mFingerprint = Build.FINGERPRINT;
2200            }
2201
2202            primeDomainVerificationsLPw();
2203            checkDefaultBrowser();
2204
2205            // All the changes are done during package scanning.
2206            mSettings.updateInternalDatabaseVersion();
2207
2208            // can downgrade to reader
2209            mSettings.writeLPr();
2210
2211            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2212                    SystemClock.uptimeMillis());
2213
2214            mRequiredVerifierPackage = getRequiredVerifierLPr();
2215
2216            mInstallerService = new PackageInstallerService(context, this);
2217
2218            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2219            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2220                    mIntentFilterVerifierComponent);
2221
2222        } // synchronized (mPackages)
2223        } // synchronized (mInstallLock)
2224
2225        // Now after opening every single application zip, make sure they
2226        // are all flushed.  Not really needed, but keeps things nice and
2227        // tidy.
2228        Runtime.getRuntime().gc();
2229
2230        // Expose private service for system components to use.
2231        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2232    }
2233
2234    @Override
2235    public boolean isFirstBoot() {
2236        return !mRestoredSettings;
2237    }
2238
2239    @Override
2240    public boolean isOnlyCoreApps() {
2241        return mOnlyCore;
2242    }
2243
2244    @Override
2245    public boolean isUpgrade() {
2246        return mIsUpgrade;
2247    }
2248
2249    private String getRequiredVerifierLPr() {
2250        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2251        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2252                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2253
2254        String requiredVerifier = null;
2255
2256        final int N = receivers.size();
2257        for (int i = 0; i < N; i++) {
2258            final ResolveInfo info = receivers.get(i);
2259
2260            if (info.activityInfo == null) {
2261                continue;
2262            }
2263
2264            final String packageName = info.activityInfo.packageName;
2265
2266            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2267                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2268                continue;
2269            }
2270
2271            if (requiredVerifier != null) {
2272                throw new RuntimeException("There can be only one required verifier");
2273            }
2274
2275            requiredVerifier = packageName;
2276        }
2277
2278        return requiredVerifier;
2279    }
2280
2281    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2282        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2283        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2284                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2285
2286        ComponentName verifierComponentName = null;
2287
2288        int priority = -1000;
2289        final int N = receivers.size();
2290        for (int i = 0; i < N; i++) {
2291            final ResolveInfo info = receivers.get(i);
2292
2293            if (info.activityInfo == null) {
2294                continue;
2295            }
2296
2297            final String packageName = info.activityInfo.packageName;
2298
2299            final PackageSetting ps = mSettings.mPackages.get(packageName);
2300            if (ps == null) {
2301                continue;
2302            }
2303
2304            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2305                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2306                continue;
2307            }
2308
2309            // Select the IntentFilterVerifier with the highest priority
2310            if (priority < info.priority) {
2311                priority = info.priority;
2312                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2313                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2314                        + verifierComponentName + " with priority: " + info.priority);
2315            }
2316        }
2317
2318        return verifierComponentName;
2319    }
2320
2321    private void primeDomainVerificationsLPw() {
2322        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2323        boolean updated = false;
2324        ArraySet<String> allHostsSet = new ArraySet<>();
2325        for (PackageParser.Package pkg : mPackages.values()) {
2326            final String packageName = pkg.packageName;
2327            if (!hasDomainURLs(pkg)) {
2328                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2329                            "package with no domain URLs: " + packageName);
2330                continue;
2331            }
2332            if (!pkg.isSystemApp()) {
2333                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2334                        "No priming domain verifications for a non system package : " +
2335                                packageName);
2336                continue;
2337            }
2338            for (PackageParser.Activity a : pkg.activities) {
2339                for (ActivityIntentInfo filter : a.intents) {
2340                    if (hasValidDomains(filter)) {
2341                        allHostsSet.addAll(filter.getHostsList());
2342                    }
2343                }
2344            }
2345            if (allHostsSet.size() == 0) {
2346                allHostsSet.add("*");
2347            }
2348            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2349            IntentFilterVerificationInfo ivi =
2350                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2351            if (ivi != null) {
2352                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2353                        "Priming domain verifications for package: " + packageName +
2354                        " with hosts:" + ivi.getDomainsString());
2355                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2356                updated = true;
2357            }
2358            else {
2359                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2360                        "No priming domain verifications for package: " + packageName);
2361            }
2362            allHostsSet.clear();
2363        }
2364        if (updated) {
2365            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2366                    "Will need to write primed domain verifications");
2367        }
2368        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2369    }
2370
2371    private void checkDefaultBrowser() {
2372        final int myUserId = UserHandle.myUserId();
2373        final String packageName = getDefaultBrowserPackageName(myUserId);
2374        PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2375        if (info == null) {
2376            Slog.w(TAG, "Default browser no longer installed: " + packageName);
2377            setDefaultBrowserPackageName(null, myUserId);
2378        }
2379    }
2380
2381    @Override
2382    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2383            throws RemoteException {
2384        try {
2385            return super.onTransact(code, data, reply, flags);
2386        } catch (RuntimeException e) {
2387            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2388                Slog.wtf(TAG, "Package Manager Crash", e);
2389            }
2390            throw e;
2391        }
2392    }
2393
2394    void cleanupInstallFailedPackage(PackageSetting ps) {
2395        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2396
2397        removeDataDirsLI(ps.volumeUuid, ps.name);
2398        if (ps.codePath != null) {
2399            if (ps.codePath.isDirectory()) {
2400                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2401            } else {
2402                ps.codePath.delete();
2403            }
2404        }
2405        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2406            if (ps.resourcePath.isDirectory()) {
2407                FileUtils.deleteContents(ps.resourcePath);
2408            }
2409            ps.resourcePath.delete();
2410        }
2411        mSettings.removePackageLPw(ps.name);
2412    }
2413
2414    static int[] appendInts(int[] cur, int[] add) {
2415        if (add == null) return cur;
2416        if (cur == null) return add;
2417        final int N = add.length;
2418        for (int i=0; i<N; i++) {
2419            cur = appendInt(cur, add[i]);
2420        }
2421        return cur;
2422    }
2423
2424    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2425        if (!sUserManager.exists(userId)) return null;
2426        final PackageSetting ps = (PackageSetting) p.mExtras;
2427        if (ps == null) {
2428            return null;
2429        }
2430
2431        final PermissionsState permissionsState = ps.getPermissionsState();
2432
2433        final int[] gids = permissionsState.computeGids(userId);
2434        final Set<String> permissions = permissionsState.getPermissions(userId);
2435        final PackageUserState state = ps.readUserState(userId);
2436
2437        return PackageParser.generatePackageInfo(p, gids, flags,
2438                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2439    }
2440
2441    @Override
2442    public boolean isPackageFrozen(String packageName) {
2443        synchronized (mPackages) {
2444            final PackageSetting ps = mSettings.mPackages.get(packageName);
2445            if (ps != null) {
2446                return ps.frozen;
2447            }
2448        }
2449        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2450        return true;
2451    }
2452
2453    @Override
2454    public boolean isPackageAvailable(String packageName, int userId) {
2455        if (!sUserManager.exists(userId)) return false;
2456        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2457        synchronized (mPackages) {
2458            PackageParser.Package p = mPackages.get(packageName);
2459            if (p != null) {
2460                final PackageSetting ps = (PackageSetting) p.mExtras;
2461                if (ps != null) {
2462                    final PackageUserState state = ps.readUserState(userId);
2463                    if (state != null) {
2464                        return PackageParser.isAvailable(state);
2465                    }
2466                }
2467            }
2468        }
2469        return false;
2470    }
2471
2472    @Override
2473    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2474        if (!sUserManager.exists(userId)) return null;
2475        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2476        // reader
2477        synchronized (mPackages) {
2478            PackageParser.Package p = mPackages.get(packageName);
2479            if (DEBUG_PACKAGE_INFO)
2480                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2481            if (p != null) {
2482                return generatePackageInfo(p, flags, userId);
2483            }
2484            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2485                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2486            }
2487        }
2488        return null;
2489    }
2490
2491    @Override
2492    public String[] currentToCanonicalPackageNames(String[] names) {
2493        String[] out = new String[names.length];
2494        // reader
2495        synchronized (mPackages) {
2496            for (int i=names.length-1; i>=0; i--) {
2497                PackageSetting ps = mSettings.mPackages.get(names[i]);
2498                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2499            }
2500        }
2501        return out;
2502    }
2503
2504    @Override
2505    public String[] canonicalToCurrentPackageNames(String[] names) {
2506        String[] out = new String[names.length];
2507        // reader
2508        synchronized (mPackages) {
2509            for (int i=names.length-1; i>=0; i--) {
2510                String cur = mSettings.mRenamedPackages.get(names[i]);
2511                out[i] = cur != null ? cur : names[i];
2512            }
2513        }
2514        return out;
2515    }
2516
2517    @Override
2518    public int getPackageUid(String packageName, int userId) {
2519        if (!sUserManager.exists(userId)) return -1;
2520        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2521
2522        // reader
2523        synchronized (mPackages) {
2524            PackageParser.Package p = mPackages.get(packageName);
2525            if(p != null) {
2526                return UserHandle.getUid(userId, p.applicationInfo.uid);
2527            }
2528            PackageSetting ps = mSettings.mPackages.get(packageName);
2529            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2530                return -1;
2531            }
2532            p = ps.pkg;
2533            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2534        }
2535    }
2536
2537    @Override
2538    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2539        if (!sUserManager.exists(userId)) {
2540            return null;
2541        }
2542
2543        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2544                "getPackageGids");
2545
2546        // reader
2547        synchronized (mPackages) {
2548            PackageParser.Package p = mPackages.get(packageName);
2549            if (DEBUG_PACKAGE_INFO) {
2550                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2551            }
2552            if (p != null) {
2553                PackageSetting ps = (PackageSetting) p.mExtras;
2554                return ps.getPermissionsState().computeGids(userId);
2555            }
2556        }
2557
2558        return null;
2559    }
2560
2561    static PermissionInfo generatePermissionInfo(
2562            BasePermission bp, int flags) {
2563        if (bp.perm != null) {
2564            return PackageParser.generatePermissionInfo(bp.perm, flags);
2565        }
2566        PermissionInfo pi = new PermissionInfo();
2567        pi.name = bp.name;
2568        pi.packageName = bp.sourcePackage;
2569        pi.nonLocalizedLabel = bp.name;
2570        pi.protectionLevel = bp.protectionLevel;
2571        return pi;
2572    }
2573
2574    @Override
2575    public PermissionInfo getPermissionInfo(String name, int flags) {
2576        // reader
2577        synchronized (mPackages) {
2578            final BasePermission p = mSettings.mPermissions.get(name);
2579            if (p != null) {
2580                return generatePermissionInfo(p, flags);
2581            }
2582            return null;
2583        }
2584    }
2585
2586    @Override
2587    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2588        // reader
2589        synchronized (mPackages) {
2590            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2591            for (BasePermission p : mSettings.mPermissions.values()) {
2592                if (group == null) {
2593                    if (p.perm == null || p.perm.info.group == null) {
2594                        out.add(generatePermissionInfo(p, flags));
2595                    }
2596                } else {
2597                    if (p.perm != null && group.equals(p.perm.info.group)) {
2598                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2599                    }
2600                }
2601            }
2602
2603            if (out.size() > 0) {
2604                return out;
2605            }
2606            return mPermissionGroups.containsKey(group) ? out : null;
2607        }
2608    }
2609
2610    @Override
2611    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2612        // reader
2613        synchronized (mPackages) {
2614            return PackageParser.generatePermissionGroupInfo(
2615                    mPermissionGroups.get(name), flags);
2616        }
2617    }
2618
2619    @Override
2620    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2621        // reader
2622        synchronized (mPackages) {
2623            final int N = mPermissionGroups.size();
2624            ArrayList<PermissionGroupInfo> out
2625                    = new ArrayList<PermissionGroupInfo>(N);
2626            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2627                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2628            }
2629            return out;
2630        }
2631    }
2632
2633    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2634            int userId) {
2635        if (!sUserManager.exists(userId)) return null;
2636        PackageSetting ps = mSettings.mPackages.get(packageName);
2637        if (ps != null) {
2638            if (ps.pkg == null) {
2639                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2640                        flags, userId);
2641                if (pInfo != null) {
2642                    return pInfo.applicationInfo;
2643                }
2644                return null;
2645            }
2646            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2647                    ps.readUserState(userId), userId);
2648        }
2649        return null;
2650    }
2651
2652    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2653            int userId) {
2654        if (!sUserManager.exists(userId)) return null;
2655        PackageSetting ps = mSettings.mPackages.get(packageName);
2656        if (ps != null) {
2657            PackageParser.Package pkg = ps.pkg;
2658            if (pkg == null) {
2659                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2660                    return null;
2661                }
2662                // Only data remains, so we aren't worried about code paths
2663                pkg = new PackageParser.Package(packageName);
2664                pkg.applicationInfo.packageName = packageName;
2665                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2666                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2667                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2668                        packageName, userId).getAbsolutePath();
2669                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2670                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2671            }
2672            return generatePackageInfo(pkg, flags, userId);
2673        }
2674        return null;
2675    }
2676
2677    @Override
2678    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2679        if (!sUserManager.exists(userId)) return null;
2680        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2681        // writer
2682        synchronized (mPackages) {
2683            PackageParser.Package p = mPackages.get(packageName);
2684            if (DEBUG_PACKAGE_INFO) Log.v(
2685                    TAG, "getApplicationInfo " + packageName
2686                    + ": " + p);
2687            if (p != null) {
2688                PackageSetting ps = mSettings.mPackages.get(packageName);
2689                if (ps == null) return null;
2690                // Note: isEnabledLP() does not apply here - always return info
2691                return PackageParser.generateApplicationInfo(
2692                        p, flags, ps.readUserState(userId), userId);
2693            }
2694            if ("android".equals(packageName)||"system".equals(packageName)) {
2695                return mAndroidApplication;
2696            }
2697            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2698                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2699            }
2700        }
2701        return null;
2702    }
2703
2704    @Override
2705    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2706            final IPackageDataObserver observer) {
2707        mContext.enforceCallingOrSelfPermission(
2708                android.Manifest.permission.CLEAR_APP_CACHE, null);
2709        // Queue up an async operation since clearing cache may take a little while.
2710        mHandler.post(new Runnable() {
2711            public void run() {
2712                mHandler.removeCallbacks(this);
2713                int retCode = -1;
2714                synchronized (mInstallLock) {
2715                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2716                    if (retCode < 0) {
2717                        Slog.w(TAG, "Couldn't clear application caches");
2718                    }
2719                }
2720                if (observer != null) {
2721                    try {
2722                        observer.onRemoveCompleted(null, (retCode >= 0));
2723                    } catch (RemoteException e) {
2724                        Slog.w(TAG, "RemoveException when invoking call back");
2725                    }
2726                }
2727            }
2728        });
2729    }
2730
2731    @Override
2732    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2733            final IntentSender pi) {
2734        mContext.enforceCallingOrSelfPermission(
2735                android.Manifest.permission.CLEAR_APP_CACHE, null);
2736        // Queue up an async operation since clearing cache may take a little while.
2737        mHandler.post(new Runnable() {
2738            public void run() {
2739                mHandler.removeCallbacks(this);
2740                int retCode = -1;
2741                synchronized (mInstallLock) {
2742                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2743                    if (retCode < 0) {
2744                        Slog.w(TAG, "Couldn't clear application caches");
2745                    }
2746                }
2747                if(pi != null) {
2748                    try {
2749                        // Callback via pending intent
2750                        int code = (retCode >= 0) ? 1 : 0;
2751                        pi.sendIntent(null, code, null,
2752                                null, null);
2753                    } catch (SendIntentException e1) {
2754                        Slog.i(TAG, "Failed to send pending intent");
2755                    }
2756                }
2757            }
2758        });
2759    }
2760
2761    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2762        synchronized (mInstallLock) {
2763            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2764                throw new IOException("Failed to free enough space");
2765            }
2766        }
2767    }
2768
2769    @Override
2770    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2771        if (!sUserManager.exists(userId)) return null;
2772        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2773        synchronized (mPackages) {
2774            PackageParser.Activity a = mActivities.mActivities.get(component);
2775
2776            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2777            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2778                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2779                if (ps == null) return null;
2780                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2781                        userId);
2782            }
2783            if (mResolveComponentName.equals(component)) {
2784                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2785                        new PackageUserState(), userId);
2786            }
2787        }
2788        return null;
2789    }
2790
2791    @Override
2792    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2793            String resolvedType) {
2794        synchronized (mPackages) {
2795            PackageParser.Activity a = mActivities.mActivities.get(component);
2796            if (a == null) {
2797                return false;
2798            }
2799            for (int i=0; i<a.intents.size(); i++) {
2800                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2801                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2802                    return true;
2803                }
2804            }
2805            return false;
2806        }
2807    }
2808
2809    @Override
2810    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2811        if (!sUserManager.exists(userId)) return null;
2812        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2813        synchronized (mPackages) {
2814            PackageParser.Activity a = mReceivers.mActivities.get(component);
2815            if (DEBUG_PACKAGE_INFO) Log.v(
2816                TAG, "getReceiverInfo " + component + ": " + a);
2817            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2818                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2819                if (ps == null) return null;
2820                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2821                        userId);
2822            }
2823        }
2824        return null;
2825    }
2826
2827    @Override
2828    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2829        if (!sUserManager.exists(userId)) return null;
2830        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2831        synchronized (mPackages) {
2832            PackageParser.Service s = mServices.mServices.get(component);
2833            if (DEBUG_PACKAGE_INFO) Log.v(
2834                TAG, "getServiceInfo " + component + ": " + s);
2835            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2836                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2837                if (ps == null) return null;
2838                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2839                        userId);
2840            }
2841        }
2842        return null;
2843    }
2844
2845    @Override
2846    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2847        if (!sUserManager.exists(userId)) return null;
2848        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2849        synchronized (mPackages) {
2850            PackageParser.Provider p = mProviders.mProviders.get(component);
2851            if (DEBUG_PACKAGE_INFO) Log.v(
2852                TAG, "getProviderInfo " + component + ": " + p);
2853            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2854                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2855                if (ps == null) return null;
2856                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2857                        userId);
2858            }
2859        }
2860        return null;
2861    }
2862
2863    @Override
2864    public String[] getSystemSharedLibraryNames() {
2865        Set<String> libSet;
2866        synchronized (mPackages) {
2867            libSet = mSharedLibraries.keySet();
2868            int size = libSet.size();
2869            if (size > 0) {
2870                String[] libs = new String[size];
2871                libSet.toArray(libs);
2872                return libs;
2873            }
2874        }
2875        return null;
2876    }
2877
2878    /**
2879     * @hide
2880     */
2881    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2882        synchronized (mPackages) {
2883            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2884            if (lib != null && lib.apk != null) {
2885                return mPackages.get(lib.apk);
2886            }
2887        }
2888        return null;
2889    }
2890
2891    @Override
2892    public FeatureInfo[] getSystemAvailableFeatures() {
2893        Collection<FeatureInfo> featSet;
2894        synchronized (mPackages) {
2895            featSet = mAvailableFeatures.values();
2896            int size = featSet.size();
2897            if (size > 0) {
2898                FeatureInfo[] features = new FeatureInfo[size+1];
2899                featSet.toArray(features);
2900                FeatureInfo fi = new FeatureInfo();
2901                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2902                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2903                features[size] = fi;
2904                return features;
2905            }
2906        }
2907        return null;
2908    }
2909
2910    @Override
2911    public boolean hasSystemFeature(String name) {
2912        synchronized (mPackages) {
2913            return mAvailableFeatures.containsKey(name);
2914        }
2915    }
2916
2917    private void checkValidCaller(int uid, int userId) {
2918        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2919            return;
2920
2921        throw new SecurityException("Caller uid=" + uid
2922                + " is not privileged to communicate with user=" + userId);
2923    }
2924
2925    @Override
2926    public int checkPermission(String permName, String pkgName, int userId) {
2927        if (!sUserManager.exists(userId)) {
2928            return PackageManager.PERMISSION_DENIED;
2929        }
2930
2931        synchronized (mPackages) {
2932            final PackageParser.Package p = mPackages.get(pkgName);
2933            if (p != null && p.mExtras != null) {
2934                final PackageSetting ps = (PackageSetting) p.mExtras;
2935                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2936                    return PackageManager.PERMISSION_GRANTED;
2937                }
2938            }
2939        }
2940
2941        return PackageManager.PERMISSION_DENIED;
2942    }
2943
2944    @Override
2945    public int checkUidPermission(String permName, int uid) {
2946        final int userId = UserHandle.getUserId(uid);
2947
2948        if (!sUserManager.exists(userId)) {
2949            return PackageManager.PERMISSION_DENIED;
2950        }
2951
2952        synchronized (mPackages) {
2953            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2954            if (obj != null) {
2955                final SettingBase ps = (SettingBase) obj;
2956                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2957                    return PackageManager.PERMISSION_GRANTED;
2958                }
2959            } else {
2960                ArraySet<String> perms = mSystemPermissions.get(uid);
2961                if (perms != null && perms.contains(permName)) {
2962                    return PackageManager.PERMISSION_GRANTED;
2963                }
2964            }
2965        }
2966
2967        return PackageManager.PERMISSION_DENIED;
2968    }
2969
2970    /**
2971     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2972     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2973     * @param checkShell TODO(yamasani):
2974     * @param message the message to log on security exception
2975     */
2976    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2977            boolean checkShell, String message) {
2978        if (userId < 0) {
2979            throw new IllegalArgumentException("Invalid userId " + userId);
2980        }
2981        if (checkShell) {
2982            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2983        }
2984        if (userId == UserHandle.getUserId(callingUid)) return;
2985        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2986            if (requireFullPermission) {
2987                mContext.enforceCallingOrSelfPermission(
2988                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2989            } else {
2990                try {
2991                    mContext.enforceCallingOrSelfPermission(
2992                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2993                } catch (SecurityException se) {
2994                    mContext.enforceCallingOrSelfPermission(
2995                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2996                }
2997            }
2998        }
2999    }
3000
3001    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3002        if (callingUid == Process.SHELL_UID) {
3003            if (userHandle >= 0
3004                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3005                throw new SecurityException("Shell does not have permission to access user "
3006                        + userHandle);
3007            } else if (userHandle < 0) {
3008                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3009                        + Debug.getCallers(3));
3010            }
3011        }
3012    }
3013
3014    private BasePermission findPermissionTreeLP(String permName) {
3015        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3016            if (permName.startsWith(bp.name) &&
3017                    permName.length() > bp.name.length() &&
3018                    permName.charAt(bp.name.length()) == '.') {
3019                return bp;
3020            }
3021        }
3022        return null;
3023    }
3024
3025    private BasePermission checkPermissionTreeLP(String permName) {
3026        if (permName != null) {
3027            BasePermission bp = findPermissionTreeLP(permName);
3028            if (bp != null) {
3029                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3030                    return bp;
3031                }
3032                throw new SecurityException("Calling uid "
3033                        + Binder.getCallingUid()
3034                        + " is not allowed to add to permission tree "
3035                        + bp.name + " owned by uid " + bp.uid);
3036            }
3037        }
3038        throw new SecurityException("No permission tree found for " + permName);
3039    }
3040
3041    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3042        if (s1 == null) {
3043            return s2 == null;
3044        }
3045        if (s2 == null) {
3046            return false;
3047        }
3048        if (s1.getClass() != s2.getClass()) {
3049            return false;
3050        }
3051        return s1.equals(s2);
3052    }
3053
3054    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3055        if (pi1.icon != pi2.icon) return false;
3056        if (pi1.logo != pi2.logo) return false;
3057        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3058        if (!compareStrings(pi1.name, pi2.name)) return false;
3059        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3060        // We'll take care of setting this one.
3061        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3062        // These are not currently stored in settings.
3063        //if (!compareStrings(pi1.group, pi2.group)) return false;
3064        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3065        //if (pi1.labelRes != pi2.labelRes) return false;
3066        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3067        return true;
3068    }
3069
3070    int permissionInfoFootprint(PermissionInfo info) {
3071        int size = info.name.length();
3072        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3073        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3074        return size;
3075    }
3076
3077    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3078        int size = 0;
3079        for (BasePermission perm : mSettings.mPermissions.values()) {
3080            if (perm.uid == tree.uid) {
3081                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3082            }
3083        }
3084        return size;
3085    }
3086
3087    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3088        // We calculate the max size of permissions defined by this uid and throw
3089        // if that plus the size of 'info' would exceed our stated maximum.
3090        if (tree.uid != Process.SYSTEM_UID) {
3091            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3092            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3093                throw new SecurityException("Permission tree size cap exceeded");
3094            }
3095        }
3096    }
3097
3098    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3099        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3100            throw new SecurityException("Label must be specified in permission");
3101        }
3102        BasePermission tree = checkPermissionTreeLP(info.name);
3103        BasePermission bp = mSettings.mPermissions.get(info.name);
3104        boolean added = bp == null;
3105        boolean changed = true;
3106        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3107        if (added) {
3108            enforcePermissionCapLocked(info, tree);
3109            bp = new BasePermission(info.name, tree.sourcePackage,
3110                    BasePermission.TYPE_DYNAMIC);
3111        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3112            throw new SecurityException(
3113                    "Not allowed to modify non-dynamic permission "
3114                    + info.name);
3115        } else {
3116            if (bp.protectionLevel == fixedLevel
3117                    && bp.perm.owner.equals(tree.perm.owner)
3118                    && bp.uid == tree.uid
3119                    && comparePermissionInfos(bp.perm.info, info)) {
3120                changed = false;
3121            }
3122        }
3123        bp.protectionLevel = fixedLevel;
3124        info = new PermissionInfo(info);
3125        info.protectionLevel = fixedLevel;
3126        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3127        bp.perm.info.packageName = tree.perm.info.packageName;
3128        bp.uid = tree.uid;
3129        if (added) {
3130            mSettings.mPermissions.put(info.name, bp);
3131        }
3132        if (changed) {
3133            if (!async) {
3134                mSettings.writeLPr();
3135            } else {
3136                scheduleWriteSettingsLocked();
3137            }
3138        }
3139        return added;
3140    }
3141
3142    @Override
3143    public boolean addPermission(PermissionInfo info) {
3144        synchronized (mPackages) {
3145            return addPermissionLocked(info, false);
3146        }
3147    }
3148
3149    @Override
3150    public boolean addPermissionAsync(PermissionInfo info) {
3151        synchronized (mPackages) {
3152            return addPermissionLocked(info, true);
3153        }
3154    }
3155
3156    @Override
3157    public void removePermission(String name) {
3158        synchronized (mPackages) {
3159            checkPermissionTreeLP(name);
3160            BasePermission bp = mSettings.mPermissions.get(name);
3161            if (bp != null) {
3162                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3163                    throw new SecurityException(
3164                            "Not allowed to modify non-dynamic permission "
3165                            + name);
3166                }
3167                mSettings.mPermissions.remove(name);
3168                mSettings.writeLPr();
3169            }
3170        }
3171    }
3172
3173    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3174            BasePermission bp) {
3175        int index = pkg.requestedPermissions.indexOf(bp.name);
3176        if (index == -1) {
3177            throw new SecurityException("Package " + pkg.packageName
3178                    + " has not requested permission " + bp.name);
3179        }
3180        if (!bp.isRuntime()) {
3181            throw new SecurityException("Permission " + bp.name
3182                    + " is not a changeable permission type");
3183        }
3184    }
3185
3186    @Override
3187    public void grantRuntimePermission(String packageName, String name, final int userId) {
3188        if (!sUserManager.exists(userId)) {
3189            Log.e(TAG, "No such user:" + userId);
3190            return;
3191        }
3192
3193        mContext.enforceCallingOrSelfPermission(
3194                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3195                "grantRuntimePermission");
3196
3197        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3198                "grantRuntimePermission");
3199
3200        final SettingBase sb;
3201
3202        synchronized (mPackages) {
3203            final PackageParser.Package pkg = mPackages.get(packageName);
3204            if (pkg == null) {
3205                throw new IllegalArgumentException("Unknown package: " + packageName);
3206            }
3207
3208            final BasePermission bp = mSettings.mPermissions.get(name);
3209            if (bp == null) {
3210                throw new IllegalArgumentException("Unknown permission: " + name);
3211            }
3212
3213            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3214
3215            sb = (SettingBase) pkg.mExtras;
3216            if (sb == null) {
3217                throw new IllegalArgumentException("Unknown package: " + packageName);
3218            }
3219
3220            final PermissionsState permissionsState = sb.getPermissionsState();
3221
3222            final int flags = permissionsState.getPermissionFlags(name, userId);
3223            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3224                throw new SecurityException("Cannot grant system fixed permission: "
3225                        + name + " for package: " + packageName);
3226            }
3227
3228            final int result = permissionsState.grantRuntimePermission(bp, userId);
3229            switch (result) {
3230                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3231                    return;
3232                }
3233
3234                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3235                    mHandler.post(new Runnable() {
3236                        @Override
3237                        public void run() {
3238                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3239                        }
3240                    });
3241                } break;
3242            }
3243
3244            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3245
3246            // Not critical if that is lost - app has to request again.
3247            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3248        }
3249    }
3250
3251    @Override
3252    public void revokeRuntimePermission(String packageName, String name, int userId) {
3253        if (!sUserManager.exists(userId)) {
3254            Log.e(TAG, "No such user:" + userId);
3255            return;
3256        }
3257
3258        mContext.enforceCallingOrSelfPermission(
3259                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3260                "revokeRuntimePermission");
3261
3262        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3263                "revokeRuntimePermission");
3264
3265        final SettingBase sb;
3266
3267        synchronized (mPackages) {
3268            final PackageParser.Package pkg = mPackages.get(packageName);
3269            if (pkg == null) {
3270                throw new IllegalArgumentException("Unknown package: " + packageName);
3271            }
3272
3273            final BasePermission bp = mSettings.mPermissions.get(name);
3274            if (bp == null) {
3275                throw new IllegalArgumentException("Unknown permission: " + name);
3276            }
3277
3278            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3279
3280            sb = (SettingBase) pkg.mExtras;
3281            if (sb == null) {
3282                throw new IllegalArgumentException("Unknown package: " + packageName);
3283            }
3284
3285            final PermissionsState permissionsState = sb.getPermissionsState();
3286
3287            final int flags = permissionsState.getPermissionFlags(name, userId);
3288            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3289                throw new SecurityException("Cannot revoke system fixed permission: "
3290                        + name + " for package: " + packageName);
3291            }
3292
3293            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3294                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3295                return;
3296            }
3297
3298            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3299
3300            // Critical, after this call app should never have the permission.
3301            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3302        }
3303
3304        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3305    }
3306
3307    @Override
3308    public int getPermissionFlags(String name, String packageName, int userId) {
3309        if (!sUserManager.exists(userId)) {
3310            return 0;
3311        }
3312
3313        mContext.enforceCallingOrSelfPermission(
3314                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3315                "getPermissionFlags");
3316
3317        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3318                "getPermissionFlags");
3319
3320        synchronized (mPackages) {
3321            final PackageParser.Package pkg = mPackages.get(packageName);
3322            if (pkg == null) {
3323                throw new IllegalArgumentException("Unknown package: " + packageName);
3324            }
3325
3326            final BasePermission bp = mSettings.mPermissions.get(name);
3327            if (bp == null) {
3328                throw new IllegalArgumentException("Unknown permission: " + name);
3329            }
3330
3331            SettingBase sb = (SettingBase) pkg.mExtras;
3332            if (sb == null) {
3333                throw new IllegalArgumentException("Unknown package: " + packageName);
3334            }
3335
3336            PermissionsState permissionsState = sb.getPermissionsState();
3337            return permissionsState.getPermissionFlags(name, userId);
3338        }
3339    }
3340
3341    @Override
3342    public void updatePermissionFlags(String name, String packageName, int flagMask,
3343            int flagValues, int userId) {
3344        if (!sUserManager.exists(userId)) {
3345            return;
3346        }
3347
3348        mContext.enforceCallingOrSelfPermission(
3349                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3350                "updatePermissionFlags");
3351
3352        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3353                "updatePermissionFlags");
3354
3355        // Only the system can change policy and system fixed flags.
3356        if (getCallingUid() != Process.SYSTEM_UID) {
3357            flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3358            flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3359
3360            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3361            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3362        }
3363
3364        synchronized (mPackages) {
3365            final PackageParser.Package pkg = mPackages.get(packageName);
3366            if (pkg == null) {
3367                throw new IllegalArgumentException("Unknown package: " + packageName);
3368            }
3369
3370            final BasePermission bp = mSettings.mPermissions.get(name);
3371            if (bp == null) {
3372                throw new IllegalArgumentException("Unknown permission: " + name);
3373            }
3374
3375            SettingBase sb = (SettingBase) pkg.mExtras;
3376            if (sb == null) {
3377                throw new IllegalArgumentException("Unknown package: " + packageName);
3378            }
3379
3380            PermissionsState permissionsState = sb.getPermissionsState();
3381
3382            // Only the package manager can change flags for system component permissions.
3383            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3384            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3385                return;
3386            }
3387
3388            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3389                // Install and runtime permissions are stored in different places,
3390                // so figure out what permission changed and persist the change.
3391                if (permissionsState.getInstallPermissionState(name) != null) {
3392                    scheduleWriteSettingsLocked();
3393                } else if (permissionsState.getRuntimePermissionState(name, userId) != null) {
3394                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3395                }
3396            }
3397        }
3398    }
3399
3400    @Override
3401    public boolean shouldShowRequestPermissionRationale(String permissionName,
3402            String packageName, int userId) {
3403        if (UserHandle.getCallingUserId() != userId) {
3404            mContext.enforceCallingPermission(
3405                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3406                    "canShowRequestPermissionRationale for user " + userId);
3407        }
3408
3409        final int uid = getPackageUid(packageName, userId);
3410        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3411            return false;
3412        }
3413
3414        if (checkPermission(permissionName, packageName, userId)
3415                == PackageManager.PERMISSION_GRANTED) {
3416            return false;
3417        }
3418
3419        final int flags;
3420
3421        final long identity = Binder.clearCallingIdentity();
3422        try {
3423            flags = getPermissionFlags(permissionName,
3424                    packageName, userId);
3425        } finally {
3426            Binder.restoreCallingIdentity(identity);
3427        }
3428
3429        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3430                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3431                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3432
3433        if ((flags & fixedFlags) != 0) {
3434            return false;
3435        }
3436
3437        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3438    }
3439
3440    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3441        BasePermission bp = mSettings.mPermissions.get(permission);
3442        if (bp == null) {
3443            throw new SecurityException("Missing " + permission + " permission");
3444        }
3445
3446        SettingBase sb = (SettingBase) pkg.mExtras;
3447        PermissionsState permissionsState = sb.getPermissionsState();
3448
3449        if (permissionsState.grantInstallPermission(bp) !=
3450                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3451            scheduleWriteSettingsLocked();
3452        }
3453    }
3454
3455    @Override
3456    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3457        mContext.enforceCallingOrSelfPermission(
3458                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3459                "addOnPermissionsChangeListener");
3460
3461        synchronized (mPackages) {
3462            mOnPermissionChangeListeners.addListenerLocked(listener);
3463        }
3464    }
3465
3466    @Override
3467    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3468        synchronized (mPackages) {
3469            mOnPermissionChangeListeners.removeListenerLocked(listener);
3470        }
3471    }
3472
3473    @Override
3474    public boolean isProtectedBroadcast(String actionName) {
3475        synchronized (mPackages) {
3476            return mProtectedBroadcasts.contains(actionName);
3477        }
3478    }
3479
3480    @Override
3481    public int checkSignatures(String pkg1, String pkg2) {
3482        synchronized (mPackages) {
3483            final PackageParser.Package p1 = mPackages.get(pkg1);
3484            final PackageParser.Package p2 = mPackages.get(pkg2);
3485            if (p1 == null || p1.mExtras == null
3486                    || p2 == null || p2.mExtras == null) {
3487                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3488            }
3489            return compareSignatures(p1.mSignatures, p2.mSignatures);
3490        }
3491    }
3492
3493    @Override
3494    public int checkUidSignatures(int uid1, int uid2) {
3495        // Map to base uids.
3496        uid1 = UserHandle.getAppId(uid1);
3497        uid2 = UserHandle.getAppId(uid2);
3498        // reader
3499        synchronized (mPackages) {
3500            Signature[] s1;
3501            Signature[] s2;
3502            Object obj = mSettings.getUserIdLPr(uid1);
3503            if (obj != null) {
3504                if (obj instanceof SharedUserSetting) {
3505                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3506                } else if (obj instanceof PackageSetting) {
3507                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3508                } else {
3509                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3510                }
3511            } else {
3512                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3513            }
3514            obj = mSettings.getUserIdLPr(uid2);
3515            if (obj != null) {
3516                if (obj instanceof SharedUserSetting) {
3517                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3518                } else if (obj instanceof PackageSetting) {
3519                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3520                } else {
3521                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3522                }
3523            } else {
3524                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3525            }
3526            return compareSignatures(s1, s2);
3527        }
3528    }
3529
3530    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3531        final long identity = Binder.clearCallingIdentity();
3532        try {
3533            if (sb instanceof SharedUserSetting) {
3534                SharedUserSetting sus = (SharedUserSetting) sb;
3535                final int packageCount = sus.packages.size();
3536                for (int i = 0; i < packageCount; i++) {
3537                    PackageSetting susPs = sus.packages.valueAt(i);
3538                    if (userId == UserHandle.USER_ALL) {
3539                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3540                    } else {
3541                        final int uid = UserHandle.getUid(userId, susPs.appId);
3542                        killUid(uid, reason);
3543                    }
3544                }
3545            } else if (sb instanceof PackageSetting) {
3546                PackageSetting ps = (PackageSetting) sb;
3547                if (userId == UserHandle.USER_ALL) {
3548                    killApplication(ps.pkg.packageName, ps.appId, reason);
3549                } else {
3550                    final int uid = UserHandle.getUid(userId, ps.appId);
3551                    killUid(uid, reason);
3552                }
3553            }
3554        } finally {
3555            Binder.restoreCallingIdentity(identity);
3556        }
3557    }
3558
3559    private static void killUid(int uid, String reason) {
3560        IActivityManager am = ActivityManagerNative.getDefault();
3561        if (am != null) {
3562            try {
3563                am.killUid(uid, reason);
3564            } catch (RemoteException e) {
3565                /* ignore - same process */
3566            }
3567        }
3568    }
3569
3570    /**
3571     * Compares two sets of signatures. Returns:
3572     * <br />
3573     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3574     * <br />
3575     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3576     * <br />
3577     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3578     * <br />
3579     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3580     * <br />
3581     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3582     */
3583    static int compareSignatures(Signature[] s1, Signature[] s2) {
3584        if (s1 == null) {
3585            return s2 == null
3586                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3587                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3588        }
3589
3590        if (s2 == null) {
3591            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3592        }
3593
3594        if (s1.length != s2.length) {
3595            return PackageManager.SIGNATURE_NO_MATCH;
3596        }
3597
3598        // Since both signature sets are of size 1, we can compare without HashSets.
3599        if (s1.length == 1) {
3600            return s1[0].equals(s2[0]) ?
3601                    PackageManager.SIGNATURE_MATCH :
3602                    PackageManager.SIGNATURE_NO_MATCH;
3603        }
3604
3605        ArraySet<Signature> set1 = new ArraySet<Signature>();
3606        for (Signature sig : s1) {
3607            set1.add(sig);
3608        }
3609        ArraySet<Signature> set2 = new ArraySet<Signature>();
3610        for (Signature sig : s2) {
3611            set2.add(sig);
3612        }
3613        // Make sure s2 contains all signatures in s1.
3614        if (set1.equals(set2)) {
3615            return PackageManager.SIGNATURE_MATCH;
3616        }
3617        return PackageManager.SIGNATURE_NO_MATCH;
3618    }
3619
3620    /**
3621     * If the database version for this type of package (internal storage or
3622     * external storage) is less than the version where package signatures
3623     * were updated, return true.
3624     */
3625    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3626        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3627                DatabaseVersion.SIGNATURE_END_ENTITY))
3628                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3629                        DatabaseVersion.SIGNATURE_END_ENTITY));
3630    }
3631
3632    /**
3633     * Used for backward compatibility to make sure any packages with
3634     * certificate chains get upgraded to the new style. {@code existingSigs}
3635     * will be in the old format (since they were stored on disk from before the
3636     * system upgrade) and {@code scannedSigs} will be in the newer format.
3637     */
3638    private int compareSignaturesCompat(PackageSignatures existingSigs,
3639            PackageParser.Package scannedPkg) {
3640        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3641            return PackageManager.SIGNATURE_NO_MATCH;
3642        }
3643
3644        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3645        for (Signature sig : existingSigs.mSignatures) {
3646            existingSet.add(sig);
3647        }
3648        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3649        for (Signature sig : scannedPkg.mSignatures) {
3650            try {
3651                Signature[] chainSignatures = sig.getChainSignatures();
3652                for (Signature chainSig : chainSignatures) {
3653                    scannedCompatSet.add(chainSig);
3654                }
3655            } catch (CertificateEncodingException e) {
3656                scannedCompatSet.add(sig);
3657            }
3658        }
3659        /*
3660         * Make sure the expanded scanned set contains all signatures in the
3661         * existing one.
3662         */
3663        if (scannedCompatSet.equals(existingSet)) {
3664            // Migrate the old signatures to the new scheme.
3665            existingSigs.assignSignatures(scannedPkg.mSignatures);
3666            // The new KeySets will be re-added later in the scanning process.
3667            synchronized (mPackages) {
3668                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3669            }
3670            return PackageManager.SIGNATURE_MATCH;
3671        }
3672        return PackageManager.SIGNATURE_NO_MATCH;
3673    }
3674
3675    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3676        if (isExternal(scannedPkg)) {
3677            return mSettings.isExternalDatabaseVersionOlderThan(
3678                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3679        } else {
3680            return mSettings.isInternalDatabaseVersionOlderThan(
3681                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3682        }
3683    }
3684
3685    private int compareSignaturesRecover(PackageSignatures existingSigs,
3686            PackageParser.Package scannedPkg) {
3687        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3688            return PackageManager.SIGNATURE_NO_MATCH;
3689        }
3690
3691        String msg = null;
3692        try {
3693            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3694                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3695                        + scannedPkg.packageName);
3696                return PackageManager.SIGNATURE_MATCH;
3697            }
3698        } catch (CertificateException e) {
3699            msg = e.getMessage();
3700        }
3701
3702        logCriticalInfo(Log.INFO,
3703                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3704        return PackageManager.SIGNATURE_NO_MATCH;
3705    }
3706
3707    @Override
3708    public String[] getPackagesForUid(int uid) {
3709        uid = UserHandle.getAppId(uid);
3710        // reader
3711        synchronized (mPackages) {
3712            Object obj = mSettings.getUserIdLPr(uid);
3713            if (obj instanceof SharedUserSetting) {
3714                final SharedUserSetting sus = (SharedUserSetting) obj;
3715                final int N = sus.packages.size();
3716                final String[] res = new String[N];
3717                final Iterator<PackageSetting> it = sus.packages.iterator();
3718                int i = 0;
3719                while (it.hasNext()) {
3720                    res[i++] = it.next().name;
3721                }
3722                return res;
3723            } else if (obj instanceof PackageSetting) {
3724                final PackageSetting ps = (PackageSetting) obj;
3725                return new String[] { ps.name };
3726            }
3727        }
3728        return null;
3729    }
3730
3731    @Override
3732    public String getNameForUid(int uid) {
3733        // reader
3734        synchronized (mPackages) {
3735            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3736            if (obj instanceof SharedUserSetting) {
3737                final SharedUserSetting sus = (SharedUserSetting) obj;
3738                return sus.name + ":" + sus.userId;
3739            } else if (obj instanceof PackageSetting) {
3740                final PackageSetting ps = (PackageSetting) obj;
3741                return ps.name;
3742            }
3743        }
3744        return null;
3745    }
3746
3747    @Override
3748    public int getUidForSharedUser(String sharedUserName) {
3749        if(sharedUserName == null) {
3750            return -1;
3751        }
3752        // reader
3753        synchronized (mPackages) {
3754            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3755            if (suid == null) {
3756                return -1;
3757            }
3758            return suid.userId;
3759        }
3760    }
3761
3762    @Override
3763    public int getFlagsForUid(int uid) {
3764        synchronized (mPackages) {
3765            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3766            if (obj instanceof SharedUserSetting) {
3767                final SharedUserSetting sus = (SharedUserSetting) obj;
3768                return sus.pkgFlags;
3769            } else if (obj instanceof PackageSetting) {
3770                final PackageSetting ps = (PackageSetting) obj;
3771                return ps.pkgFlags;
3772            }
3773        }
3774        return 0;
3775    }
3776
3777    @Override
3778    public int getPrivateFlagsForUid(int uid) {
3779        synchronized (mPackages) {
3780            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3781            if (obj instanceof SharedUserSetting) {
3782                final SharedUserSetting sus = (SharedUserSetting) obj;
3783                return sus.pkgPrivateFlags;
3784            } else if (obj instanceof PackageSetting) {
3785                final PackageSetting ps = (PackageSetting) obj;
3786                return ps.pkgPrivateFlags;
3787            }
3788        }
3789        return 0;
3790    }
3791
3792    @Override
3793    public boolean isUidPrivileged(int uid) {
3794        uid = UserHandle.getAppId(uid);
3795        // reader
3796        synchronized (mPackages) {
3797            Object obj = mSettings.getUserIdLPr(uid);
3798            if (obj instanceof SharedUserSetting) {
3799                final SharedUserSetting sus = (SharedUserSetting) obj;
3800                final Iterator<PackageSetting> it = sus.packages.iterator();
3801                while (it.hasNext()) {
3802                    if (it.next().isPrivileged()) {
3803                        return true;
3804                    }
3805                }
3806            } else if (obj instanceof PackageSetting) {
3807                final PackageSetting ps = (PackageSetting) obj;
3808                return ps.isPrivileged();
3809            }
3810        }
3811        return false;
3812    }
3813
3814    @Override
3815    public String[] getAppOpPermissionPackages(String permissionName) {
3816        synchronized (mPackages) {
3817            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3818            if (pkgs == null) {
3819                return null;
3820            }
3821            return pkgs.toArray(new String[pkgs.size()]);
3822        }
3823    }
3824
3825    @Override
3826    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3827            int flags, int userId) {
3828        if (!sUserManager.exists(userId)) return null;
3829        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3830        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3831        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3832    }
3833
3834    @Override
3835    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3836            IntentFilter filter, int match, ComponentName activity) {
3837        final int userId = UserHandle.getCallingUserId();
3838        if (DEBUG_PREFERRED) {
3839            Log.v(TAG, "setLastChosenActivity intent=" + intent
3840                + " resolvedType=" + resolvedType
3841                + " flags=" + flags
3842                + " filter=" + filter
3843                + " match=" + match
3844                + " activity=" + activity);
3845            filter.dump(new PrintStreamPrinter(System.out), "    ");
3846        }
3847        intent.setComponent(null);
3848        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3849        // Find any earlier preferred or last chosen entries and nuke them
3850        findPreferredActivity(intent, resolvedType,
3851                flags, query, 0, false, true, false, userId);
3852        // Add the new activity as the last chosen for this filter
3853        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3854                "Setting last chosen");
3855    }
3856
3857    @Override
3858    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3859        final int userId = UserHandle.getCallingUserId();
3860        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3861        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3862        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3863                false, false, false, userId);
3864    }
3865
3866    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3867            int flags, List<ResolveInfo> query, int userId) {
3868        if (query != null) {
3869            final int N = query.size();
3870            if (N == 1) {
3871                return query.get(0);
3872            } else if (N > 1) {
3873                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3874                // If there is more than one activity with the same priority,
3875                // then let the user decide between them.
3876                ResolveInfo r0 = query.get(0);
3877                ResolveInfo r1 = query.get(1);
3878                if (DEBUG_INTENT_MATCHING || debug) {
3879                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3880                            + r1.activityInfo.name + "=" + r1.priority);
3881                }
3882                // If the first activity has a higher priority, or a different
3883                // default, then it is always desireable to pick it.
3884                if (r0.priority != r1.priority
3885                        || r0.preferredOrder != r1.preferredOrder
3886                        || r0.isDefault != r1.isDefault) {
3887                    return query.get(0);
3888                }
3889                // If we have saved a preference for a preferred activity for
3890                // this Intent, use that.
3891                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3892                        flags, query, r0.priority, true, false, debug, userId);
3893                if (ri != null) {
3894                    return ri;
3895                }
3896                if (userId != 0) {
3897                    ri = new ResolveInfo(mResolveInfo);
3898                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3899                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3900                            ri.activityInfo.applicationInfo);
3901                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3902                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3903                    return ri;
3904                }
3905                return mResolveInfo;
3906            }
3907        }
3908        return null;
3909    }
3910
3911    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3912            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3913        final int N = query.size();
3914        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3915                .get(userId);
3916        // Get the list of persistent preferred activities that handle the intent
3917        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3918        List<PersistentPreferredActivity> pprefs = ppir != null
3919                ? ppir.queryIntent(intent, resolvedType,
3920                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3921                : null;
3922        if (pprefs != null && pprefs.size() > 0) {
3923            final int M = pprefs.size();
3924            for (int i=0; i<M; i++) {
3925                final PersistentPreferredActivity ppa = pprefs.get(i);
3926                if (DEBUG_PREFERRED || debug) {
3927                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3928                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3929                            + "\n  component=" + ppa.mComponent);
3930                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3931                }
3932                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3933                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3934                if (DEBUG_PREFERRED || debug) {
3935                    Slog.v(TAG, "Found persistent preferred activity:");
3936                    if (ai != null) {
3937                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3938                    } else {
3939                        Slog.v(TAG, "  null");
3940                    }
3941                }
3942                if (ai == null) {
3943                    // This previously registered persistent preferred activity
3944                    // component is no longer known. Ignore it and do NOT remove it.
3945                    continue;
3946                }
3947                for (int j=0; j<N; j++) {
3948                    final ResolveInfo ri = query.get(j);
3949                    if (!ri.activityInfo.applicationInfo.packageName
3950                            .equals(ai.applicationInfo.packageName)) {
3951                        continue;
3952                    }
3953                    if (!ri.activityInfo.name.equals(ai.name)) {
3954                        continue;
3955                    }
3956                    //  Found a persistent preference that can handle the intent.
3957                    if (DEBUG_PREFERRED || debug) {
3958                        Slog.v(TAG, "Returning persistent preferred activity: " +
3959                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3960                    }
3961                    return ri;
3962                }
3963            }
3964        }
3965        return null;
3966    }
3967
3968    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3969            List<ResolveInfo> query, int priority, boolean always,
3970            boolean removeMatches, boolean debug, int userId) {
3971        if (!sUserManager.exists(userId)) return null;
3972        // writer
3973        synchronized (mPackages) {
3974            if (intent.getSelector() != null) {
3975                intent = intent.getSelector();
3976            }
3977            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3978
3979            // Try to find a matching persistent preferred activity.
3980            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3981                    debug, userId);
3982
3983            // If a persistent preferred activity matched, use it.
3984            if (pri != null) {
3985                return pri;
3986            }
3987
3988            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3989            // Get the list of preferred activities that handle the intent
3990            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3991            List<PreferredActivity> prefs = pir != null
3992                    ? pir.queryIntent(intent, resolvedType,
3993                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3994                    : null;
3995            if (prefs != null && prefs.size() > 0) {
3996                boolean changed = false;
3997                try {
3998                    // First figure out how good the original match set is.
3999                    // We will only allow preferred activities that came
4000                    // from the same match quality.
4001                    int match = 0;
4002
4003                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4004
4005                    final int N = query.size();
4006                    for (int j=0; j<N; j++) {
4007                        final ResolveInfo ri = query.get(j);
4008                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4009                                + ": 0x" + Integer.toHexString(match));
4010                        if (ri.match > match) {
4011                            match = ri.match;
4012                        }
4013                    }
4014
4015                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4016                            + Integer.toHexString(match));
4017
4018                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4019                    final int M = prefs.size();
4020                    for (int i=0; i<M; i++) {
4021                        final PreferredActivity pa = prefs.get(i);
4022                        if (DEBUG_PREFERRED || debug) {
4023                            Slog.v(TAG, "Checking PreferredActivity ds="
4024                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4025                                    + "\n  component=" + pa.mPref.mComponent);
4026                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4027                        }
4028                        if (pa.mPref.mMatch != match) {
4029                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4030                                    + Integer.toHexString(pa.mPref.mMatch));
4031                            continue;
4032                        }
4033                        // If it's not an "always" type preferred activity and that's what we're
4034                        // looking for, skip it.
4035                        if (always && !pa.mPref.mAlways) {
4036                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4037                            continue;
4038                        }
4039                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4040                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4041                        if (DEBUG_PREFERRED || debug) {
4042                            Slog.v(TAG, "Found preferred activity:");
4043                            if (ai != null) {
4044                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4045                            } else {
4046                                Slog.v(TAG, "  null");
4047                            }
4048                        }
4049                        if (ai == null) {
4050                            // This previously registered preferred activity
4051                            // component is no longer known.  Most likely an update
4052                            // to the app was installed and in the new version this
4053                            // component no longer exists.  Clean it up by removing
4054                            // it from the preferred activities list, and skip it.
4055                            Slog.w(TAG, "Removing dangling preferred activity: "
4056                                    + pa.mPref.mComponent);
4057                            pir.removeFilter(pa);
4058                            changed = true;
4059                            continue;
4060                        }
4061                        for (int j=0; j<N; j++) {
4062                            final ResolveInfo ri = query.get(j);
4063                            if (!ri.activityInfo.applicationInfo.packageName
4064                                    .equals(ai.applicationInfo.packageName)) {
4065                                continue;
4066                            }
4067                            if (!ri.activityInfo.name.equals(ai.name)) {
4068                                continue;
4069                            }
4070
4071                            if (removeMatches) {
4072                                pir.removeFilter(pa);
4073                                changed = true;
4074                                if (DEBUG_PREFERRED) {
4075                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4076                                }
4077                                break;
4078                            }
4079
4080                            // Okay we found a previously set preferred or last chosen app.
4081                            // If the result set is different from when this
4082                            // was created, we need to clear it and re-ask the
4083                            // user their preference, if we're looking for an "always" type entry.
4084                            if (always && !pa.mPref.sameSet(query)) {
4085                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4086                                        + intent + " type " + resolvedType);
4087                                if (DEBUG_PREFERRED) {
4088                                    Slog.v(TAG, "Removing preferred activity since set changed "
4089                                            + pa.mPref.mComponent);
4090                                }
4091                                pir.removeFilter(pa);
4092                                // Re-add the filter as a "last chosen" entry (!always)
4093                                PreferredActivity lastChosen = new PreferredActivity(
4094                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4095                                pir.addFilter(lastChosen);
4096                                changed = true;
4097                                return null;
4098                            }
4099
4100                            // Yay! Either the set matched or we're looking for the last chosen
4101                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4102                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4103                            return ri;
4104                        }
4105                    }
4106                } finally {
4107                    if (changed) {
4108                        if (DEBUG_PREFERRED) {
4109                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4110                        }
4111                        scheduleWritePackageRestrictionsLocked(userId);
4112                    }
4113                }
4114            }
4115        }
4116        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4117        return null;
4118    }
4119
4120    /*
4121     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4122     */
4123    @Override
4124    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4125            int targetUserId) {
4126        mContext.enforceCallingOrSelfPermission(
4127                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4128        List<CrossProfileIntentFilter> matches =
4129                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4130        if (matches != null) {
4131            int size = matches.size();
4132            for (int i = 0; i < size; i++) {
4133                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4134            }
4135        }
4136        if (hasWebURI(intent)) {
4137            // cross-profile app linking works only towards the parent.
4138            final UserInfo parent = getProfileParent(sourceUserId);
4139            synchronized(mPackages) {
4140                return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId,
4141                        parent.id) != null;
4142            }
4143        }
4144        return false;
4145    }
4146
4147    private UserInfo getProfileParent(int userId) {
4148        final long identity = Binder.clearCallingIdentity();
4149        try {
4150            return sUserManager.getProfileParent(userId);
4151        } finally {
4152            Binder.restoreCallingIdentity(identity);
4153        }
4154    }
4155
4156    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4157            String resolvedType, int userId) {
4158        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4159        if (resolver != null) {
4160            return resolver.queryIntent(intent, resolvedType, false, userId);
4161        }
4162        return null;
4163    }
4164
4165    @Override
4166    public List<ResolveInfo> queryIntentActivities(Intent intent,
4167            String resolvedType, int flags, int userId) {
4168        if (!sUserManager.exists(userId)) return Collections.emptyList();
4169        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4170        ComponentName comp = intent.getComponent();
4171        if (comp == null) {
4172            if (intent.getSelector() != null) {
4173                intent = intent.getSelector();
4174                comp = intent.getComponent();
4175            }
4176        }
4177
4178        if (comp != null) {
4179            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4180            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4181            if (ai != null) {
4182                final ResolveInfo ri = new ResolveInfo();
4183                ri.activityInfo = ai;
4184                list.add(ri);
4185            }
4186            return list;
4187        }
4188
4189        // reader
4190        synchronized (mPackages) {
4191            final String pkgName = intent.getPackage();
4192            if (pkgName == null) {
4193                List<CrossProfileIntentFilter> matchingFilters =
4194                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4195                // Check for results that need to skip the current profile.
4196                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4197                        resolvedType, flags, userId);
4198                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4199                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4200                    result.add(xpResolveInfo);
4201                    return filterIfNotPrimaryUser(result, userId);
4202                }
4203
4204                // Check for results in the current profile.
4205                List<ResolveInfo> result = mActivities.queryIntent(
4206                        intent, resolvedType, flags, userId);
4207
4208                // Check for cross profile results.
4209                xpResolveInfo = queryCrossProfileIntents(
4210                        matchingFilters, intent, resolvedType, flags, userId);
4211                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4212                    result.add(xpResolveInfo);
4213                    Collections.sort(result, mResolvePrioritySorter);
4214                }
4215                result = filterIfNotPrimaryUser(result, userId);
4216                if (hasWebURI(intent)) {
4217                    CrossProfileDomainInfo xpDomainInfo = null;
4218                    final UserInfo parent = getProfileParent(userId);
4219                    if (parent != null) {
4220                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4221                                flags, userId, parent.id);
4222                    }
4223                    if (xpDomainInfo != null) {
4224                        if (xpResolveInfo != null) {
4225                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4226                            // in the result.
4227                            result.remove(xpResolveInfo);
4228                        }
4229                        if (result.size() == 0) {
4230                            result.add(xpDomainInfo.resolveInfo);
4231                            return result;
4232                        }
4233                    } else if (result.size() <= 1) {
4234                        return result;
4235                    }
4236                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4237                            xpDomainInfo);
4238                    Collections.sort(result, mResolvePrioritySorter);
4239                }
4240                return result;
4241            }
4242            final PackageParser.Package pkg = mPackages.get(pkgName);
4243            if (pkg != null) {
4244                return filterIfNotPrimaryUser(
4245                        mActivities.queryIntentForPackage(
4246                                intent, resolvedType, flags, pkg.activities, userId),
4247                        userId);
4248            }
4249            return new ArrayList<ResolveInfo>();
4250        }
4251    }
4252
4253    private static class CrossProfileDomainInfo {
4254        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4255        ResolveInfo resolveInfo;
4256        /* Best domain verification status of the activities found in the other profile */
4257        int bestDomainVerificationStatus;
4258    }
4259
4260    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4261            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4262        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_APP_LINKING,
4263                sourceUserId)) {
4264            return null;
4265        }
4266        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4267                resolvedType, flags, parentUserId);
4268
4269        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4270            return null;
4271        }
4272        CrossProfileDomainInfo result = null;
4273        int size = resultTargetUser.size();
4274        for (int i = 0; i < size; i++) {
4275            ResolveInfo riTargetUser = resultTargetUser.get(i);
4276            // Intent filter verification is only for filters that specify a host. So don't return
4277            // those that handle all web uris.
4278            if (riTargetUser.handleAllWebDataURI) {
4279                continue;
4280            }
4281            String packageName = riTargetUser.activityInfo.packageName;
4282            PackageSetting ps = mSettings.mPackages.get(packageName);
4283            if (ps == null) {
4284                continue;
4285            }
4286            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4287            if (result == null) {
4288                result = new CrossProfileDomainInfo();
4289                result.resolveInfo =
4290                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4291                result.bestDomainVerificationStatus = status;
4292            } else {
4293                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4294                        result.bestDomainVerificationStatus);
4295            }
4296        }
4297        return result;
4298    }
4299
4300    /**
4301     * Verification statuses are ordered from the worse to the best, except for
4302     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4303     */
4304    private int bestDomainVerificationStatus(int status1, int status2) {
4305        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4306            return status2;
4307        }
4308        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4309            return status1;
4310        }
4311        return (int) MathUtils.max(status1, status2);
4312    }
4313
4314    private boolean isUserEnabled(int userId) {
4315        long callingId = Binder.clearCallingIdentity();
4316        try {
4317            UserInfo userInfo = sUserManager.getUserInfo(userId);
4318            return userInfo != null && userInfo.isEnabled();
4319        } finally {
4320            Binder.restoreCallingIdentity(callingId);
4321        }
4322    }
4323
4324    /**
4325     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4326     *
4327     * @return filtered list
4328     */
4329    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4330        if (userId == UserHandle.USER_OWNER) {
4331            return resolveInfos;
4332        }
4333        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4334            ResolveInfo info = resolveInfos.get(i);
4335            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4336                resolveInfos.remove(i);
4337            }
4338        }
4339        return resolveInfos;
4340    }
4341
4342    private static boolean hasWebURI(Intent intent) {
4343        if (intent.getData() == null) {
4344            return false;
4345        }
4346        final String scheme = intent.getScheme();
4347        if (TextUtils.isEmpty(scheme)) {
4348            return false;
4349        }
4350        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4351    }
4352
4353    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4354            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4355        if (DEBUG_PREFERRED) {
4356            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4357                    candidates.size());
4358        }
4359
4360        final int userId = UserHandle.getCallingUserId();
4361        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4362        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4363        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4364        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4365        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4366
4367        synchronized (mPackages) {
4368            final int count = candidates.size();
4369            // First, try to use the domain prefered App. Partition the candidates into four lists:
4370            // one for the final results, one for the "do not use ever", one for "undefined status"
4371            // and finally one for "Browser App type".
4372            for (int n=0; n<count; n++) {
4373                ResolveInfo info = candidates.get(n);
4374                String packageName = info.activityInfo.packageName;
4375                PackageSetting ps = mSettings.mPackages.get(packageName);
4376                if (ps != null) {
4377                    // Add to the special match all list (Browser use case)
4378                    if (info.handleAllWebDataURI) {
4379                        matchAllList.add(info);
4380                        continue;
4381                    }
4382                    // Try to get the status from User settings first
4383                    int status = getDomainVerificationStatusLPr(ps, userId);
4384                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4385                        alwaysList.add(info);
4386                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4387                        neverList.add(info);
4388                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4389                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4390                        undefinedList.add(info);
4391                    }
4392                }
4393            }
4394            // First try to add the "always" resolution for the current user if there is any
4395            if (alwaysList.size() > 0) {
4396                result.addAll(alwaysList);
4397            // if there is an "always" for the parent user, add it.
4398            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4399                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4400                result.add(xpDomainInfo.resolveInfo);
4401            } else {
4402                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4403                result.addAll(undefinedList);
4404                if (xpDomainInfo != null && (
4405                        xpDomainInfo.bestDomainVerificationStatus
4406                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4407                        || xpDomainInfo.bestDomainVerificationStatus
4408                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4409                    result.add(xpDomainInfo.resolveInfo);
4410                }
4411                // Also add Browsers (all of them or only the default one)
4412                if ((flags & MATCH_ALL) != 0) {
4413                    result.addAll(matchAllList);
4414                } else {
4415                    // Try to add the Default Browser if we can
4416                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4417                            UserHandle.myUserId());
4418                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4419                        boolean defaultBrowserFound = false;
4420                        final int browserCount = matchAllList.size();
4421                        for (int n=0; n<browserCount; n++) {
4422                            ResolveInfo browser = matchAllList.get(n);
4423                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4424                                result.add(browser);
4425                                defaultBrowserFound = true;
4426                                break;
4427                            }
4428                        }
4429                        if (!defaultBrowserFound) {
4430                            result.addAll(matchAllList);
4431                        }
4432                    } else {
4433                        result.addAll(matchAllList);
4434                    }
4435                }
4436
4437                // If there is nothing selected, add all candidates and remove the ones that the User
4438                // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4439                if (result.size() == 0) {
4440                    result.addAll(candidates);
4441                    result.removeAll(neverList);
4442                }
4443            }
4444        }
4445        if (DEBUG_PREFERRED) {
4446            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4447                    result.size());
4448        }
4449        return result;
4450    }
4451
4452    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4453        int status = ps.getDomainVerificationStatusForUser(userId);
4454        // if none available, get the master status
4455        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4456            if (ps.getIntentFilterVerificationInfo() != null) {
4457                status = ps.getIntentFilterVerificationInfo().getStatus();
4458            }
4459        }
4460        return status;
4461    }
4462
4463    private ResolveInfo querySkipCurrentProfileIntents(
4464            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4465            int flags, int sourceUserId) {
4466        if (matchingFilters != null) {
4467            int size = matchingFilters.size();
4468            for (int i = 0; i < size; i ++) {
4469                CrossProfileIntentFilter filter = matchingFilters.get(i);
4470                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4471                    // Checking if there are activities in the target user that can handle the
4472                    // intent.
4473                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4474                            flags, sourceUserId);
4475                    if (resolveInfo != null) {
4476                        return resolveInfo;
4477                    }
4478                }
4479            }
4480        }
4481        return null;
4482    }
4483
4484    // Return matching ResolveInfo if any for skip current profile intent filters.
4485    private ResolveInfo queryCrossProfileIntents(
4486            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4487            int flags, int sourceUserId) {
4488        if (matchingFilters != null) {
4489            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4490            // match the same intent. For performance reasons, it is better not to
4491            // run queryIntent twice for the same userId
4492            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4493            int size = matchingFilters.size();
4494            for (int i = 0; i < size; i++) {
4495                CrossProfileIntentFilter filter = matchingFilters.get(i);
4496                int targetUserId = filter.getTargetUserId();
4497                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4498                        && !alreadyTriedUserIds.get(targetUserId)) {
4499                    // Checking if there are activities in the target user that can handle the
4500                    // intent.
4501                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4502                            flags, sourceUserId);
4503                    if (resolveInfo != null) return resolveInfo;
4504                    alreadyTriedUserIds.put(targetUserId, true);
4505                }
4506            }
4507        }
4508        return null;
4509    }
4510
4511    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4512            String resolvedType, int flags, int sourceUserId) {
4513        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4514                resolvedType, flags, filter.getTargetUserId());
4515        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4516            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4517        }
4518        return null;
4519    }
4520
4521    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4522            int sourceUserId, int targetUserId) {
4523        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4524        String className;
4525        if (targetUserId == UserHandle.USER_OWNER) {
4526            className = FORWARD_INTENT_TO_USER_OWNER;
4527        } else {
4528            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4529        }
4530        ComponentName forwardingActivityComponentName = new ComponentName(
4531                mAndroidApplication.packageName, className);
4532        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4533                sourceUserId);
4534        if (targetUserId == UserHandle.USER_OWNER) {
4535            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4536            forwardingResolveInfo.noResourceId = true;
4537        }
4538        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4539        forwardingResolveInfo.priority = 0;
4540        forwardingResolveInfo.preferredOrder = 0;
4541        forwardingResolveInfo.match = 0;
4542        forwardingResolveInfo.isDefault = true;
4543        forwardingResolveInfo.filter = filter;
4544        forwardingResolveInfo.targetUserId = targetUserId;
4545        return forwardingResolveInfo;
4546    }
4547
4548    @Override
4549    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4550            Intent[] specifics, String[] specificTypes, Intent intent,
4551            String resolvedType, int flags, int userId) {
4552        if (!sUserManager.exists(userId)) return Collections.emptyList();
4553        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4554                false, "query intent activity options");
4555        final String resultsAction = intent.getAction();
4556
4557        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4558                | PackageManager.GET_RESOLVED_FILTER, userId);
4559
4560        if (DEBUG_INTENT_MATCHING) {
4561            Log.v(TAG, "Query " + intent + ": " + results);
4562        }
4563
4564        int specificsPos = 0;
4565        int N;
4566
4567        // todo: note that the algorithm used here is O(N^2).  This
4568        // isn't a problem in our current environment, but if we start running
4569        // into situations where we have more than 5 or 10 matches then this
4570        // should probably be changed to something smarter...
4571
4572        // First we go through and resolve each of the specific items
4573        // that were supplied, taking care of removing any corresponding
4574        // duplicate items in the generic resolve list.
4575        if (specifics != null) {
4576            for (int i=0; i<specifics.length; i++) {
4577                final Intent sintent = specifics[i];
4578                if (sintent == null) {
4579                    continue;
4580                }
4581
4582                if (DEBUG_INTENT_MATCHING) {
4583                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4584                }
4585
4586                String action = sintent.getAction();
4587                if (resultsAction != null && resultsAction.equals(action)) {
4588                    // If this action was explicitly requested, then don't
4589                    // remove things that have it.
4590                    action = null;
4591                }
4592
4593                ResolveInfo ri = null;
4594                ActivityInfo ai = null;
4595
4596                ComponentName comp = sintent.getComponent();
4597                if (comp == null) {
4598                    ri = resolveIntent(
4599                        sintent,
4600                        specificTypes != null ? specificTypes[i] : null,
4601                            flags, userId);
4602                    if (ri == null) {
4603                        continue;
4604                    }
4605                    if (ri == mResolveInfo) {
4606                        // ACK!  Must do something better with this.
4607                    }
4608                    ai = ri.activityInfo;
4609                    comp = new ComponentName(ai.applicationInfo.packageName,
4610                            ai.name);
4611                } else {
4612                    ai = getActivityInfo(comp, flags, userId);
4613                    if (ai == null) {
4614                        continue;
4615                    }
4616                }
4617
4618                // Look for any generic query activities that are duplicates
4619                // of this specific one, and remove them from the results.
4620                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4621                N = results.size();
4622                int j;
4623                for (j=specificsPos; j<N; j++) {
4624                    ResolveInfo sri = results.get(j);
4625                    if ((sri.activityInfo.name.equals(comp.getClassName())
4626                            && sri.activityInfo.applicationInfo.packageName.equals(
4627                                    comp.getPackageName()))
4628                        || (action != null && sri.filter.matchAction(action))) {
4629                        results.remove(j);
4630                        if (DEBUG_INTENT_MATCHING) Log.v(
4631                            TAG, "Removing duplicate item from " + j
4632                            + " due to specific " + specificsPos);
4633                        if (ri == null) {
4634                            ri = sri;
4635                        }
4636                        j--;
4637                        N--;
4638                    }
4639                }
4640
4641                // Add this specific item to its proper place.
4642                if (ri == null) {
4643                    ri = new ResolveInfo();
4644                    ri.activityInfo = ai;
4645                }
4646                results.add(specificsPos, ri);
4647                ri.specificIndex = i;
4648                specificsPos++;
4649            }
4650        }
4651
4652        // Now we go through the remaining generic results and remove any
4653        // duplicate actions that are found here.
4654        N = results.size();
4655        for (int i=specificsPos; i<N-1; i++) {
4656            final ResolveInfo rii = results.get(i);
4657            if (rii.filter == null) {
4658                continue;
4659            }
4660
4661            // Iterate over all of the actions of this result's intent
4662            // filter...  typically this should be just one.
4663            final Iterator<String> it = rii.filter.actionsIterator();
4664            if (it == null) {
4665                continue;
4666            }
4667            while (it.hasNext()) {
4668                final String action = it.next();
4669                if (resultsAction != null && resultsAction.equals(action)) {
4670                    // If this action was explicitly requested, then don't
4671                    // remove things that have it.
4672                    continue;
4673                }
4674                for (int j=i+1; j<N; j++) {
4675                    final ResolveInfo rij = results.get(j);
4676                    if (rij.filter != null && rij.filter.hasAction(action)) {
4677                        results.remove(j);
4678                        if (DEBUG_INTENT_MATCHING) Log.v(
4679                            TAG, "Removing duplicate item from " + j
4680                            + " due to action " + action + " at " + i);
4681                        j--;
4682                        N--;
4683                    }
4684                }
4685            }
4686
4687            // If the caller didn't request filter information, drop it now
4688            // so we don't have to marshall/unmarshall it.
4689            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4690                rii.filter = null;
4691            }
4692        }
4693
4694        // Filter out the caller activity if so requested.
4695        if (caller != null) {
4696            N = results.size();
4697            for (int i=0; i<N; i++) {
4698                ActivityInfo ainfo = results.get(i).activityInfo;
4699                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4700                        && caller.getClassName().equals(ainfo.name)) {
4701                    results.remove(i);
4702                    break;
4703                }
4704            }
4705        }
4706
4707        // If the caller didn't request filter information,
4708        // drop them now so we don't have to
4709        // marshall/unmarshall it.
4710        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4711            N = results.size();
4712            for (int i=0; i<N; i++) {
4713                results.get(i).filter = null;
4714            }
4715        }
4716
4717        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4718        return results;
4719    }
4720
4721    @Override
4722    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4723            int userId) {
4724        if (!sUserManager.exists(userId)) return Collections.emptyList();
4725        ComponentName comp = intent.getComponent();
4726        if (comp == null) {
4727            if (intent.getSelector() != null) {
4728                intent = intent.getSelector();
4729                comp = intent.getComponent();
4730            }
4731        }
4732        if (comp != null) {
4733            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4734            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4735            if (ai != null) {
4736                ResolveInfo ri = new ResolveInfo();
4737                ri.activityInfo = ai;
4738                list.add(ri);
4739            }
4740            return list;
4741        }
4742
4743        // reader
4744        synchronized (mPackages) {
4745            String pkgName = intent.getPackage();
4746            if (pkgName == null) {
4747                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4748            }
4749            final PackageParser.Package pkg = mPackages.get(pkgName);
4750            if (pkg != null) {
4751                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4752                        userId);
4753            }
4754            return null;
4755        }
4756    }
4757
4758    @Override
4759    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4760        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4761        if (!sUserManager.exists(userId)) return null;
4762        if (query != null) {
4763            if (query.size() >= 1) {
4764                // If there is more than one service with the same priority,
4765                // just arbitrarily pick the first one.
4766                return query.get(0);
4767            }
4768        }
4769        return null;
4770    }
4771
4772    @Override
4773    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4774            int userId) {
4775        if (!sUserManager.exists(userId)) return Collections.emptyList();
4776        ComponentName comp = intent.getComponent();
4777        if (comp == null) {
4778            if (intent.getSelector() != null) {
4779                intent = intent.getSelector();
4780                comp = intent.getComponent();
4781            }
4782        }
4783        if (comp != null) {
4784            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4785            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4786            if (si != null) {
4787                final ResolveInfo ri = new ResolveInfo();
4788                ri.serviceInfo = si;
4789                list.add(ri);
4790            }
4791            return list;
4792        }
4793
4794        // reader
4795        synchronized (mPackages) {
4796            String pkgName = intent.getPackage();
4797            if (pkgName == null) {
4798                return mServices.queryIntent(intent, resolvedType, flags, userId);
4799            }
4800            final PackageParser.Package pkg = mPackages.get(pkgName);
4801            if (pkg != null) {
4802                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4803                        userId);
4804            }
4805            return null;
4806        }
4807    }
4808
4809    @Override
4810    public List<ResolveInfo> queryIntentContentProviders(
4811            Intent intent, String resolvedType, int flags, int userId) {
4812        if (!sUserManager.exists(userId)) return Collections.emptyList();
4813        ComponentName comp = intent.getComponent();
4814        if (comp == null) {
4815            if (intent.getSelector() != null) {
4816                intent = intent.getSelector();
4817                comp = intent.getComponent();
4818            }
4819        }
4820        if (comp != null) {
4821            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4822            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4823            if (pi != null) {
4824                final ResolveInfo ri = new ResolveInfo();
4825                ri.providerInfo = pi;
4826                list.add(ri);
4827            }
4828            return list;
4829        }
4830
4831        // reader
4832        synchronized (mPackages) {
4833            String pkgName = intent.getPackage();
4834            if (pkgName == null) {
4835                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4836            }
4837            final PackageParser.Package pkg = mPackages.get(pkgName);
4838            if (pkg != null) {
4839                return mProviders.queryIntentForPackage(
4840                        intent, resolvedType, flags, pkg.providers, userId);
4841            }
4842            return null;
4843        }
4844    }
4845
4846    @Override
4847    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4848        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4849
4850        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4851
4852        // writer
4853        synchronized (mPackages) {
4854            ArrayList<PackageInfo> list;
4855            if (listUninstalled) {
4856                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4857                for (PackageSetting ps : mSettings.mPackages.values()) {
4858                    PackageInfo pi;
4859                    if (ps.pkg != null) {
4860                        pi = generatePackageInfo(ps.pkg, flags, userId);
4861                    } else {
4862                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4863                    }
4864                    if (pi != null) {
4865                        list.add(pi);
4866                    }
4867                }
4868            } else {
4869                list = new ArrayList<PackageInfo>(mPackages.size());
4870                for (PackageParser.Package p : mPackages.values()) {
4871                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4872                    if (pi != null) {
4873                        list.add(pi);
4874                    }
4875                }
4876            }
4877
4878            return new ParceledListSlice<PackageInfo>(list);
4879        }
4880    }
4881
4882    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4883            String[] permissions, boolean[] tmp, int flags, int userId) {
4884        int numMatch = 0;
4885        final PermissionsState permissionsState = ps.getPermissionsState();
4886        for (int i=0; i<permissions.length; i++) {
4887            final String permission = permissions[i];
4888            if (permissionsState.hasPermission(permission, userId)) {
4889                tmp[i] = true;
4890                numMatch++;
4891            } else {
4892                tmp[i] = false;
4893            }
4894        }
4895        if (numMatch == 0) {
4896            return;
4897        }
4898        PackageInfo pi;
4899        if (ps.pkg != null) {
4900            pi = generatePackageInfo(ps.pkg, flags, userId);
4901        } else {
4902            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4903        }
4904        // The above might return null in cases of uninstalled apps or install-state
4905        // skew across users/profiles.
4906        if (pi != null) {
4907            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4908                if (numMatch == permissions.length) {
4909                    pi.requestedPermissions = permissions;
4910                } else {
4911                    pi.requestedPermissions = new String[numMatch];
4912                    numMatch = 0;
4913                    for (int i=0; i<permissions.length; i++) {
4914                        if (tmp[i]) {
4915                            pi.requestedPermissions[numMatch] = permissions[i];
4916                            numMatch++;
4917                        }
4918                    }
4919                }
4920            }
4921            list.add(pi);
4922        }
4923    }
4924
4925    @Override
4926    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4927            String[] permissions, int flags, int userId) {
4928        if (!sUserManager.exists(userId)) return null;
4929        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4930
4931        // writer
4932        synchronized (mPackages) {
4933            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4934            boolean[] tmpBools = new boolean[permissions.length];
4935            if (listUninstalled) {
4936                for (PackageSetting ps : mSettings.mPackages.values()) {
4937                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4938                }
4939            } else {
4940                for (PackageParser.Package pkg : mPackages.values()) {
4941                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4942                    if (ps != null) {
4943                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4944                                userId);
4945                    }
4946                }
4947            }
4948
4949            return new ParceledListSlice<PackageInfo>(list);
4950        }
4951    }
4952
4953    @Override
4954    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4955        if (!sUserManager.exists(userId)) return null;
4956        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4957
4958        // writer
4959        synchronized (mPackages) {
4960            ArrayList<ApplicationInfo> list;
4961            if (listUninstalled) {
4962                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4963                for (PackageSetting ps : mSettings.mPackages.values()) {
4964                    ApplicationInfo ai;
4965                    if (ps.pkg != null) {
4966                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4967                                ps.readUserState(userId), userId);
4968                    } else {
4969                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4970                    }
4971                    if (ai != null) {
4972                        list.add(ai);
4973                    }
4974                }
4975            } else {
4976                list = new ArrayList<ApplicationInfo>(mPackages.size());
4977                for (PackageParser.Package p : mPackages.values()) {
4978                    if (p.mExtras != null) {
4979                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4980                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4981                        if (ai != null) {
4982                            list.add(ai);
4983                        }
4984                    }
4985                }
4986            }
4987
4988            return new ParceledListSlice<ApplicationInfo>(list);
4989        }
4990    }
4991
4992    public List<ApplicationInfo> getPersistentApplications(int flags) {
4993        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4994
4995        // reader
4996        synchronized (mPackages) {
4997            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4998            final int userId = UserHandle.getCallingUserId();
4999            while (i.hasNext()) {
5000                final PackageParser.Package p = i.next();
5001                if (p.applicationInfo != null
5002                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5003                        && (!mSafeMode || isSystemApp(p))) {
5004                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5005                    if (ps != null) {
5006                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5007                                ps.readUserState(userId), userId);
5008                        if (ai != null) {
5009                            finalList.add(ai);
5010                        }
5011                    }
5012                }
5013            }
5014        }
5015
5016        return finalList;
5017    }
5018
5019    @Override
5020    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5021        if (!sUserManager.exists(userId)) return null;
5022        // reader
5023        synchronized (mPackages) {
5024            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5025            PackageSetting ps = provider != null
5026                    ? mSettings.mPackages.get(provider.owner.packageName)
5027                    : null;
5028            return ps != null
5029                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5030                    && (!mSafeMode || (provider.info.applicationInfo.flags
5031                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5032                    ? PackageParser.generateProviderInfo(provider, flags,
5033                            ps.readUserState(userId), userId)
5034                    : null;
5035        }
5036    }
5037
5038    /**
5039     * @deprecated
5040     */
5041    @Deprecated
5042    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5043        // reader
5044        synchronized (mPackages) {
5045            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5046                    .entrySet().iterator();
5047            final int userId = UserHandle.getCallingUserId();
5048            while (i.hasNext()) {
5049                Map.Entry<String, PackageParser.Provider> entry = i.next();
5050                PackageParser.Provider p = entry.getValue();
5051                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5052
5053                if (ps != null && p.syncable
5054                        && (!mSafeMode || (p.info.applicationInfo.flags
5055                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5056                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5057                            ps.readUserState(userId), userId);
5058                    if (info != null) {
5059                        outNames.add(entry.getKey());
5060                        outInfo.add(info);
5061                    }
5062                }
5063            }
5064        }
5065    }
5066
5067    @Override
5068    public List<ProviderInfo> queryContentProviders(String processName,
5069            int uid, int flags) {
5070        ArrayList<ProviderInfo> finalList = null;
5071        // reader
5072        synchronized (mPackages) {
5073            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5074            final int userId = processName != null ?
5075                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5076            while (i.hasNext()) {
5077                final PackageParser.Provider p = i.next();
5078                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5079                if (ps != null && p.info.authority != null
5080                        && (processName == null
5081                                || (p.info.processName.equals(processName)
5082                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5083                        && mSettings.isEnabledLPr(p.info, flags, userId)
5084                        && (!mSafeMode
5085                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5086                    if (finalList == null) {
5087                        finalList = new ArrayList<ProviderInfo>(3);
5088                    }
5089                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5090                            ps.readUserState(userId), userId);
5091                    if (info != null) {
5092                        finalList.add(info);
5093                    }
5094                }
5095            }
5096        }
5097
5098        if (finalList != null) {
5099            Collections.sort(finalList, mProviderInitOrderSorter);
5100        }
5101
5102        return finalList;
5103    }
5104
5105    @Override
5106    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5107            int flags) {
5108        // reader
5109        synchronized (mPackages) {
5110            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5111            return PackageParser.generateInstrumentationInfo(i, flags);
5112        }
5113    }
5114
5115    @Override
5116    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5117            int flags) {
5118        ArrayList<InstrumentationInfo> finalList =
5119            new ArrayList<InstrumentationInfo>();
5120
5121        // reader
5122        synchronized (mPackages) {
5123            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5124            while (i.hasNext()) {
5125                final PackageParser.Instrumentation p = i.next();
5126                if (targetPackage == null
5127                        || targetPackage.equals(p.info.targetPackage)) {
5128                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5129                            flags);
5130                    if (ii != null) {
5131                        finalList.add(ii);
5132                    }
5133                }
5134            }
5135        }
5136
5137        return finalList;
5138    }
5139
5140    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5141        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5142        if (overlays == null) {
5143            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5144            return;
5145        }
5146        for (PackageParser.Package opkg : overlays.values()) {
5147            // Not much to do if idmap fails: we already logged the error
5148            // and we certainly don't want to abort installation of pkg simply
5149            // because an overlay didn't fit properly. For these reasons,
5150            // ignore the return value of createIdmapForPackagePairLI.
5151            createIdmapForPackagePairLI(pkg, opkg);
5152        }
5153    }
5154
5155    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5156            PackageParser.Package opkg) {
5157        if (!opkg.mTrustedOverlay) {
5158            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5159                    opkg.baseCodePath + ": overlay not trusted");
5160            return false;
5161        }
5162        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5163        if (overlaySet == null) {
5164            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5165                    opkg.baseCodePath + " but target package has no known overlays");
5166            return false;
5167        }
5168        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5169        // TODO: generate idmap for split APKs
5170        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5171            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5172                    + opkg.baseCodePath);
5173            return false;
5174        }
5175        PackageParser.Package[] overlayArray =
5176            overlaySet.values().toArray(new PackageParser.Package[0]);
5177        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5178            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5179                return p1.mOverlayPriority - p2.mOverlayPriority;
5180            }
5181        };
5182        Arrays.sort(overlayArray, cmp);
5183
5184        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5185        int i = 0;
5186        for (PackageParser.Package p : overlayArray) {
5187            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5188        }
5189        return true;
5190    }
5191
5192    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5193        final File[] files = dir.listFiles();
5194        if (ArrayUtils.isEmpty(files)) {
5195            Log.d(TAG, "No files in app dir " + dir);
5196            return;
5197        }
5198
5199        if (DEBUG_PACKAGE_SCANNING) {
5200            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5201                    + " flags=0x" + Integer.toHexString(parseFlags));
5202        }
5203
5204        for (File file : files) {
5205            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5206                    && !PackageInstallerService.isStageName(file.getName());
5207            if (!isPackage) {
5208                // Ignore entries which are not packages
5209                continue;
5210            }
5211            try {
5212                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5213                        scanFlags, currentTime, null);
5214            } catch (PackageManagerException e) {
5215                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5216
5217                // Delete invalid userdata apps
5218                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5219                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5220                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5221                    if (file.isDirectory()) {
5222                        mInstaller.rmPackageDir(file.getAbsolutePath());
5223                    } else {
5224                        file.delete();
5225                    }
5226                }
5227            }
5228        }
5229    }
5230
5231    private static File getSettingsProblemFile() {
5232        File dataDir = Environment.getDataDirectory();
5233        File systemDir = new File(dataDir, "system");
5234        File fname = new File(systemDir, "uiderrors.txt");
5235        return fname;
5236    }
5237
5238    static void reportSettingsProblem(int priority, String msg) {
5239        logCriticalInfo(priority, msg);
5240    }
5241
5242    static void logCriticalInfo(int priority, String msg) {
5243        Slog.println(priority, TAG, msg);
5244        EventLogTags.writePmCriticalInfo(msg);
5245        try {
5246            File fname = getSettingsProblemFile();
5247            FileOutputStream out = new FileOutputStream(fname, true);
5248            PrintWriter pw = new FastPrintWriter(out);
5249            SimpleDateFormat formatter = new SimpleDateFormat();
5250            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5251            pw.println(dateString + ": " + msg);
5252            pw.close();
5253            FileUtils.setPermissions(
5254                    fname.toString(),
5255                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5256                    -1, -1);
5257        } catch (java.io.IOException e) {
5258        }
5259    }
5260
5261    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5262            PackageParser.Package pkg, File srcFile, int parseFlags)
5263            throws PackageManagerException {
5264        if (ps != null
5265                && ps.codePath.equals(srcFile)
5266                && ps.timeStamp == srcFile.lastModified()
5267                && !isCompatSignatureUpdateNeeded(pkg)
5268                && !isRecoverSignatureUpdateNeeded(pkg)) {
5269            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5270            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5271            ArraySet<PublicKey> signingKs;
5272            synchronized (mPackages) {
5273                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5274            }
5275            if (ps.signatures.mSignatures != null
5276                    && ps.signatures.mSignatures.length != 0
5277                    && signingKs != null) {
5278                // Optimization: reuse the existing cached certificates
5279                // if the package appears to be unchanged.
5280                pkg.mSignatures = ps.signatures.mSignatures;
5281                pkg.mSigningKeys = signingKs;
5282                return;
5283            }
5284
5285            Slog.w(TAG, "PackageSetting for " + ps.name
5286                    + " is missing signatures.  Collecting certs again to recover them.");
5287        } else {
5288            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5289        }
5290
5291        try {
5292            pp.collectCertificates(pkg, parseFlags);
5293            pp.collectManifestDigest(pkg);
5294        } catch (PackageParserException e) {
5295            throw PackageManagerException.from(e);
5296        }
5297    }
5298
5299    /*
5300     *  Scan a package and return the newly parsed package.
5301     *  Returns null in case of errors and the error code is stored in mLastScanError
5302     */
5303    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5304            long currentTime, UserHandle user) throws PackageManagerException {
5305        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5306        parseFlags |= mDefParseFlags;
5307        PackageParser pp = new PackageParser();
5308        pp.setSeparateProcesses(mSeparateProcesses);
5309        pp.setOnlyCoreApps(mOnlyCore);
5310        pp.setDisplayMetrics(mMetrics);
5311
5312        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5313            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5314        }
5315
5316        final PackageParser.Package pkg;
5317        try {
5318            pkg = pp.parsePackage(scanFile, parseFlags);
5319        } catch (PackageParserException e) {
5320            throw PackageManagerException.from(e);
5321        }
5322
5323        PackageSetting ps = null;
5324        PackageSetting updatedPkg;
5325        // reader
5326        synchronized (mPackages) {
5327            // Look to see if we already know about this package.
5328            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5329            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5330                // This package has been renamed to its original name.  Let's
5331                // use that.
5332                ps = mSettings.peekPackageLPr(oldName);
5333            }
5334            // If there was no original package, see one for the real package name.
5335            if (ps == null) {
5336                ps = mSettings.peekPackageLPr(pkg.packageName);
5337            }
5338            // Check to see if this package could be hiding/updating a system
5339            // package.  Must look for it either under the original or real
5340            // package name depending on our state.
5341            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5342            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5343        }
5344        boolean updatedPkgBetter = false;
5345        // First check if this is a system package that may involve an update
5346        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5347            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5348            // it needs to drop FLAG_PRIVILEGED.
5349            if (locationIsPrivileged(scanFile)) {
5350                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5351            } else {
5352                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5353            }
5354
5355            if (ps != null && !ps.codePath.equals(scanFile)) {
5356                // The path has changed from what was last scanned...  check the
5357                // version of the new path against what we have stored to determine
5358                // what to do.
5359                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5360                if (pkg.mVersionCode <= ps.versionCode) {
5361                    // The system package has been updated and the code path does not match
5362                    // Ignore entry. Skip it.
5363                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5364                            + " ignored: updated version " + ps.versionCode
5365                            + " better than this " + pkg.mVersionCode);
5366                    if (!updatedPkg.codePath.equals(scanFile)) {
5367                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5368                                + ps.name + " changing from " + updatedPkg.codePathString
5369                                + " to " + scanFile);
5370                        updatedPkg.codePath = scanFile;
5371                        updatedPkg.codePathString = scanFile.toString();
5372                        updatedPkg.resourcePath = scanFile;
5373                        updatedPkg.resourcePathString = scanFile.toString();
5374                    }
5375                    updatedPkg.pkg = pkg;
5376                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5377                } else {
5378                    // The current app on the system partition is better than
5379                    // what we have updated to on the data partition; switch
5380                    // back to the system partition version.
5381                    // At this point, its safely assumed that package installation for
5382                    // apps in system partition will go through. If not there won't be a working
5383                    // version of the app
5384                    // writer
5385                    synchronized (mPackages) {
5386                        // Just remove the loaded entries from package lists.
5387                        mPackages.remove(ps.name);
5388                    }
5389
5390                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5391                            + " reverting from " + ps.codePathString
5392                            + ": new version " + pkg.mVersionCode
5393                            + " better than installed " + ps.versionCode);
5394
5395                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5396                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5397                    synchronized (mInstallLock) {
5398                        args.cleanUpResourcesLI();
5399                    }
5400                    synchronized (mPackages) {
5401                        mSettings.enableSystemPackageLPw(ps.name);
5402                    }
5403                    updatedPkgBetter = true;
5404                }
5405            }
5406        }
5407
5408        if (updatedPkg != null) {
5409            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5410            // initially
5411            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5412
5413            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5414            // flag set initially
5415            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5416                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5417            }
5418        }
5419
5420        // Verify certificates against what was last scanned
5421        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5422
5423        /*
5424         * A new system app appeared, but we already had a non-system one of the
5425         * same name installed earlier.
5426         */
5427        boolean shouldHideSystemApp = false;
5428        if (updatedPkg == null && ps != null
5429                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5430            /*
5431             * Check to make sure the signatures match first. If they don't,
5432             * wipe the installed application and its data.
5433             */
5434            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5435                    != PackageManager.SIGNATURE_MATCH) {
5436                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5437                        + " signatures don't match existing userdata copy; removing");
5438                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5439                ps = null;
5440            } else {
5441                /*
5442                 * If the newly-added system app is an older version than the
5443                 * already installed version, hide it. It will be scanned later
5444                 * and re-added like an update.
5445                 */
5446                if (pkg.mVersionCode <= ps.versionCode) {
5447                    shouldHideSystemApp = true;
5448                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5449                            + " but new version " + pkg.mVersionCode + " better than installed "
5450                            + ps.versionCode + "; hiding system");
5451                } else {
5452                    /*
5453                     * The newly found system app is a newer version that the
5454                     * one previously installed. Simply remove the
5455                     * already-installed application and replace it with our own
5456                     * while keeping the application data.
5457                     */
5458                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5459                            + " reverting from " + ps.codePathString + ": new version "
5460                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5461                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5462                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5463                    synchronized (mInstallLock) {
5464                        args.cleanUpResourcesLI();
5465                    }
5466                }
5467            }
5468        }
5469
5470        // The apk is forward locked (not public) if its code and resources
5471        // are kept in different files. (except for app in either system or
5472        // vendor path).
5473        // TODO grab this value from PackageSettings
5474        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5475            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5476                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5477            }
5478        }
5479
5480        // TODO: extend to support forward-locked splits
5481        String resourcePath = null;
5482        String baseResourcePath = null;
5483        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5484            if (ps != null && ps.resourcePathString != null) {
5485                resourcePath = ps.resourcePathString;
5486                baseResourcePath = ps.resourcePathString;
5487            } else {
5488                // Should not happen at all. Just log an error.
5489                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5490            }
5491        } else {
5492            resourcePath = pkg.codePath;
5493            baseResourcePath = pkg.baseCodePath;
5494        }
5495
5496        // Set application objects path explicitly.
5497        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5498        pkg.applicationInfo.setCodePath(pkg.codePath);
5499        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5500        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5501        pkg.applicationInfo.setResourcePath(resourcePath);
5502        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5503        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5504
5505        // Note that we invoke the following method only if we are about to unpack an application
5506        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5507                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5508
5509        /*
5510         * If the system app should be overridden by a previously installed
5511         * data, hide the system app now and let the /data/app scan pick it up
5512         * again.
5513         */
5514        if (shouldHideSystemApp) {
5515            synchronized (mPackages) {
5516                /*
5517                 * We have to grant systems permissions before we hide, because
5518                 * grantPermissions will assume the package update is trying to
5519                 * expand its permissions.
5520                 */
5521                grantPermissionsLPw(pkg, true, pkg.packageName);
5522                mSettings.disableSystemPackageLPw(pkg.packageName);
5523            }
5524        }
5525
5526        return scannedPkg;
5527    }
5528
5529    private static String fixProcessName(String defProcessName,
5530            String processName, int uid) {
5531        if (processName == null) {
5532            return defProcessName;
5533        }
5534        return processName;
5535    }
5536
5537    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5538            throws PackageManagerException {
5539        if (pkgSetting.signatures.mSignatures != null) {
5540            // Already existing package. Make sure signatures match
5541            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5542                    == PackageManager.SIGNATURE_MATCH;
5543            if (!match) {
5544                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5545                        == PackageManager.SIGNATURE_MATCH;
5546            }
5547            if (!match) {
5548                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5549                        == PackageManager.SIGNATURE_MATCH;
5550            }
5551            if (!match) {
5552                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5553                        + pkg.packageName + " signatures do not match the "
5554                        + "previously installed version; ignoring!");
5555            }
5556        }
5557
5558        // Check for shared user signatures
5559        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5560            // Already existing package. Make sure signatures match
5561            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5562                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5563            if (!match) {
5564                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5565                        == PackageManager.SIGNATURE_MATCH;
5566            }
5567            if (!match) {
5568                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5569                        == PackageManager.SIGNATURE_MATCH;
5570            }
5571            if (!match) {
5572                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5573                        "Package " + pkg.packageName
5574                        + " has no signatures that match those in shared user "
5575                        + pkgSetting.sharedUser.name + "; ignoring!");
5576            }
5577        }
5578    }
5579
5580    /**
5581     * Enforces that only the system UID or root's UID can call a method exposed
5582     * via Binder.
5583     *
5584     * @param message used as message if SecurityException is thrown
5585     * @throws SecurityException if the caller is not system or root
5586     */
5587    private static final void enforceSystemOrRoot(String message) {
5588        final int uid = Binder.getCallingUid();
5589        if (uid != Process.SYSTEM_UID && uid != 0) {
5590            throw new SecurityException(message);
5591        }
5592    }
5593
5594    @Override
5595    public void performBootDexOpt() {
5596        enforceSystemOrRoot("Only the system can request dexopt be performed");
5597
5598        // Before everything else, see whether we need to fstrim.
5599        try {
5600            IMountService ms = PackageHelper.getMountService();
5601            if (ms != null) {
5602                final boolean isUpgrade = isUpgrade();
5603                boolean doTrim = isUpgrade;
5604                if (doTrim) {
5605                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5606                } else {
5607                    final long interval = android.provider.Settings.Global.getLong(
5608                            mContext.getContentResolver(),
5609                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5610                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5611                    if (interval > 0) {
5612                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5613                        if (timeSinceLast > interval) {
5614                            doTrim = true;
5615                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5616                                    + "; running immediately");
5617                        }
5618                    }
5619                }
5620                if (doTrim) {
5621                    if (!isFirstBoot()) {
5622                        try {
5623                            ActivityManagerNative.getDefault().showBootMessage(
5624                                    mContext.getResources().getString(
5625                                            R.string.android_upgrading_fstrim), true);
5626                        } catch (RemoteException e) {
5627                        }
5628                    }
5629                    ms.runMaintenance();
5630                }
5631            } else {
5632                Slog.e(TAG, "Mount service unavailable!");
5633            }
5634        } catch (RemoteException e) {
5635            // Can't happen; MountService is local
5636        }
5637
5638        final ArraySet<PackageParser.Package> pkgs;
5639        synchronized (mPackages) {
5640            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5641        }
5642
5643        if (pkgs != null) {
5644            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5645            // in case the device runs out of space.
5646            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5647            // Give priority to core apps.
5648            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5649                PackageParser.Package pkg = it.next();
5650                if (pkg.coreApp) {
5651                    if (DEBUG_DEXOPT) {
5652                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5653                    }
5654                    sortedPkgs.add(pkg);
5655                    it.remove();
5656                }
5657            }
5658            // Give priority to system apps that listen for pre boot complete.
5659            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5660            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5661            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5662                PackageParser.Package pkg = it.next();
5663                if (pkgNames.contains(pkg.packageName)) {
5664                    if (DEBUG_DEXOPT) {
5665                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5666                    }
5667                    sortedPkgs.add(pkg);
5668                    it.remove();
5669                }
5670            }
5671            // Give priority to system apps.
5672            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5673                PackageParser.Package pkg = it.next();
5674                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5675                    if (DEBUG_DEXOPT) {
5676                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5677                    }
5678                    sortedPkgs.add(pkg);
5679                    it.remove();
5680                }
5681            }
5682            // Give priority to updated system apps.
5683            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5684                PackageParser.Package pkg = it.next();
5685                if (pkg.isUpdatedSystemApp()) {
5686                    if (DEBUG_DEXOPT) {
5687                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5688                    }
5689                    sortedPkgs.add(pkg);
5690                    it.remove();
5691                }
5692            }
5693            // Give priority to apps that listen for boot complete.
5694            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5695            pkgNames = getPackageNamesForIntent(intent);
5696            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5697                PackageParser.Package pkg = it.next();
5698                if (pkgNames.contains(pkg.packageName)) {
5699                    if (DEBUG_DEXOPT) {
5700                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5701                    }
5702                    sortedPkgs.add(pkg);
5703                    it.remove();
5704                }
5705            }
5706            // Filter out packages that aren't recently used.
5707            filterRecentlyUsedApps(pkgs);
5708            // Add all remaining apps.
5709            for (PackageParser.Package pkg : pkgs) {
5710                if (DEBUG_DEXOPT) {
5711                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5712                }
5713                sortedPkgs.add(pkg);
5714            }
5715
5716            // If we want to be lazy, filter everything that wasn't recently used.
5717            if (mLazyDexOpt) {
5718                filterRecentlyUsedApps(sortedPkgs);
5719            }
5720
5721            int i = 0;
5722            int total = sortedPkgs.size();
5723            File dataDir = Environment.getDataDirectory();
5724            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5725            if (lowThreshold == 0) {
5726                throw new IllegalStateException("Invalid low memory threshold");
5727            }
5728            for (PackageParser.Package pkg : sortedPkgs) {
5729                long usableSpace = dataDir.getUsableSpace();
5730                if (usableSpace < lowThreshold) {
5731                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5732                    break;
5733                }
5734                performBootDexOpt(pkg, ++i, total);
5735            }
5736        }
5737    }
5738
5739    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5740        // Filter out packages that aren't recently used.
5741        //
5742        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5743        // should do a full dexopt.
5744        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5745            int total = pkgs.size();
5746            int skipped = 0;
5747            long now = System.currentTimeMillis();
5748            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5749                PackageParser.Package pkg = i.next();
5750                long then = pkg.mLastPackageUsageTimeInMills;
5751                if (then + mDexOptLRUThresholdInMills < now) {
5752                    if (DEBUG_DEXOPT) {
5753                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5754                              ((then == 0) ? "never" : new Date(then)));
5755                    }
5756                    i.remove();
5757                    skipped++;
5758                }
5759            }
5760            if (DEBUG_DEXOPT) {
5761                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5762            }
5763        }
5764    }
5765
5766    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5767        List<ResolveInfo> ris = null;
5768        try {
5769            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5770                    intent, null, 0, UserHandle.USER_OWNER);
5771        } catch (RemoteException e) {
5772        }
5773        ArraySet<String> pkgNames = new ArraySet<String>();
5774        if (ris != null) {
5775            for (ResolveInfo ri : ris) {
5776                pkgNames.add(ri.activityInfo.packageName);
5777            }
5778        }
5779        return pkgNames;
5780    }
5781
5782    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5783        if (DEBUG_DEXOPT) {
5784            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5785        }
5786        if (!isFirstBoot()) {
5787            try {
5788                ActivityManagerNative.getDefault().showBootMessage(
5789                        mContext.getResources().getString(R.string.android_upgrading_apk,
5790                                curr, total), true);
5791            } catch (RemoteException e) {
5792            }
5793        }
5794        PackageParser.Package p = pkg;
5795        synchronized (mInstallLock) {
5796            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5797                    false /* force dex */, false /* defer */, true /* include dependencies */);
5798        }
5799    }
5800
5801    @Override
5802    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5803        return performDexOpt(packageName, instructionSet, false);
5804    }
5805
5806    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5807        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5808        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5809        if (!dexopt && !updateUsage) {
5810            // We aren't going to dexopt or update usage, so bail early.
5811            return false;
5812        }
5813        PackageParser.Package p;
5814        final String targetInstructionSet;
5815        synchronized (mPackages) {
5816            p = mPackages.get(packageName);
5817            if (p == null) {
5818                return false;
5819            }
5820            if (updateUsage) {
5821                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5822            }
5823            mPackageUsage.write(false);
5824            if (!dexopt) {
5825                // We aren't going to dexopt, so bail early.
5826                return false;
5827            }
5828
5829            targetInstructionSet = instructionSet != null ? instructionSet :
5830                    getPrimaryInstructionSet(p.applicationInfo);
5831            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5832                return false;
5833            }
5834        }
5835
5836        synchronized (mInstallLock) {
5837            final String[] instructionSets = new String[] { targetInstructionSet };
5838            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5839                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5840            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5841        }
5842    }
5843
5844    public ArraySet<String> getPackagesThatNeedDexOpt() {
5845        ArraySet<String> pkgs = null;
5846        synchronized (mPackages) {
5847            for (PackageParser.Package p : mPackages.values()) {
5848                if (DEBUG_DEXOPT) {
5849                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5850                }
5851                if (!p.mDexOptPerformed.isEmpty()) {
5852                    continue;
5853                }
5854                if (pkgs == null) {
5855                    pkgs = new ArraySet<String>();
5856                }
5857                pkgs.add(p.packageName);
5858            }
5859        }
5860        return pkgs;
5861    }
5862
5863    public void shutdown() {
5864        mPackageUsage.write(true);
5865    }
5866
5867    @Override
5868    public void forceDexOpt(String packageName) {
5869        enforceSystemOrRoot("forceDexOpt");
5870
5871        PackageParser.Package pkg;
5872        synchronized (mPackages) {
5873            pkg = mPackages.get(packageName);
5874            if (pkg == null) {
5875                throw new IllegalArgumentException("Missing package: " + packageName);
5876            }
5877        }
5878
5879        synchronized (mInstallLock) {
5880            final String[] instructionSets = new String[] {
5881                    getPrimaryInstructionSet(pkg.applicationInfo) };
5882            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5883                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5884            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5885                throw new IllegalStateException("Failed to dexopt: " + res);
5886            }
5887        }
5888    }
5889
5890    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5891        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5892            Slog.w(TAG, "Unable to update from " + oldPkg.name
5893                    + " to " + newPkg.packageName
5894                    + ": old package not in system partition");
5895            return false;
5896        } else if (mPackages.get(oldPkg.name) != null) {
5897            Slog.w(TAG, "Unable to update from " + oldPkg.name
5898                    + " to " + newPkg.packageName
5899                    + ": old package still exists");
5900            return false;
5901        }
5902        return true;
5903    }
5904
5905    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
5906        int[] users = sUserManager.getUserIds();
5907        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
5908        if (res < 0) {
5909            return res;
5910        }
5911        for (int user : users) {
5912            if (user != 0) {
5913                res = mInstaller.createUserData(volumeUuid, packageName,
5914                        UserHandle.getUid(user, uid), user, seinfo);
5915                if (res < 0) {
5916                    return res;
5917                }
5918            }
5919        }
5920        return res;
5921    }
5922
5923    private int removeDataDirsLI(String volumeUuid, String packageName) {
5924        int[] users = sUserManager.getUserIds();
5925        int res = 0;
5926        for (int user : users) {
5927            int resInner = mInstaller.remove(volumeUuid, packageName, user);
5928            if (resInner < 0) {
5929                res = resInner;
5930            }
5931        }
5932
5933        return res;
5934    }
5935
5936    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
5937        int[] users = sUserManager.getUserIds();
5938        int res = 0;
5939        for (int user : users) {
5940            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
5941            if (resInner < 0) {
5942                res = resInner;
5943            }
5944        }
5945        return res;
5946    }
5947
5948    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5949            PackageParser.Package changingLib) {
5950        if (file.path != null) {
5951            usesLibraryFiles.add(file.path);
5952            return;
5953        }
5954        PackageParser.Package p = mPackages.get(file.apk);
5955        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5956            // If we are doing this while in the middle of updating a library apk,
5957            // then we need to make sure to use that new apk for determining the
5958            // dependencies here.  (We haven't yet finished committing the new apk
5959            // to the package manager state.)
5960            if (p == null || p.packageName.equals(changingLib.packageName)) {
5961                p = changingLib;
5962            }
5963        }
5964        if (p != null) {
5965            usesLibraryFiles.addAll(p.getAllCodePaths());
5966        }
5967    }
5968
5969    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5970            PackageParser.Package changingLib) throws PackageManagerException {
5971        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5972            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5973            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5974            for (int i=0; i<N; i++) {
5975                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5976                if (file == null) {
5977                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5978                            "Package " + pkg.packageName + " requires unavailable shared library "
5979                            + pkg.usesLibraries.get(i) + "; failing!");
5980                }
5981                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5982            }
5983            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5984            for (int i=0; i<N; i++) {
5985                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5986                if (file == null) {
5987                    Slog.w(TAG, "Package " + pkg.packageName
5988                            + " desires unavailable shared library "
5989                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5990                } else {
5991                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5992                }
5993            }
5994            N = usesLibraryFiles.size();
5995            if (N > 0) {
5996                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5997            } else {
5998                pkg.usesLibraryFiles = null;
5999            }
6000        }
6001    }
6002
6003    private static boolean hasString(List<String> list, List<String> which) {
6004        if (list == null) {
6005            return false;
6006        }
6007        for (int i=list.size()-1; i>=0; i--) {
6008            for (int j=which.size()-1; j>=0; j--) {
6009                if (which.get(j).equals(list.get(i))) {
6010                    return true;
6011                }
6012            }
6013        }
6014        return false;
6015    }
6016
6017    private void updateAllSharedLibrariesLPw() {
6018        for (PackageParser.Package pkg : mPackages.values()) {
6019            try {
6020                updateSharedLibrariesLPw(pkg, null);
6021            } catch (PackageManagerException e) {
6022                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6023            }
6024        }
6025    }
6026
6027    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6028            PackageParser.Package changingPkg) {
6029        ArrayList<PackageParser.Package> res = null;
6030        for (PackageParser.Package pkg : mPackages.values()) {
6031            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6032                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6033                if (res == null) {
6034                    res = new ArrayList<PackageParser.Package>();
6035                }
6036                res.add(pkg);
6037                try {
6038                    updateSharedLibrariesLPw(pkg, changingPkg);
6039                } catch (PackageManagerException e) {
6040                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6041                }
6042            }
6043        }
6044        return res;
6045    }
6046
6047    /**
6048     * Derive the value of the {@code cpuAbiOverride} based on the provided
6049     * value and an optional stored value from the package settings.
6050     */
6051    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6052        String cpuAbiOverride = null;
6053
6054        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6055            cpuAbiOverride = null;
6056        } else if (abiOverride != null) {
6057            cpuAbiOverride = abiOverride;
6058        } else if (settings != null) {
6059            cpuAbiOverride = settings.cpuAbiOverrideString;
6060        }
6061
6062        return cpuAbiOverride;
6063    }
6064
6065    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6066            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6067        boolean success = false;
6068        try {
6069            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6070                    currentTime, user);
6071            success = true;
6072            return res;
6073        } finally {
6074            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6075                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6076            }
6077        }
6078    }
6079
6080    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6081            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6082        final File scanFile = new File(pkg.codePath);
6083        if (pkg.applicationInfo.getCodePath() == null ||
6084                pkg.applicationInfo.getResourcePath() == null) {
6085            // Bail out. The resource and code paths haven't been set.
6086            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6087                    "Code and resource paths haven't been set correctly");
6088        }
6089
6090        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6091            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6092        } else {
6093            // Only allow system apps to be flagged as core apps.
6094            pkg.coreApp = false;
6095        }
6096
6097        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6098            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6099        }
6100
6101        if (mCustomResolverComponentName != null &&
6102                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6103            setUpCustomResolverActivity(pkg);
6104        }
6105
6106        if (pkg.packageName.equals("android")) {
6107            synchronized (mPackages) {
6108                if (mAndroidApplication != null) {
6109                    Slog.w(TAG, "*************************************************");
6110                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6111                    Slog.w(TAG, " file=" + scanFile);
6112                    Slog.w(TAG, "*************************************************");
6113                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6114                            "Core android package being redefined.  Skipping.");
6115                }
6116
6117                // Set up information for our fall-back user intent resolution activity.
6118                mPlatformPackage = pkg;
6119                pkg.mVersionCode = mSdkVersion;
6120                mAndroidApplication = pkg.applicationInfo;
6121
6122                if (!mResolverReplaced) {
6123                    mResolveActivity.applicationInfo = mAndroidApplication;
6124                    mResolveActivity.name = ResolverActivity.class.getName();
6125                    mResolveActivity.packageName = mAndroidApplication.packageName;
6126                    mResolveActivity.processName = "system:ui";
6127                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6128                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6129                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6130                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6131                    mResolveActivity.exported = true;
6132                    mResolveActivity.enabled = true;
6133                    mResolveInfo.activityInfo = mResolveActivity;
6134                    mResolveInfo.priority = 0;
6135                    mResolveInfo.preferredOrder = 0;
6136                    mResolveInfo.match = 0;
6137                    mResolveComponentName = new ComponentName(
6138                            mAndroidApplication.packageName, mResolveActivity.name);
6139                }
6140            }
6141        }
6142
6143        if (DEBUG_PACKAGE_SCANNING) {
6144            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6145                Log.d(TAG, "Scanning package " + pkg.packageName);
6146        }
6147
6148        if (mPackages.containsKey(pkg.packageName)
6149                || mSharedLibraries.containsKey(pkg.packageName)) {
6150            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6151                    "Application package " + pkg.packageName
6152                    + " already installed.  Skipping duplicate.");
6153        }
6154
6155        // If we're only installing presumed-existing packages, require that the
6156        // scanned APK is both already known and at the path previously established
6157        // for it.  Previously unknown packages we pick up normally, but if we have an
6158        // a priori expectation about this package's install presence, enforce it.
6159        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6160            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6161            if (known != null) {
6162                if (DEBUG_PACKAGE_SCANNING) {
6163                    Log.d(TAG, "Examining " + pkg.codePath
6164                            + " and requiring known paths " + known.codePathString
6165                            + " & " + known.resourcePathString);
6166                }
6167                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6168                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6169                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6170                            "Application package " + pkg.packageName
6171                            + " found at " + pkg.applicationInfo.getCodePath()
6172                            + " but expected at " + known.codePathString + "; ignoring.");
6173                }
6174            }
6175        }
6176
6177        // Initialize package source and resource directories
6178        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6179        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6180
6181        SharedUserSetting suid = null;
6182        PackageSetting pkgSetting = null;
6183
6184        if (!isSystemApp(pkg)) {
6185            // Only system apps can use these features.
6186            pkg.mOriginalPackages = null;
6187            pkg.mRealPackage = null;
6188            pkg.mAdoptPermissions = null;
6189        }
6190
6191        // writer
6192        synchronized (mPackages) {
6193            if (pkg.mSharedUserId != null) {
6194                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6195                if (suid == null) {
6196                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6197                            "Creating application package " + pkg.packageName
6198                            + " for shared user failed");
6199                }
6200                if (DEBUG_PACKAGE_SCANNING) {
6201                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6202                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6203                                + "): packages=" + suid.packages);
6204                }
6205            }
6206
6207            // Check if we are renaming from an original package name.
6208            PackageSetting origPackage = null;
6209            String realName = null;
6210            if (pkg.mOriginalPackages != null) {
6211                // This package may need to be renamed to a previously
6212                // installed name.  Let's check on that...
6213                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6214                if (pkg.mOriginalPackages.contains(renamed)) {
6215                    // This package had originally been installed as the
6216                    // original name, and we have already taken care of
6217                    // transitioning to the new one.  Just update the new
6218                    // one to continue using the old name.
6219                    realName = pkg.mRealPackage;
6220                    if (!pkg.packageName.equals(renamed)) {
6221                        // Callers into this function may have already taken
6222                        // care of renaming the package; only do it here if
6223                        // it is not already done.
6224                        pkg.setPackageName(renamed);
6225                    }
6226
6227                } else {
6228                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6229                        if ((origPackage = mSettings.peekPackageLPr(
6230                                pkg.mOriginalPackages.get(i))) != null) {
6231                            // We do have the package already installed under its
6232                            // original name...  should we use it?
6233                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6234                                // New package is not compatible with original.
6235                                origPackage = null;
6236                                continue;
6237                            } else if (origPackage.sharedUser != null) {
6238                                // Make sure uid is compatible between packages.
6239                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6240                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6241                                            + " to " + pkg.packageName + ": old uid "
6242                                            + origPackage.sharedUser.name
6243                                            + " differs from " + pkg.mSharedUserId);
6244                                    origPackage = null;
6245                                    continue;
6246                                }
6247                            } else {
6248                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6249                                        + pkg.packageName + " to old name " + origPackage.name);
6250                            }
6251                            break;
6252                        }
6253                    }
6254                }
6255            }
6256
6257            if (mTransferedPackages.contains(pkg.packageName)) {
6258                Slog.w(TAG, "Package " + pkg.packageName
6259                        + " was transferred to another, but its .apk remains");
6260            }
6261
6262            // Just create the setting, don't add it yet. For already existing packages
6263            // the PkgSetting exists already and doesn't have to be created.
6264            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6265                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6266                    pkg.applicationInfo.primaryCpuAbi,
6267                    pkg.applicationInfo.secondaryCpuAbi,
6268                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6269                    user, false);
6270            if (pkgSetting == null) {
6271                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6272                        "Creating application package " + pkg.packageName + " failed");
6273            }
6274
6275            if (pkgSetting.origPackage != null) {
6276                // If we are first transitioning from an original package,
6277                // fix up the new package's name now.  We need to do this after
6278                // looking up the package under its new name, so getPackageLP
6279                // can take care of fiddling things correctly.
6280                pkg.setPackageName(origPackage.name);
6281
6282                // File a report about this.
6283                String msg = "New package " + pkgSetting.realName
6284                        + " renamed to replace old package " + pkgSetting.name;
6285                reportSettingsProblem(Log.WARN, msg);
6286
6287                // Make a note of it.
6288                mTransferedPackages.add(origPackage.name);
6289
6290                // No longer need to retain this.
6291                pkgSetting.origPackage = null;
6292            }
6293
6294            if (realName != null) {
6295                // Make a note of it.
6296                mTransferedPackages.add(pkg.packageName);
6297            }
6298
6299            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6300                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6301            }
6302
6303            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6304                // Check all shared libraries and map to their actual file path.
6305                // We only do this here for apps not on a system dir, because those
6306                // are the only ones that can fail an install due to this.  We
6307                // will take care of the system apps by updating all of their
6308                // library paths after the scan is done.
6309                updateSharedLibrariesLPw(pkg, null);
6310            }
6311
6312            if (mFoundPolicyFile) {
6313                SELinuxMMAC.assignSeinfoValue(pkg);
6314            }
6315
6316            pkg.applicationInfo.uid = pkgSetting.appId;
6317            pkg.mExtras = pkgSetting;
6318            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6319                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6320                    // We just determined the app is signed correctly, so bring
6321                    // over the latest parsed certs.
6322                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6323                } else {
6324                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6325                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6326                                "Package " + pkg.packageName + " upgrade keys do not match the "
6327                                + "previously installed version");
6328                    } else {
6329                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6330                        String msg = "System package " + pkg.packageName
6331                            + " signature changed; retaining data.";
6332                        reportSettingsProblem(Log.WARN, msg);
6333                    }
6334                }
6335            } else {
6336                try {
6337                    verifySignaturesLP(pkgSetting, pkg);
6338                    // We just determined the app is signed correctly, so bring
6339                    // over the latest parsed certs.
6340                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6341                } catch (PackageManagerException e) {
6342                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6343                        throw e;
6344                    }
6345                    // The signature has changed, but this package is in the system
6346                    // image...  let's recover!
6347                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6348                    // However...  if this package is part of a shared user, but it
6349                    // doesn't match the signature of the shared user, let's fail.
6350                    // What this means is that you can't change the signatures
6351                    // associated with an overall shared user, which doesn't seem all
6352                    // that unreasonable.
6353                    if (pkgSetting.sharedUser != null) {
6354                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6355                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6356                            throw new PackageManagerException(
6357                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6358                                            "Signature mismatch for shared user : "
6359                                            + pkgSetting.sharedUser);
6360                        }
6361                    }
6362                    // File a report about this.
6363                    String msg = "System package " + pkg.packageName
6364                        + " signature changed; retaining data.";
6365                    reportSettingsProblem(Log.WARN, msg);
6366                }
6367            }
6368            // Verify that this new package doesn't have any content providers
6369            // that conflict with existing packages.  Only do this if the
6370            // package isn't already installed, since we don't want to break
6371            // things that are installed.
6372            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6373                final int N = pkg.providers.size();
6374                int i;
6375                for (i=0; i<N; i++) {
6376                    PackageParser.Provider p = pkg.providers.get(i);
6377                    if (p.info.authority != null) {
6378                        String names[] = p.info.authority.split(";");
6379                        for (int j = 0; j < names.length; j++) {
6380                            if (mProvidersByAuthority.containsKey(names[j])) {
6381                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6382                                final String otherPackageName =
6383                                        ((other != null && other.getComponentName() != null) ?
6384                                                other.getComponentName().getPackageName() : "?");
6385                                throw new PackageManagerException(
6386                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6387                                                "Can't install because provider name " + names[j]
6388                                                + " (in package " + pkg.applicationInfo.packageName
6389                                                + ") is already used by " + otherPackageName);
6390                            }
6391                        }
6392                    }
6393                }
6394            }
6395
6396            if (pkg.mAdoptPermissions != null) {
6397                // This package wants to adopt ownership of permissions from
6398                // another package.
6399                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6400                    final String origName = pkg.mAdoptPermissions.get(i);
6401                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6402                    if (orig != null) {
6403                        if (verifyPackageUpdateLPr(orig, pkg)) {
6404                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6405                                    + pkg.packageName);
6406                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6407                        }
6408                    }
6409                }
6410            }
6411        }
6412
6413        final String pkgName = pkg.packageName;
6414
6415        final long scanFileTime = scanFile.lastModified();
6416        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6417        pkg.applicationInfo.processName = fixProcessName(
6418                pkg.applicationInfo.packageName,
6419                pkg.applicationInfo.processName,
6420                pkg.applicationInfo.uid);
6421
6422        File dataPath;
6423        if (mPlatformPackage == pkg) {
6424            // The system package is special.
6425            dataPath = new File(Environment.getDataDirectory(), "system");
6426
6427            pkg.applicationInfo.dataDir = dataPath.getPath();
6428
6429        } else {
6430            // This is a normal package, need to make its data directory.
6431            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6432                    UserHandle.USER_OWNER);
6433
6434            boolean uidError = false;
6435            if (dataPath.exists()) {
6436                int currentUid = 0;
6437                try {
6438                    StructStat stat = Os.stat(dataPath.getPath());
6439                    currentUid = stat.st_uid;
6440                } catch (ErrnoException e) {
6441                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6442                }
6443
6444                // If we have mismatched owners for the data path, we have a problem.
6445                if (currentUid != pkg.applicationInfo.uid) {
6446                    boolean recovered = false;
6447                    if (currentUid == 0) {
6448                        // The directory somehow became owned by root.  Wow.
6449                        // This is probably because the system was stopped while
6450                        // installd was in the middle of messing with its libs
6451                        // directory.  Ask installd to fix that.
6452                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6453                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6454                        if (ret >= 0) {
6455                            recovered = true;
6456                            String msg = "Package " + pkg.packageName
6457                                    + " unexpectedly changed to uid 0; recovered to " +
6458                                    + pkg.applicationInfo.uid;
6459                            reportSettingsProblem(Log.WARN, msg);
6460                        }
6461                    }
6462                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6463                            || (scanFlags&SCAN_BOOTING) != 0)) {
6464                        // If this is a system app, we can at least delete its
6465                        // current data so the application will still work.
6466                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6467                        if (ret >= 0) {
6468                            // TODO: Kill the processes first
6469                            // Old data gone!
6470                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6471                                    ? "System package " : "Third party package ";
6472                            String msg = prefix + pkg.packageName
6473                                    + " has changed from uid: "
6474                                    + currentUid + " to "
6475                                    + pkg.applicationInfo.uid + "; old data erased";
6476                            reportSettingsProblem(Log.WARN, msg);
6477                            recovered = true;
6478
6479                            // And now re-install the app.
6480                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6481                                    pkg.applicationInfo.seinfo);
6482                            if (ret == -1) {
6483                                // Ack should not happen!
6484                                msg = prefix + pkg.packageName
6485                                        + " could not have data directory re-created after delete.";
6486                                reportSettingsProblem(Log.WARN, msg);
6487                                throw new PackageManagerException(
6488                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6489                            }
6490                        }
6491                        if (!recovered) {
6492                            mHasSystemUidErrors = true;
6493                        }
6494                    } else if (!recovered) {
6495                        // If we allow this install to proceed, we will be broken.
6496                        // Abort, abort!
6497                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6498                                "scanPackageLI");
6499                    }
6500                    if (!recovered) {
6501                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6502                            + pkg.applicationInfo.uid + "/fs_"
6503                            + currentUid;
6504                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6505                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6506                        String msg = "Package " + pkg.packageName
6507                                + " has mismatched uid: "
6508                                + currentUid + " on disk, "
6509                                + pkg.applicationInfo.uid + " in settings";
6510                        // writer
6511                        synchronized (mPackages) {
6512                            mSettings.mReadMessages.append(msg);
6513                            mSettings.mReadMessages.append('\n');
6514                            uidError = true;
6515                            if (!pkgSetting.uidError) {
6516                                reportSettingsProblem(Log.ERROR, msg);
6517                            }
6518                        }
6519                    }
6520                }
6521                pkg.applicationInfo.dataDir = dataPath.getPath();
6522                if (mShouldRestoreconData) {
6523                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6524                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6525                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6526                }
6527            } else {
6528                if (DEBUG_PACKAGE_SCANNING) {
6529                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6530                        Log.v(TAG, "Want this data dir: " + dataPath);
6531                }
6532                //invoke installer to do the actual installation
6533                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6534                        pkg.applicationInfo.seinfo);
6535                if (ret < 0) {
6536                    // Error from installer
6537                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6538                            "Unable to create data dirs [errorCode=" + ret + "]");
6539                }
6540
6541                if (dataPath.exists()) {
6542                    pkg.applicationInfo.dataDir = dataPath.getPath();
6543                } else {
6544                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6545                    pkg.applicationInfo.dataDir = null;
6546                }
6547            }
6548
6549            pkgSetting.uidError = uidError;
6550        }
6551
6552        final String path = scanFile.getPath();
6553        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6554
6555        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6556            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6557
6558            // Some system apps still use directory structure for native libraries
6559            // in which case we might end up not detecting abi solely based on apk
6560            // structure. Try to detect abi based on directory structure.
6561            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6562                    pkg.applicationInfo.primaryCpuAbi == null) {
6563                setBundledAppAbisAndRoots(pkg, pkgSetting);
6564                setNativeLibraryPaths(pkg);
6565            }
6566
6567        } else {
6568            if ((scanFlags & SCAN_MOVE) != 0) {
6569                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6570                // but we already have this packages package info in the PackageSetting. We just
6571                // use that and derive the native library path based on the new codepath.
6572                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6573                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6574            }
6575
6576            // Set native library paths again. For moves, the path will be updated based on the
6577            // ABIs we've determined above. For non-moves, the path will be updated based on the
6578            // ABIs we determined during compilation, but the path will depend on the final
6579            // package path (after the rename away from the stage path).
6580            setNativeLibraryPaths(pkg);
6581        }
6582
6583        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6584        final int[] userIds = sUserManager.getUserIds();
6585        synchronized (mInstallLock) {
6586            // Create a native library symlink only if we have native libraries
6587            // and if the native libraries are 32 bit libraries. We do not provide
6588            // this symlink for 64 bit libraries.
6589            if (pkg.applicationInfo.primaryCpuAbi != null &&
6590                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6591                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6592                for (int userId : userIds) {
6593                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6594                            nativeLibPath, userId) < 0) {
6595                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6596                                "Failed linking native library dir (user=" + userId + ")");
6597                    }
6598                }
6599            }
6600        }
6601
6602        // This is a special case for the "system" package, where the ABI is
6603        // dictated by the zygote configuration (and init.rc). We should keep track
6604        // of this ABI so that we can deal with "normal" applications that run under
6605        // the same UID correctly.
6606        if (mPlatformPackage == pkg) {
6607            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6608                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6609        }
6610
6611        // If there's a mismatch between the abi-override in the package setting
6612        // and the abiOverride specified for the install. Warn about this because we
6613        // would've already compiled the app without taking the package setting into
6614        // account.
6615        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6616            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6617                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6618                        " for package: " + pkg.packageName);
6619            }
6620        }
6621
6622        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6623        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6624        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6625
6626        // Copy the derived override back to the parsed package, so that we can
6627        // update the package settings accordingly.
6628        pkg.cpuAbiOverride = cpuAbiOverride;
6629
6630        if (DEBUG_ABI_SELECTION) {
6631            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6632                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6633                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6634        }
6635
6636        // Push the derived path down into PackageSettings so we know what to
6637        // clean up at uninstall time.
6638        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6639
6640        if (DEBUG_ABI_SELECTION) {
6641            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6642                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6643                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6644        }
6645
6646        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6647            // We don't do this here during boot because we can do it all
6648            // at once after scanning all existing packages.
6649            //
6650            // We also do this *before* we perform dexopt on this package, so that
6651            // we can avoid redundant dexopts, and also to make sure we've got the
6652            // code and package path correct.
6653            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6654                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6655        }
6656
6657        if ((scanFlags & SCAN_NO_DEX) == 0) {
6658            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6659                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6660            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6661                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6662            }
6663        }
6664        if (mFactoryTest && pkg.requestedPermissions.contains(
6665                android.Manifest.permission.FACTORY_TEST)) {
6666            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6667        }
6668
6669        ArrayList<PackageParser.Package> clientLibPkgs = null;
6670
6671        // writer
6672        synchronized (mPackages) {
6673            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6674                // Only system apps can add new shared libraries.
6675                if (pkg.libraryNames != null) {
6676                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6677                        String name = pkg.libraryNames.get(i);
6678                        boolean allowed = false;
6679                        if (pkg.isUpdatedSystemApp()) {
6680                            // New library entries can only be added through the
6681                            // system image.  This is important to get rid of a lot
6682                            // of nasty edge cases: for example if we allowed a non-
6683                            // system update of the app to add a library, then uninstalling
6684                            // the update would make the library go away, and assumptions
6685                            // we made such as through app install filtering would now
6686                            // have allowed apps on the device which aren't compatible
6687                            // with it.  Better to just have the restriction here, be
6688                            // conservative, and create many fewer cases that can negatively
6689                            // impact the user experience.
6690                            final PackageSetting sysPs = mSettings
6691                                    .getDisabledSystemPkgLPr(pkg.packageName);
6692                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6693                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6694                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6695                                        allowed = true;
6696                                        allowed = true;
6697                                        break;
6698                                    }
6699                                }
6700                            }
6701                        } else {
6702                            allowed = true;
6703                        }
6704                        if (allowed) {
6705                            if (!mSharedLibraries.containsKey(name)) {
6706                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6707                            } else if (!name.equals(pkg.packageName)) {
6708                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6709                                        + name + " already exists; skipping");
6710                            }
6711                        } else {
6712                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6713                                    + name + " that is not declared on system image; skipping");
6714                        }
6715                    }
6716                    if ((scanFlags&SCAN_BOOTING) == 0) {
6717                        // If we are not booting, we need to update any applications
6718                        // that are clients of our shared library.  If we are booting,
6719                        // this will all be done once the scan is complete.
6720                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6721                    }
6722                }
6723            }
6724        }
6725
6726        // We also need to dexopt any apps that are dependent on this library.  Note that
6727        // if these fail, we should abort the install since installing the library will
6728        // result in some apps being broken.
6729        if (clientLibPkgs != null) {
6730            if ((scanFlags & SCAN_NO_DEX) == 0) {
6731                for (int i = 0; i < clientLibPkgs.size(); i++) {
6732                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6733                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6734                            null /* instruction sets */, forceDex,
6735                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6736                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6737                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6738                                "scanPackageLI failed to dexopt clientLibPkgs");
6739                    }
6740                }
6741            }
6742        }
6743
6744        // Also need to kill any apps that are dependent on the library.
6745        if (clientLibPkgs != null) {
6746            for (int i=0; i<clientLibPkgs.size(); i++) {
6747                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6748                killApplication(clientPkg.applicationInfo.packageName,
6749                        clientPkg.applicationInfo.uid, "update lib");
6750            }
6751        }
6752
6753        // Make sure we're not adding any bogus keyset info
6754        KeySetManagerService ksms = mSettings.mKeySetManagerService;
6755        ksms.assertScannedPackageValid(pkg);
6756
6757        // writer
6758        synchronized (mPackages) {
6759            // We don't expect installation to fail beyond this point
6760
6761            // Add the new setting to mSettings
6762            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6763            // Add the new setting to mPackages
6764            mPackages.put(pkg.applicationInfo.packageName, pkg);
6765            // Make sure we don't accidentally delete its data.
6766            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6767            while (iter.hasNext()) {
6768                PackageCleanItem item = iter.next();
6769                if (pkgName.equals(item.packageName)) {
6770                    iter.remove();
6771                }
6772            }
6773
6774            // Take care of first install / last update times.
6775            if (currentTime != 0) {
6776                if (pkgSetting.firstInstallTime == 0) {
6777                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6778                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6779                    pkgSetting.lastUpdateTime = currentTime;
6780                }
6781            } else if (pkgSetting.firstInstallTime == 0) {
6782                // We need *something*.  Take time time stamp of the file.
6783                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6784            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6785                if (scanFileTime != pkgSetting.timeStamp) {
6786                    // A package on the system image has changed; consider this
6787                    // to be an update.
6788                    pkgSetting.lastUpdateTime = scanFileTime;
6789                }
6790            }
6791
6792            // Add the package's KeySets to the global KeySetManagerService
6793            ksms.addScannedPackageLPw(pkg);
6794
6795            int N = pkg.providers.size();
6796            StringBuilder r = null;
6797            int i;
6798            for (i=0; i<N; i++) {
6799                PackageParser.Provider p = pkg.providers.get(i);
6800                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6801                        p.info.processName, pkg.applicationInfo.uid);
6802                mProviders.addProvider(p);
6803                p.syncable = p.info.isSyncable;
6804                if (p.info.authority != null) {
6805                    String names[] = p.info.authority.split(";");
6806                    p.info.authority = null;
6807                    for (int j = 0; j < names.length; j++) {
6808                        if (j == 1 && p.syncable) {
6809                            // We only want the first authority for a provider to possibly be
6810                            // syncable, so if we already added this provider using a different
6811                            // authority clear the syncable flag. We copy the provider before
6812                            // changing it because the mProviders object contains a reference
6813                            // to a provider that we don't want to change.
6814                            // Only do this for the second authority since the resulting provider
6815                            // object can be the same for all future authorities for this provider.
6816                            p = new PackageParser.Provider(p);
6817                            p.syncable = false;
6818                        }
6819                        if (!mProvidersByAuthority.containsKey(names[j])) {
6820                            mProvidersByAuthority.put(names[j], p);
6821                            if (p.info.authority == null) {
6822                                p.info.authority = names[j];
6823                            } else {
6824                                p.info.authority = p.info.authority + ";" + names[j];
6825                            }
6826                            if (DEBUG_PACKAGE_SCANNING) {
6827                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6828                                    Log.d(TAG, "Registered content provider: " + names[j]
6829                                            + ", className = " + p.info.name + ", isSyncable = "
6830                                            + p.info.isSyncable);
6831                            }
6832                        } else {
6833                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6834                            Slog.w(TAG, "Skipping provider name " + names[j] +
6835                                    " (in package " + pkg.applicationInfo.packageName +
6836                                    "): name already used by "
6837                                    + ((other != null && other.getComponentName() != null)
6838                                            ? other.getComponentName().getPackageName() : "?"));
6839                        }
6840                    }
6841                }
6842                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6843                    if (r == null) {
6844                        r = new StringBuilder(256);
6845                    } else {
6846                        r.append(' ');
6847                    }
6848                    r.append(p.info.name);
6849                }
6850            }
6851            if (r != null) {
6852                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6853            }
6854
6855            N = pkg.services.size();
6856            r = null;
6857            for (i=0; i<N; i++) {
6858                PackageParser.Service s = pkg.services.get(i);
6859                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6860                        s.info.processName, pkg.applicationInfo.uid);
6861                mServices.addService(s);
6862                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6863                    if (r == null) {
6864                        r = new StringBuilder(256);
6865                    } else {
6866                        r.append(' ');
6867                    }
6868                    r.append(s.info.name);
6869                }
6870            }
6871            if (r != null) {
6872                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6873            }
6874
6875            N = pkg.receivers.size();
6876            r = null;
6877            for (i=0; i<N; i++) {
6878                PackageParser.Activity a = pkg.receivers.get(i);
6879                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6880                        a.info.processName, pkg.applicationInfo.uid);
6881                mReceivers.addActivity(a, "receiver");
6882                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6883                    if (r == null) {
6884                        r = new StringBuilder(256);
6885                    } else {
6886                        r.append(' ');
6887                    }
6888                    r.append(a.info.name);
6889                }
6890            }
6891            if (r != null) {
6892                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6893            }
6894
6895            N = pkg.activities.size();
6896            r = null;
6897            for (i=0; i<N; i++) {
6898                PackageParser.Activity a = pkg.activities.get(i);
6899                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6900                        a.info.processName, pkg.applicationInfo.uid);
6901                mActivities.addActivity(a, "activity");
6902                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6903                    if (r == null) {
6904                        r = new StringBuilder(256);
6905                    } else {
6906                        r.append(' ');
6907                    }
6908                    r.append(a.info.name);
6909                }
6910            }
6911            if (r != null) {
6912                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6913            }
6914
6915            N = pkg.permissionGroups.size();
6916            r = null;
6917            for (i=0; i<N; i++) {
6918                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6919                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6920                if (cur == null) {
6921                    mPermissionGroups.put(pg.info.name, pg);
6922                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6923                        if (r == null) {
6924                            r = new StringBuilder(256);
6925                        } else {
6926                            r.append(' ');
6927                        }
6928                        r.append(pg.info.name);
6929                    }
6930                } else {
6931                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6932                            + pg.info.packageName + " ignored: original from "
6933                            + cur.info.packageName);
6934                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6935                        if (r == null) {
6936                            r = new StringBuilder(256);
6937                        } else {
6938                            r.append(' ');
6939                        }
6940                        r.append("DUP:");
6941                        r.append(pg.info.name);
6942                    }
6943                }
6944            }
6945            if (r != null) {
6946                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6947            }
6948
6949            N = pkg.permissions.size();
6950            r = null;
6951            for (i=0; i<N; i++) {
6952                PackageParser.Permission p = pkg.permissions.get(i);
6953
6954                // Now that permission groups have a special meaning, we ignore permission
6955                // groups for legacy apps to prevent unexpected behavior. In particular,
6956                // permissions for one app being granted to someone just becuase they happen
6957                // to be in a group defined by another app (before this had no implications).
6958                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
6959                    p.group = mPermissionGroups.get(p.info.group);
6960                    // Warn for a permission in an unknown group.
6961                    if (p.info.group != null && p.group == null) {
6962                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6963                                + p.info.packageName + " in an unknown group " + p.info.group);
6964                    }
6965                }
6966
6967                ArrayMap<String, BasePermission> permissionMap =
6968                        p.tree ? mSettings.mPermissionTrees
6969                                : mSettings.mPermissions;
6970                BasePermission bp = permissionMap.get(p.info.name);
6971
6972                // Allow system apps to redefine non-system permissions
6973                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6974                    final boolean currentOwnerIsSystem = (bp.perm != null
6975                            && isSystemApp(bp.perm.owner));
6976                    if (isSystemApp(p.owner)) {
6977                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6978                            // It's a built-in permission and no owner, take ownership now
6979                            bp.packageSetting = pkgSetting;
6980                            bp.perm = p;
6981                            bp.uid = pkg.applicationInfo.uid;
6982                            bp.sourcePackage = p.info.packageName;
6983                        } else if (!currentOwnerIsSystem) {
6984                            String msg = "New decl " + p.owner + " of permission  "
6985                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6986                            reportSettingsProblem(Log.WARN, msg);
6987                            bp = null;
6988                        }
6989                    }
6990                }
6991
6992                if (bp == null) {
6993                    bp = new BasePermission(p.info.name, p.info.packageName,
6994                            BasePermission.TYPE_NORMAL);
6995                    permissionMap.put(p.info.name, bp);
6996                }
6997
6998                if (bp.perm == null) {
6999                    if (bp.sourcePackage == null
7000                            || bp.sourcePackage.equals(p.info.packageName)) {
7001                        BasePermission tree = findPermissionTreeLP(p.info.name);
7002                        if (tree == null
7003                                || tree.sourcePackage.equals(p.info.packageName)) {
7004                            bp.packageSetting = pkgSetting;
7005                            bp.perm = p;
7006                            bp.uid = pkg.applicationInfo.uid;
7007                            bp.sourcePackage = p.info.packageName;
7008                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7009                                if (r == null) {
7010                                    r = new StringBuilder(256);
7011                                } else {
7012                                    r.append(' ');
7013                                }
7014                                r.append(p.info.name);
7015                            }
7016                        } else {
7017                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7018                                    + p.info.packageName + " ignored: base tree "
7019                                    + tree.name + " is from package "
7020                                    + tree.sourcePackage);
7021                        }
7022                    } else {
7023                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7024                                + p.info.packageName + " ignored: original from "
7025                                + bp.sourcePackage);
7026                    }
7027                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7028                    if (r == null) {
7029                        r = new StringBuilder(256);
7030                    } else {
7031                        r.append(' ');
7032                    }
7033                    r.append("DUP:");
7034                    r.append(p.info.name);
7035                }
7036                if (bp.perm == p) {
7037                    bp.protectionLevel = p.info.protectionLevel;
7038                }
7039            }
7040
7041            if (r != null) {
7042                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7043            }
7044
7045            N = pkg.instrumentation.size();
7046            r = null;
7047            for (i=0; i<N; i++) {
7048                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7049                a.info.packageName = pkg.applicationInfo.packageName;
7050                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7051                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7052                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7053                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7054                a.info.dataDir = pkg.applicationInfo.dataDir;
7055
7056                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7057                // need other information about the application, like the ABI and what not ?
7058                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7059                mInstrumentation.put(a.getComponentName(), a);
7060                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7061                    if (r == null) {
7062                        r = new StringBuilder(256);
7063                    } else {
7064                        r.append(' ');
7065                    }
7066                    r.append(a.info.name);
7067                }
7068            }
7069            if (r != null) {
7070                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7071            }
7072
7073            if (pkg.protectedBroadcasts != null) {
7074                N = pkg.protectedBroadcasts.size();
7075                for (i=0; i<N; i++) {
7076                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7077                }
7078            }
7079
7080            pkgSetting.setTimeStamp(scanFileTime);
7081
7082            // Create idmap files for pairs of (packages, overlay packages).
7083            // Note: "android", ie framework-res.apk, is handled by native layers.
7084            if (pkg.mOverlayTarget != null) {
7085                // This is an overlay package.
7086                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7087                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7088                        mOverlays.put(pkg.mOverlayTarget,
7089                                new ArrayMap<String, PackageParser.Package>());
7090                    }
7091                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7092                    map.put(pkg.packageName, pkg);
7093                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7094                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7095                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7096                                "scanPackageLI failed to createIdmap");
7097                    }
7098                }
7099            } else if (mOverlays.containsKey(pkg.packageName) &&
7100                    !pkg.packageName.equals("android")) {
7101                // This is a regular package, with one or more known overlay packages.
7102                createIdmapsForPackageLI(pkg);
7103            }
7104        }
7105
7106        return pkg;
7107    }
7108
7109    /**
7110     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7111     * is derived purely on the basis of the contents of {@code scanFile} and
7112     * {@code cpuAbiOverride}.
7113     *
7114     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7115     */
7116    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7117                                 String cpuAbiOverride, boolean extractLibs)
7118            throws PackageManagerException {
7119        // TODO: We can probably be smarter about this stuff. For installed apps,
7120        // we can calculate this information at install time once and for all. For
7121        // system apps, we can probably assume that this information doesn't change
7122        // after the first boot scan. As things stand, we do lots of unnecessary work.
7123
7124        // Give ourselves some initial paths; we'll come back for another
7125        // pass once we've determined ABI below.
7126        setNativeLibraryPaths(pkg);
7127
7128        // We would never need to extract libs for forward-locked and external packages,
7129        // since the container service will do it for us. We shouldn't attempt to
7130        // extract libs from system app when it was not updated.
7131        if (pkg.isForwardLocked() || isExternal(pkg) ||
7132            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7133            extractLibs = false;
7134        }
7135
7136        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7137        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7138
7139        NativeLibraryHelper.Handle handle = null;
7140        try {
7141            handle = NativeLibraryHelper.Handle.create(scanFile);
7142            // TODO(multiArch): This can be null for apps that didn't go through the
7143            // usual installation process. We can calculate it again, like we
7144            // do during install time.
7145            //
7146            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7147            // unnecessary.
7148            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7149
7150            // Null out the abis so that they can be recalculated.
7151            pkg.applicationInfo.primaryCpuAbi = null;
7152            pkg.applicationInfo.secondaryCpuAbi = null;
7153            if (isMultiArch(pkg.applicationInfo)) {
7154                // Warn if we've set an abiOverride for multi-lib packages..
7155                // By definition, we need to copy both 32 and 64 bit libraries for
7156                // such packages.
7157                if (pkg.cpuAbiOverride != null
7158                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7159                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7160                }
7161
7162                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7163                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7164                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7165                    if (extractLibs) {
7166                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7167                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7168                                useIsaSpecificSubdirs);
7169                    } else {
7170                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7171                    }
7172                }
7173
7174                maybeThrowExceptionForMultiArchCopy(
7175                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7176
7177                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7178                    if (extractLibs) {
7179                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7180                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7181                                useIsaSpecificSubdirs);
7182                    } else {
7183                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7184                    }
7185                }
7186
7187                maybeThrowExceptionForMultiArchCopy(
7188                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7189
7190                if (abi64 >= 0) {
7191                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7192                }
7193
7194                if (abi32 >= 0) {
7195                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7196                    if (abi64 >= 0) {
7197                        pkg.applicationInfo.secondaryCpuAbi = abi;
7198                    } else {
7199                        pkg.applicationInfo.primaryCpuAbi = abi;
7200                    }
7201                }
7202            } else {
7203                String[] abiList = (cpuAbiOverride != null) ?
7204                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7205
7206                // Enable gross and lame hacks for apps that are built with old
7207                // SDK tools. We must scan their APKs for renderscript bitcode and
7208                // not launch them if it's present. Don't bother checking on devices
7209                // that don't have 64 bit support.
7210                boolean needsRenderScriptOverride = false;
7211                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7212                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7213                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7214                    needsRenderScriptOverride = true;
7215                }
7216
7217                final int copyRet;
7218                if (extractLibs) {
7219                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7220                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7221                } else {
7222                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7223                }
7224
7225                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7226                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7227                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7228                }
7229
7230                if (copyRet >= 0) {
7231                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7232                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7233                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7234                } else if (needsRenderScriptOverride) {
7235                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7236                }
7237            }
7238        } catch (IOException ioe) {
7239            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7240        } finally {
7241            IoUtils.closeQuietly(handle);
7242        }
7243
7244        // Now that we've calculated the ABIs and determined if it's an internal app,
7245        // we will go ahead and populate the nativeLibraryPath.
7246        setNativeLibraryPaths(pkg);
7247    }
7248
7249    /**
7250     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7251     * i.e, so that all packages can be run inside a single process if required.
7252     *
7253     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7254     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7255     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7256     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7257     * updating a package that belongs to a shared user.
7258     *
7259     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7260     * adds unnecessary complexity.
7261     */
7262    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7263            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7264        String requiredInstructionSet = null;
7265        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7266            requiredInstructionSet = VMRuntime.getInstructionSet(
7267                     scannedPackage.applicationInfo.primaryCpuAbi);
7268        }
7269
7270        PackageSetting requirer = null;
7271        for (PackageSetting ps : packagesForUser) {
7272            // If packagesForUser contains scannedPackage, we skip it. This will happen
7273            // when scannedPackage is an update of an existing package. Without this check,
7274            // we will never be able to change the ABI of any package belonging to a shared
7275            // user, even if it's compatible with other packages.
7276            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7277                if (ps.primaryCpuAbiString == null) {
7278                    continue;
7279                }
7280
7281                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7282                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7283                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7284                    // this but there's not much we can do.
7285                    String errorMessage = "Instruction set mismatch, "
7286                            + ((requirer == null) ? "[caller]" : requirer)
7287                            + " requires " + requiredInstructionSet + " whereas " + ps
7288                            + " requires " + instructionSet;
7289                    Slog.w(TAG, errorMessage);
7290                }
7291
7292                if (requiredInstructionSet == null) {
7293                    requiredInstructionSet = instructionSet;
7294                    requirer = ps;
7295                }
7296            }
7297        }
7298
7299        if (requiredInstructionSet != null) {
7300            String adjustedAbi;
7301            if (requirer != null) {
7302                // requirer != null implies that either scannedPackage was null or that scannedPackage
7303                // did not require an ABI, in which case we have to adjust scannedPackage to match
7304                // the ABI of the set (which is the same as requirer's ABI)
7305                adjustedAbi = requirer.primaryCpuAbiString;
7306                if (scannedPackage != null) {
7307                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7308                }
7309            } else {
7310                // requirer == null implies that we're updating all ABIs in the set to
7311                // match scannedPackage.
7312                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7313            }
7314
7315            for (PackageSetting ps : packagesForUser) {
7316                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7317                    if (ps.primaryCpuAbiString != null) {
7318                        continue;
7319                    }
7320
7321                    ps.primaryCpuAbiString = adjustedAbi;
7322                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7323                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7324                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7325
7326                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7327                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7328                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7329                            ps.primaryCpuAbiString = null;
7330                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7331                            return;
7332                        } else {
7333                            mInstaller.rmdex(ps.codePathString,
7334                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7335                        }
7336                    }
7337                }
7338            }
7339        }
7340    }
7341
7342    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7343        synchronized (mPackages) {
7344            mResolverReplaced = true;
7345            // Set up information for custom user intent resolution activity.
7346            mResolveActivity.applicationInfo = pkg.applicationInfo;
7347            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7348            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7349            mResolveActivity.processName = pkg.applicationInfo.packageName;
7350            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7351            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7352                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7353            mResolveActivity.theme = 0;
7354            mResolveActivity.exported = true;
7355            mResolveActivity.enabled = true;
7356            mResolveInfo.activityInfo = mResolveActivity;
7357            mResolveInfo.priority = 0;
7358            mResolveInfo.preferredOrder = 0;
7359            mResolveInfo.match = 0;
7360            mResolveComponentName = mCustomResolverComponentName;
7361            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7362                    mResolveComponentName);
7363        }
7364    }
7365
7366    private static String calculateBundledApkRoot(final String codePathString) {
7367        final File codePath = new File(codePathString);
7368        final File codeRoot;
7369        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7370            codeRoot = Environment.getRootDirectory();
7371        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7372            codeRoot = Environment.getOemDirectory();
7373        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7374            codeRoot = Environment.getVendorDirectory();
7375        } else {
7376            // Unrecognized code path; take its top real segment as the apk root:
7377            // e.g. /something/app/blah.apk => /something
7378            try {
7379                File f = codePath.getCanonicalFile();
7380                File parent = f.getParentFile();    // non-null because codePath is a file
7381                File tmp;
7382                while ((tmp = parent.getParentFile()) != null) {
7383                    f = parent;
7384                    parent = tmp;
7385                }
7386                codeRoot = f;
7387                Slog.w(TAG, "Unrecognized code path "
7388                        + codePath + " - using " + codeRoot);
7389            } catch (IOException e) {
7390                // Can't canonicalize the code path -- shenanigans?
7391                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7392                return Environment.getRootDirectory().getPath();
7393            }
7394        }
7395        return codeRoot.getPath();
7396    }
7397
7398    /**
7399     * Derive and set the location of native libraries for the given package,
7400     * which varies depending on where and how the package was installed.
7401     */
7402    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7403        final ApplicationInfo info = pkg.applicationInfo;
7404        final String codePath = pkg.codePath;
7405        final File codeFile = new File(codePath);
7406        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7407        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7408
7409        info.nativeLibraryRootDir = null;
7410        info.nativeLibraryRootRequiresIsa = false;
7411        info.nativeLibraryDir = null;
7412        info.secondaryNativeLibraryDir = null;
7413
7414        if (isApkFile(codeFile)) {
7415            // Monolithic install
7416            if (bundledApp) {
7417                // If "/system/lib64/apkname" exists, assume that is the per-package
7418                // native library directory to use; otherwise use "/system/lib/apkname".
7419                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7420                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7421                        getPrimaryInstructionSet(info));
7422
7423                // This is a bundled system app so choose the path based on the ABI.
7424                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7425                // is just the default path.
7426                final String apkName = deriveCodePathName(codePath);
7427                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7428                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7429                        apkName).getAbsolutePath();
7430
7431                if (info.secondaryCpuAbi != null) {
7432                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7433                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7434                            secondaryLibDir, apkName).getAbsolutePath();
7435                }
7436            } else if (asecApp) {
7437                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7438                        .getAbsolutePath();
7439            } else {
7440                final String apkName = deriveCodePathName(codePath);
7441                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7442                        .getAbsolutePath();
7443            }
7444
7445            info.nativeLibraryRootRequiresIsa = false;
7446            info.nativeLibraryDir = info.nativeLibraryRootDir;
7447        } else {
7448            // Cluster install
7449            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7450            info.nativeLibraryRootRequiresIsa = true;
7451
7452            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7453                    getPrimaryInstructionSet(info)).getAbsolutePath();
7454
7455            if (info.secondaryCpuAbi != null) {
7456                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7457                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7458            }
7459        }
7460    }
7461
7462    /**
7463     * Calculate the abis and roots for a bundled app. These can uniquely
7464     * be determined from the contents of the system partition, i.e whether
7465     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7466     * of this information, and instead assume that the system was built
7467     * sensibly.
7468     */
7469    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7470                                           PackageSetting pkgSetting) {
7471        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7472
7473        // If "/system/lib64/apkname" exists, assume that is the per-package
7474        // native library directory to use; otherwise use "/system/lib/apkname".
7475        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7476        setBundledAppAbi(pkg, apkRoot, apkName);
7477        // pkgSetting might be null during rescan following uninstall of updates
7478        // to a bundled app, so accommodate that possibility.  The settings in
7479        // that case will be established later from the parsed package.
7480        //
7481        // If the settings aren't null, sync them up with what we've just derived.
7482        // note that apkRoot isn't stored in the package settings.
7483        if (pkgSetting != null) {
7484            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7485            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7486        }
7487    }
7488
7489    /**
7490     * Deduces the ABI of a bundled app and sets the relevant fields on the
7491     * parsed pkg object.
7492     *
7493     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7494     *        under which system libraries are installed.
7495     * @param apkName the name of the installed package.
7496     */
7497    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7498        final File codeFile = new File(pkg.codePath);
7499
7500        final boolean has64BitLibs;
7501        final boolean has32BitLibs;
7502        if (isApkFile(codeFile)) {
7503            // Monolithic install
7504            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7505            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7506        } else {
7507            // Cluster install
7508            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7509            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7510                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7511                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7512                has64BitLibs = (new File(rootDir, isa)).exists();
7513            } else {
7514                has64BitLibs = false;
7515            }
7516            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7517                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7518                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7519                has32BitLibs = (new File(rootDir, isa)).exists();
7520            } else {
7521                has32BitLibs = false;
7522            }
7523        }
7524
7525        if (has64BitLibs && !has32BitLibs) {
7526            // The package has 64 bit libs, but not 32 bit libs. Its primary
7527            // ABI should be 64 bit. We can safely assume here that the bundled
7528            // native libraries correspond to the most preferred ABI in the list.
7529
7530            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7531            pkg.applicationInfo.secondaryCpuAbi = null;
7532        } else if (has32BitLibs && !has64BitLibs) {
7533            // The package has 32 bit libs but not 64 bit libs. Its primary
7534            // ABI should be 32 bit.
7535
7536            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7537            pkg.applicationInfo.secondaryCpuAbi = null;
7538        } else if (has32BitLibs && has64BitLibs) {
7539            // The application has both 64 and 32 bit bundled libraries. We check
7540            // here that the app declares multiArch support, and warn if it doesn't.
7541            //
7542            // We will be lenient here and record both ABIs. The primary will be the
7543            // ABI that's higher on the list, i.e, a device that's configured to prefer
7544            // 64 bit apps will see a 64 bit primary ABI,
7545
7546            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7547                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7548            }
7549
7550            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7551                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7552                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7553            } else {
7554                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7555                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7556            }
7557        } else {
7558            pkg.applicationInfo.primaryCpuAbi = null;
7559            pkg.applicationInfo.secondaryCpuAbi = null;
7560        }
7561    }
7562
7563    private void killApplication(String pkgName, int appId, String reason) {
7564        // Request the ActivityManager to kill the process(only for existing packages)
7565        // so that we do not end up in a confused state while the user is still using the older
7566        // version of the application while the new one gets installed.
7567        IActivityManager am = ActivityManagerNative.getDefault();
7568        if (am != null) {
7569            try {
7570                am.killApplicationWithAppId(pkgName, appId, reason);
7571            } catch (RemoteException e) {
7572            }
7573        }
7574    }
7575
7576    void removePackageLI(PackageSetting ps, boolean chatty) {
7577        if (DEBUG_INSTALL) {
7578            if (chatty)
7579                Log.d(TAG, "Removing package " + ps.name);
7580        }
7581
7582        // writer
7583        synchronized (mPackages) {
7584            mPackages.remove(ps.name);
7585            final PackageParser.Package pkg = ps.pkg;
7586            if (pkg != null) {
7587                cleanPackageDataStructuresLILPw(pkg, chatty);
7588            }
7589        }
7590    }
7591
7592    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7593        if (DEBUG_INSTALL) {
7594            if (chatty)
7595                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7596        }
7597
7598        // writer
7599        synchronized (mPackages) {
7600            mPackages.remove(pkg.applicationInfo.packageName);
7601            cleanPackageDataStructuresLILPw(pkg, chatty);
7602        }
7603    }
7604
7605    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7606        int N = pkg.providers.size();
7607        StringBuilder r = null;
7608        int i;
7609        for (i=0; i<N; i++) {
7610            PackageParser.Provider p = pkg.providers.get(i);
7611            mProviders.removeProvider(p);
7612            if (p.info.authority == null) {
7613
7614                /* There was another ContentProvider with this authority when
7615                 * this app was installed so this authority is null,
7616                 * Ignore it as we don't have to unregister the provider.
7617                 */
7618                continue;
7619            }
7620            String names[] = p.info.authority.split(";");
7621            for (int j = 0; j < names.length; j++) {
7622                if (mProvidersByAuthority.get(names[j]) == p) {
7623                    mProvidersByAuthority.remove(names[j]);
7624                    if (DEBUG_REMOVE) {
7625                        if (chatty)
7626                            Log.d(TAG, "Unregistered content provider: " + names[j]
7627                                    + ", className = " + p.info.name + ", isSyncable = "
7628                                    + p.info.isSyncable);
7629                    }
7630                }
7631            }
7632            if (DEBUG_REMOVE && chatty) {
7633                if (r == null) {
7634                    r = new StringBuilder(256);
7635                } else {
7636                    r.append(' ');
7637                }
7638                r.append(p.info.name);
7639            }
7640        }
7641        if (r != null) {
7642            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7643        }
7644
7645        N = pkg.services.size();
7646        r = null;
7647        for (i=0; i<N; i++) {
7648            PackageParser.Service s = pkg.services.get(i);
7649            mServices.removeService(s);
7650            if (chatty) {
7651                if (r == null) {
7652                    r = new StringBuilder(256);
7653                } else {
7654                    r.append(' ');
7655                }
7656                r.append(s.info.name);
7657            }
7658        }
7659        if (r != null) {
7660            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7661        }
7662
7663        N = pkg.receivers.size();
7664        r = null;
7665        for (i=0; i<N; i++) {
7666            PackageParser.Activity a = pkg.receivers.get(i);
7667            mReceivers.removeActivity(a, "receiver");
7668            if (DEBUG_REMOVE && chatty) {
7669                if (r == null) {
7670                    r = new StringBuilder(256);
7671                } else {
7672                    r.append(' ');
7673                }
7674                r.append(a.info.name);
7675            }
7676        }
7677        if (r != null) {
7678            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7679        }
7680
7681        N = pkg.activities.size();
7682        r = null;
7683        for (i=0; i<N; i++) {
7684            PackageParser.Activity a = pkg.activities.get(i);
7685            mActivities.removeActivity(a, "activity");
7686            if (DEBUG_REMOVE && chatty) {
7687                if (r == null) {
7688                    r = new StringBuilder(256);
7689                } else {
7690                    r.append(' ');
7691                }
7692                r.append(a.info.name);
7693            }
7694        }
7695        if (r != null) {
7696            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7697        }
7698
7699        N = pkg.permissions.size();
7700        r = null;
7701        for (i=0; i<N; i++) {
7702            PackageParser.Permission p = pkg.permissions.get(i);
7703            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7704            if (bp == null) {
7705                bp = mSettings.mPermissionTrees.get(p.info.name);
7706            }
7707            if (bp != null && bp.perm == p) {
7708                bp.perm = null;
7709                if (DEBUG_REMOVE && chatty) {
7710                    if (r == null) {
7711                        r = new StringBuilder(256);
7712                    } else {
7713                        r.append(' ');
7714                    }
7715                    r.append(p.info.name);
7716                }
7717            }
7718            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7719                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7720                if (appOpPerms != null) {
7721                    appOpPerms.remove(pkg.packageName);
7722                }
7723            }
7724        }
7725        if (r != null) {
7726            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7727        }
7728
7729        N = pkg.requestedPermissions.size();
7730        r = null;
7731        for (i=0; i<N; i++) {
7732            String perm = pkg.requestedPermissions.get(i);
7733            BasePermission bp = mSettings.mPermissions.get(perm);
7734            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7735                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7736                if (appOpPerms != null) {
7737                    appOpPerms.remove(pkg.packageName);
7738                    if (appOpPerms.isEmpty()) {
7739                        mAppOpPermissionPackages.remove(perm);
7740                    }
7741                }
7742            }
7743        }
7744        if (r != null) {
7745            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7746        }
7747
7748        N = pkg.instrumentation.size();
7749        r = null;
7750        for (i=0; i<N; i++) {
7751            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7752            mInstrumentation.remove(a.getComponentName());
7753            if (DEBUG_REMOVE && chatty) {
7754                if (r == null) {
7755                    r = new StringBuilder(256);
7756                } else {
7757                    r.append(' ');
7758                }
7759                r.append(a.info.name);
7760            }
7761        }
7762        if (r != null) {
7763            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7764        }
7765
7766        r = null;
7767        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7768            // Only system apps can hold shared libraries.
7769            if (pkg.libraryNames != null) {
7770                for (i=0; i<pkg.libraryNames.size(); i++) {
7771                    String name = pkg.libraryNames.get(i);
7772                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7773                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7774                        mSharedLibraries.remove(name);
7775                        if (DEBUG_REMOVE && chatty) {
7776                            if (r == null) {
7777                                r = new StringBuilder(256);
7778                            } else {
7779                                r.append(' ');
7780                            }
7781                            r.append(name);
7782                        }
7783                    }
7784                }
7785            }
7786        }
7787        if (r != null) {
7788            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7789        }
7790    }
7791
7792    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7793        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7794            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7795                return true;
7796            }
7797        }
7798        return false;
7799    }
7800
7801    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7802    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7803    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7804
7805    private void updatePermissionsLPw(String changingPkg,
7806            PackageParser.Package pkgInfo, int flags) {
7807        // Make sure there are no dangling permission trees.
7808        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7809        while (it.hasNext()) {
7810            final BasePermission bp = it.next();
7811            if (bp.packageSetting == null) {
7812                // We may not yet have parsed the package, so just see if
7813                // we still know about its settings.
7814                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7815            }
7816            if (bp.packageSetting == null) {
7817                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7818                        + " from package " + bp.sourcePackage);
7819                it.remove();
7820            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7821                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7822                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7823                            + " from package " + bp.sourcePackage);
7824                    flags |= UPDATE_PERMISSIONS_ALL;
7825                    it.remove();
7826                }
7827            }
7828        }
7829
7830        // Make sure all dynamic permissions have been assigned to a package,
7831        // and make sure there are no dangling permissions.
7832        it = mSettings.mPermissions.values().iterator();
7833        while (it.hasNext()) {
7834            final BasePermission bp = it.next();
7835            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7836                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7837                        + bp.name + " pkg=" + bp.sourcePackage
7838                        + " info=" + bp.pendingInfo);
7839                if (bp.packageSetting == null && bp.pendingInfo != null) {
7840                    final BasePermission tree = findPermissionTreeLP(bp.name);
7841                    if (tree != null && tree.perm != null) {
7842                        bp.packageSetting = tree.packageSetting;
7843                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7844                                new PermissionInfo(bp.pendingInfo));
7845                        bp.perm.info.packageName = tree.perm.info.packageName;
7846                        bp.perm.info.name = bp.name;
7847                        bp.uid = tree.uid;
7848                    }
7849                }
7850            }
7851            if (bp.packageSetting == null) {
7852                // We may not yet have parsed the package, so just see if
7853                // we still know about its settings.
7854                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7855            }
7856            if (bp.packageSetting == null) {
7857                Slog.w(TAG, "Removing dangling permission: " + bp.name
7858                        + " from package " + bp.sourcePackage);
7859                it.remove();
7860            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7861                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7862                    Slog.i(TAG, "Removing old permission: " + bp.name
7863                            + " from package " + bp.sourcePackage);
7864                    flags |= UPDATE_PERMISSIONS_ALL;
7865                    it.remove();
7866                }
7867            }
7868        }
7869
7870        // Now update the permissions for all packages, in particular
7871        // replace the granted permissions of the system packages.
7872        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7873            for (PackageParser.Package pkg : mPackages.values()) {
7874                if (pkg != pkgInfo) {
7875                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7876                            changingPkg);
7877                }
7878            }
7879        }
7880
7881        if (pkgInfo != null) {
7882            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7883        }
7884    }
7885
7886    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7887            String packageOfInterest) {
7888        // IMPORTANT: There are two types of permissions: install and runtime.
7889        // Install time permissions are granted when the app is installed to
7890        // all device users and users added in the future. Runtime permissions
7891        // are granted at runtime explicitly to specific users. Normal and signature
7892        // protected permissions are install time permissions. Dangerous permissions
7893        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7894        // otherwise they are runtime permissions. This function does not manage
7895        // runtime permissions except for the case an app targeting Lollipop MR1
7896        // being upgraded to target a newer SDK, in which case dangerous permissions
7897        // are transformed from install time to runtime ones.
7898
7899        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7900        if (ps == null) {
7901            return;
7902        }
7903
7904        PermissionsState permissionsState = ps.getPermissionsState();
7905        PermissionsState origPermissions = permissionsState;
7906
7907        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7908
7909        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
7910
7911        boolean changedInstallPermission = false;
7912
7913        if (replace) {
7914            ps.installPermissionsFixed = false;
7915            if (!ps.isSharedUser()) {
7916                origPermissions = new PermissionsState(permissionsState);
7917                permissionsState.reset();
7918            }
7919        }
7920
7921        permissionsState.setGlobalGids(mGlobalGids);
7922
7923        final int N = pkg.requestedPermissions.size();
7924        for (int i=0; i<N; i++) {
7925            final String name = pkg.requestedPermissions.get(i);
7926            final BasePermission bp = mSettings.mPermissions.get(name);
7927
7928            if (DEBUG_INSTALL) {
7929                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7930            }
7931
7932            if (bp == null || bp.packageSetting == null) {
7933                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7934                    Slog.w(TAG, "Unknown permission " + name
7935                            + " in package " + pkg.packageName);
7936                }
7937                continue;
7938            }
7939
7940            final String perm = bp.name;
7941            boolean allowedSig = false;
7942            int grant = GRANT_DENIED;
7943
7944            // Keep track of app op permissions.
7945            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7946                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7947                if (pkgs == null) {
7948                    pkgs = new ArraySet<>();
7949                    mAppOpPermissionPackages.put(bp.name, pkgs);
7950                }
7951                pkgs.add(pkg.packageName);
7952            }
7953
7954            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7955            switch (level) {
7956                case PermissionInfo.PROTECTION_NORMAL: {
7957                    // For all apps normal permissions are install time ones.
7958                    grant = GRANT_INSTALL;
7959                } break;
7960
7961                case PermissionInfo.PROTECTION_DANGEROUS: {
7962                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7963                        // For legacy apps dangerous permissions are install time ones.
7964                        grant = GRANT_INSTALL_LEGACY;
7965                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7966                        // For legacy apps that became modern, install becomes runtime.
7967                        grant = GRANT_UPGRADE;
7968                    } else {
7969                        // For modern apps keep runtime permissions unchanged.
7970                        grant = GRANT_RUNTIME;
7971                    }
7972                } break;
7973
7974                case PermissionInfo.PROTECTION_SIGNATURE: {
7975                    // For all apps signature permissions are install time ones.
7976                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7977                    if (allowedSig) {
7978                        grant = GRANT_INSTALL;
7979                    }
7980                } break;
7981            }
7982
7983            if (DEBUG_INSTALL) {
7984                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7985            }
7986
7987            if (grant != GRANT_DENIED) {
7988                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7989                    // If this is an existing, non-system package, then
7990                    // we can't add any new permissions to it.
7991                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7992                        // Except...  if this is a permission that was added
7993                        // to the platform (note: need to only do this when
7994                        // updating the platform).
7995                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7996                            grant = GRANT_DENIED;
7997                        }
7998                    }
7999                }
8000
8001                switch (grant) {
8002                    case GRANT_INSTALL: {
8003                        // Revoke this as runtime permission to handle the case of
8004                        // a runtime permission being downgraded to an install one.
8005                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8006                            if (origPermissions.getRuntimePermissionState(
8007                                    bp.name, userId) != null) {
8008                                // Revoke the runtime permission and clear the flags.
8009                                origPermissions.revokeRuntimePermission(bp, userId);
8010                                origPermissions.updatePermissionFlags(bp, userId,
8011                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8012                                // If we revoked a permission permission, we have to write.
8013                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8014                                        changedRuntimePermissionUserIds, userId);
8015                            }
8016                        }
8017                        // Grant an install permission.
8018                        if (permissionsState.grantInstallPermission(bp) !=
8019                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8020                            changedInstallPermission = true;
8021                        }
8022                    } break;
8023
8024                    case GRANT_INSTALL_LEGACY: {
8025                        // Grant an install permission.
8026                        if (permissionsState.grantInstallPermission(bp) !=
8027                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8028                            changedInstallPermission = true;
8029                        }
8030                    } break;
8031
8032                    case GRANT_RUNTIME: {
8033                        // Grant previously granted runtime permissions.
8034                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8035                            PermissionState permissionState = origPermissions
8036                                    .getRuntimePermissionState(bp.name, userId);
8037                            final int flags = permissionState != null
8038                                    ? permissionState.getFlags() : 0;
8039                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8040                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8041                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8042                                    // If we cannot put the permission as it was, we have to write.
8043                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8044                                            changedRuntimePermissionUserIds, userId);
8045                                }
8046                            }
8047                            // Propagate the permission flags.
8048                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8049                        }
8050                    } break;
8051
8052                    case GRANT_UPGRADE: {
8053                        // Grant runtime permissions for a previously held install permission.
8054                        PermissionState permissionState = origPermissions
8055                                .getInstallPermissionState(bp.name);
8056                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8057
8058                        if (origPermissions.revokeInstallPermission(bp)
8059                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8060                            // We will be transferring the permission flags, so clear them.
8061                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8062                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8063                            changedInstallPermission = true;
8064                        }
8065
8066                        // If the permission is not to be promoted to runtime we ignore it and
8067                        // also its other flags as they are not applicable to install permissions.
8068                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8069                            for (int userId : currentUserIds) {
8070                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8071                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8072                                    // Transfer the permission flags.
8073                                    permissionsState.updatePermissionFlags(bp, userId,
8074                                            flags, flags);
8075                                    // If we granted the permission, we have to write.
8076                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8077                                            changedRuntimePermissionUserIds, userId);
8078                                }
8079                            }
8080                        }
8081                    } break;
8082
8083                    default: {
8084                        if (packageOfInterest == null
8085                                || packageOfInterest.equals(pkg.packageName)) {
8086                            Slog.w(TAG, "Not granting permission " + perm
8087                                    + " to package " + pkg.packageName
8088                                    + " because it was previously installed without");
8089                        }
8090                    } break;
8091                }
8092            } else {
8093                if (permissionsState.revokeInstallPermission(bp) !=
8094                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8095                    // Also drop the permission flags.
8096                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8097                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8098                    changedInstallPermission = true;
8099                    Slog.i(TAG, "Un-granting permission " + perm
8100                            + " from package " + pkg.packageName
8101                            + " (protectionLevel=" + bp.protectionLevel
8102                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8103                            + ")");
8104                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8105                    // Don't print warning for app op permissions, since it is fine for them
8106                    // not to be granted, there is a UI for the user to decide.
8107                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8108                        Slog.w(TAG, "Not granting permission " + perm
8109                                + " to package " + pkg.packageName
8110                                + " (protectionLevel=" + bp.protectionLevel
8111                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8112                                + ")");
8113                    }
8114                }
8115            }
8116        }
8117
8118        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8119                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8120            // This is the first that we have heard about this package, so the
8121            // permissions we have now selected are fixed until explicitly
8122            // changed.
8123            ps.installPermissionsFixed = true;
8124        }
8125
8126        // Persist the runtime permissions state for users with changes.
8127        for (int userId : changedRuntimePermissionUserIds) {
8128            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8129        }
8130    }
8131
8132    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8133        boolean allowed = false;
8134        final int NP = PackageParser.NEW_PERMISSIONS.length;
8135        for (int ip=0; ip<NP; ip++) {
8136            final PackageParser.NewPermissionInfo npi
8137                    = PackageParser.NEW_PERMISSIONS[ip];
8138            if (npi.name.equals(perm)
8139                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8140                allowed = true;
8141                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8142                        + pkg.packageName);
8143                break;
8144            }
8145        }
8146        return allowed;
8147    }
8148
8149    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8150            BasePermission bp, PermissionsState origPermissions) {
8151        boolean allowed;
8152        allowed = (compareSignatures(
8153                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8154                        == PackageManager.SIGNATURE_MATCH)
8155                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8156                        == PackageManager.SIGNATURE_MATCH);
8157        if (!allowed && (bp.protectionLevel
8158                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
8159            if (isSystemApp(pkg)) {
8160                // For updated system applications, a system permission
8161                // is granted only if it had been defined by the original application.
8162                if (pkg.isUpdatedSystemApp()) {
8163                    final PackageSetting sysPs = mSettings
8164                            .getDisabledSystemPkgLPr(pkg.packageName);
8165                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8166                        // If the original was granted this permission, we take
8167                        // that grant decision as read and propagate it to the
8168                        // update.
8169                        if (sysPs.isPrivileged()) {
8170                            allowed = true;
8171                        }
8172                    } else {
8173                        // The system apk may have been updated with an older
8174                        // version of the one on the data partition, but which
8175                        // granted a new system permission that it didn't have
8176                        // before.  In this case we do want to allow the app to
8177                        // now get the new permission if the ancestral apk is
8178                        // privileged to get it.
8179                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8180                            for (int j=0;
8181                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8182                                if (perm.equals(
8183                                        sysPs.pkg.requestedPermissions.get(j))) {
8184                                    allowed = true;
8185                                    break;
8186                                }
8187                            }
8188                        }
8189                    }
8190                } else {
8191                    allowed = isPrivilegedApp(pkg);
8192                }
8193            }
8194        }
8195        if (!allowed && (bp.protectionLevel
8196                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8197            // For development permissions, a development permission
8198            // is granted only if it was already granted.
8199            allowed = origPermissions.hasInstallPermission(perm);
8200        }
8201        return allowed;
8202    }
8203
8204    final class ActivityIntentResolver
8205            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8206        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8207                boolean defaultOnly, int userId) {
8208            if (!sUserManager.exists(userId)) return null;
8209            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8210            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8211        }
8212
8213        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8214                int userId) {
8215            if (!sUserManager.exists(userId)) return null;
8216            mFlags = flags;
8217            return super.queryIntent(intent, resolvedType,
8218                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8219        }
8220
8221        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8222                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8223            if (!sUserManager.exists(userId)) return null;
8224            if (packageActivities == null) {
8225                return null;
8226            }
8227            mFlags = flags;
8228            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8229            final int N = packageActivities.size();
8230            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8231                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8232
8233            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8234            for (int i = 0; i < N; ++i) {
8235                intentFilters = packageActivities.get(i).intents;
8236                if (intentFilters != null && intentFilters.size() > 0) {
8237                    PackageParser.ActivityIntentInfo[] array =
8238                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8239                    intentFilters.toArray(array);
8240                    listCut.add(array);
8241                }
8242            }
8243            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8244        }
8245
8246        public final void addActivity(PackageParser.Activity a, String type) {
8247            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8248            mActivities.put(a.getComponentName(), a);
8249            if (DEBUG_SHOW_INFO)
8250                Log.v(
8251                TAG, "  " + type + " " +
8252                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8253            if (DEBUG_SHOW_INFO)
8254                Log.v(TAG, "    Class=" + a.info.name);
8255            final int NI = a.intents.size();
8256            for (int j=0; j<NI; j++) {
8257                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8258                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8259                    intent.setPriority(0);
8260                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8261                            + a.className + " with priority > 0, forcing to 0");
8262                }
8263                if (DEBUG_SHOW_INFO) {
8264                    Log.v(TAG, "    IntentFilter:");
8265                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8266                }
8267                if (!intent.debugCheck()) {
8268                    Log.w(TAG, "==> For Activity " + a.info.name);
8269                }
8270                addFilter(intent);
8271            }
8272        }
8273
8274        public final void removeActivity(PackageParser.Activity a, String type) {
8275            mActivities.remove(a.getComponentName());
8276            if (DEBUG_SHOW_INFO) {
8277                Log.v(TAG, "  " + type + " "
8278                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8279                                : a.info.name) + ":");
8280                Log.v(TAG, "    Class=" + a.info.name);
8281            }
8282            final int NI = a.intents.size();
8283            for (int j=0; j<NI; j++) {
8284                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8285                if (DEBUG_SHOW_INFO) {
8286                    Log.v(TAG, "    IntentFilter:");
8287                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8288                }
8289                removeFilter(intent);
8290            }
8291        }
8292
8293        @Override
8294        protected boolean allowFilterResult(
8295                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8296            ActivityInfo filterAi = filter.activity.info;
8297            for (int i=dest.size()-1; i>=0; i--) {
8298                ActivityInfo destAi = dest.get(i).activityInfo;
8299                if (destAi.name == filterAi.name
8300                        && destAi.packageName == filterAi.packageName) {
8301                    return false;
8302                }
8303            }
8304            return true;
8305        }
8306
8307        @Override
8308        protected ActivityIntentInfo[] newArray(int size) {
8309            return new ActivityIntentInfo[size];
8310        }
8311
8312        @Override
8313        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8314            if (!sUserManager.exists(userId)) return true;
8315            PackageParser.Package p = filter.activity.owner;
8316            if (p != null) {
8317                PackageSetting ps = (PackageSetting)p.mExtras;
8318                if (ps != null) {
8319                    // System apps are never considered stopped for purposes of
8320                    // filtering, because there may be no way for the user to
8321                    // actually re-launch them.
8322                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8323                            && ps.getStopped(userId);
8324                }
8325            }
8326            return false;
8327        }
8328
8329        @Override
8330        protected boolean isPackageForFilter(String packageName,
8331                PackageParser.ActivityIntentInfo info) {
8332            return packageName.equals(info.activity.owner.packageName);
8333        }
8334
8335        @Override
8336        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8337                int match, int userId) {
8338            if (!sUserManager.exists(userId)) return null;
8339            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8340                return null;
8341            }
8342            final PackageParser.Activity activity = info.activity;
8343            if (mSafeMode && (activity.info.applicationInfo.flags
8344                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8345                return null;
8346            }
8347            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8348            if (ps == null) {
8349                return null;
8350            }
8351            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8352                    ps.readUserState(userId), userId);
8353            if (ai == null) {
8354                return null;
8355            }
8356            final ResolveInfo res = new ResolveInfo();
8357            res.activityInfo = ai;
8358            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8359                res.filter = info;
8360            }
8361            if (info != null) {
8362                res.handleAllWebDataURI = info.handleAllWebDataURI();
8363            }
8364            res.priority = info.getPriority();
8365            res.preferredOrder = activity.owner.mPreferredOrder;
8366            //System.out.println("Result: " + res.activityInfo.className +
8367            //                   " = " + res.priority);
8368            res.match = match;
8369            res.isDefault = info.hasDefault;
8370            res.labelRes = info.labelRes;
8371            res.nonLocalizedLabel = info.nonLocalizedLabel;
8372            if (userNeedsBadging(userId)) {
8373                res.noResourceId = true;
8374            } else {
8375                res.icon = info.icon;
8376            }
8377            res.iconResourceId = info.icon;
8378            res.system = res.activityInfo.applicationInfo.isSystemApp();
8379            return res;
8380        }
8381
8382        @Override
8383        protected void sortResults(List<ResolveInfo> results) {
8384            Collections.sort(results, mResolvePrioritySorter);
8385        }
8386
8387        @Override
8388        protected void dumpFilter(PrintWriter out, String prefix,
8389                PackageParser.ActivityIntentInfo filter) {
8390            out.print(prefix); out.print(
8391                    Integer.toHexString(System.identityHashCode(filter.activity)));
8392                    out.print(' ');
8393                    filter.activity.printComponentShortName(out);
8394                    out.print(" filter ");
8395                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8396        }
8397
8398        @Override
8399        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8400            return filter.activity;
8401        }
8402
8403        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8404            PackageParser.Activity activity = (PackageParser.Activity)label;
8405            out.print(prefix); out.print(
8406                    Integer.toHexString(System.identityHashCode(activity)));
8407                    out.print(' ');
8408                    activity.printComponentShortName(out);
8409            if (count > 1) {
8410                out.print(" ("); out.print(count); out.print(" filters)");
8411            }
8412            out.println();
8413        }
8414
8415//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8416//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8417//            final List<ResolveInfo> retList = Lists.newArrayList();
8418//            while (i.hasNext()) {
8419//                final ResolveInfo resolveInfo = i.next();
8420//                if (isEnabledLP(resolveInfo.activityInfo)) {
8421//                    retList.add(resolveInfo);
8422//                }
8423//            }
8424//            return retList;
8425//        }
8426
8427        // Keys are String (activity class name), values are Activity.
8428        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8429                = new ArrayMap<ComponentName, PackageParser.Activity>();
8430        private int mFlags;
8431    }
8432
8433    private final class ServiceIntentResolver
8434            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8435        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8436                boolean defaultOnly, int userId) {
8437            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8438            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8439        }
8440
8441        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8442                int userId) {
8443            if (!sUserManager.exists(userId)) return null;
8444            mFlags = flags;
8445            return super.queryIntent(intent, resolvedType,
8446                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8447        }
8448
8449        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8450                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8451            if (!sUserManager.exists(userId)) return null;
8452            if (packageServices == null) {
8453                return null;
8454            }
8455            mFlags = flags;
8456            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8457            final int N = packageServices.size();
8458            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8459                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8460
8461            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8462            for (int i = 0; i < N; ++i) {
8463                intentFilters = packageServices.get(i).intents;
8464                if (intentFilters != null && intentFilters.size() > 0) {
8465                    PackageParser.ServiceIntentInfo[] array =
8466                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8467                    intentFilters.toArray(array);
8468                    listCut.add(array);
8469                }
8470            }
8471            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8472        }
8473
8474        public final void addService(PackageParser.Service s) {
8475            mServices.put(s.getComponentName(), s);
8476            if (DEBUG_SHOW_INFO) {
8477                Log.v(TAG, "  "
8478                        + (s.info.nonLocalizedLabel != null
8479                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8480                Log.v(TAG, "    Class=" + s.info.name);
8481            }
8482            final int NI = s.intents.size();
8483            int j;
8484            for (j=0; j<NI; j++) {
8485                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8486                if (DEBUG_SHOW_INFO) {
8487                    Log.v(TAG, "    IntentFilter:");
8488                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8489                }
8490                if (!intent.debugCheck()) {
8491                    Log.w(TAG, "==> For Service " + s.info.name);
8492                }
8493                addFilter(intent);
8494            }
8495        }
8496
8497        public final void removeService(PackageParser.Service s) {
8498            mServices.remove(s.getComponentName());
8499            if (DEBUG_SHOW_INFO) {
8500                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8501                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8502                Log.v(TAG, "    Class=" + s.info.name);
8503            }
8504            final int NI = s.intents.size();
8505            int j;
8506            for (j=0; j<NI; j++) {
8507                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8508                if (DEBUG_SHOW_INFO) {
8509                    Log.v(TAG, "    IntentFilter:");
8510                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8511                }
8512                removeFilter(intent);
8513            }
8514        }
8515
8516        @Override
8517        protected boolean allowFilterResult(
8518                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8519            ServiceInfo filterSi = filter.service.info;
8520            for (int i=dest.size()-1; i>=0; i--) {
8521                ServiceInfo destAi = dest.get(i).serviceInfo;
8522                if (destAi.name == filterSi.name
8523                        && destAi.packageName == filterSi.packageName) {
8524                    return false;
8525                }
8526            }
8527            return true;
8528        }
8529
8530        @Override
8531        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8532            return new PackageParser.ServiceIntentInfo[size];
8533        }
8534
8535        @Override
8536        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8537            if (!sUserManager.exists(userId)) return true;
8538            PackageParser.Package p = filter.service.owner;
8539            if (p != null) {
8540                PackageSetting ps = (PackageSetting)p.mExtras;
8541                if (ps != null) {
8542                    // System apps are never considered stopped for purposes of
8543                    // filtering, because there may be no way for the user to
8544                    // actually re-launch them.
8545                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8546                            && ps.getStopped(userId);
8547                }
8548            }
8549            return false;
8550        }
8551
8552        @Override
8553        protected boolean isPackageForFilter(String packageName,
8554                PackageParser.ServiceIntentInfo info) {
8555            return packageName.equals(info.service.owner.packageName);
8556        }
8557
8558        @Override
8559        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8560                int match, int userId) {
8561            if (!sUserManager.exists(userId)) return null;
8562            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8563            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8564                return null;
8565            }
8566            final PackageParser.Service service = info.service;
8567            if (mSafeMode && (service.info.applicationInfo.flags
8568                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8569                return null;
8570            }
8571            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8572            if (ps == null) {
8573                return null;
8574            }
8575            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8576                    ps.readUserState(userId), userId);
8577            if (si == null) {
8578                return null;
8579            }
8580            final ResolveInfo res = new ResolveInfo();
8581            res.serviceInfo = si;
8582            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8583                res.filter = filter;
8584            }
8585            res.priority = info.getPriority();
8586            res.preferredOrder = service.owner.mPreferredOrder;
8587            res.match = match;
8588            res.isDefault = info.hasDefault;
8589            res.labelRes = info.labelRes;
8590            res.nonLocalizedLabel = info.nonLocalizedLabel;
8591            res.icon = info.icon;
8592            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8593            return res;
8594        }
8595
8596        @Override
8597        protected void sortResults(List<ResolveInfo> results) {
8598            Collections.sort(results, mResolvePrioritySorter);
8599        }
8600
8601        @Override
8602        protected void dumpFilter(PrintWriter out, String prefix,
8603                PackageParser.ServiceIntentInfo filter) {
8604            out.print(prefix); out.print(
8605                    Integer.toHexString(System.identityHashCode(filter.service)));
8606                    out.print(' ');
8607                    filter.service.printComponentShortName(out);
8608                    out.print(" filter ");
8609                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8610        }
8611
8612        @Override
8613        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8614            return filter.service;
8615        }
8616
8617        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8618            PackageParser.Service service = (PackageParser.Service)label;
8619            out.print(prefix); out.print(
8620                    Integer.toHexString(System.identityHashCode(service)));
8621                    out.print(' ');
8622                    service.printComponentShortName(out);
8623            if (count > 1) {
8624                out.print(" ("); out.print(count); out.print(" filters)");
8625            }
8626            out.println();
8627        }
8628
8629//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8630//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8631//            final List<ResolveInfo> retList = Lists.newArrayList();
8632//            while (i.hasNext()) {
8633//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8634//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8635//                    retList.add(resolveInfo);
8636//                }
8637//            }
8638//            return retList;
8639//        }
8640
8641        // Keys are String (activity class name), values are Activity.
8642        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8643                = new ArrayMap<ComponentName, PackageParser.Service>();
8644        private int mFlags;
8645    };
8646
8647    private final class ProviderIntentResolver
8648            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8649        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8650                boolean defaultOnly, int userId) {
8651            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8652            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8653        }
8654
8655        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8656                int userId) {
8657            if (!sUserManager.exists(userId))
8658                return null;
8659            mFlags = flags;
8660            return super.queryIntent(intent, resolvedType,
8661                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8662        }
8663
8664        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8665                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8666            if (!sUserManager.exists(userId))
8667                return null;
8668            if (packageProviders == null) {
8669                return null;
8670            }
8671            mFlags = flags;
8672            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8673            final int N = packageProviders.size();
8674            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8675                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8676
8677            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8678            for (int i = 0; i < N; ++i) {
8679                intentFilters = packageProviders.get(i).intents;
8680                if (intentFilters != null && intentFilters.size() > 0) {
8681                    PackageParser.ProviderIntentInfo[] array =
8682                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8683                    intentFilters.toArray(array);
8684                    listCut.add(array);
8685                }
8686            }
8687            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8688        }
8689
8690        public final void addProvider(PackageParser.Provider p) {
8691            if (mProviders.containsKey(p.getComponentName())) {
8692                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8693                return;
8694            }
8695
8696            mProviders.put(p.getComponentName(), p);
8697            if (DEBUG_SHOW_INFO) {
8698                Log.v(TAG, "  "
8699                        + (p.info.nonLocalizedLabel != null
8700                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8701                Log.v(TAG, "    Class=" + p.info.name);
8702            }
8703            final int NI = p.intents.size();
8704            int j;
8705            for (j = 0; j < NI; j++) {
8706                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8707                if (DEBUG_SHOW_INFO) {
8708                    Log.v(TAG, "    IntentFilter:");
8709                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8710                }
8711                if (!intent.debugCheck()) {
8712                    Log.w(TAG, "==> For Provider " + p.info.name);
8713                }
8714                addFilter(intent);
8715            }
8716        }
8717
8718        public final void removeProvider(PackageParser.Provider p) {
8719            mProviders.remove(p.getComponentName());
8720            if (DEBUG_SHOW_INFO) {
8721                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8722                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8723                Log.v(TAG, "    Class=" + p.info.name);
8724            }
8725            final int NI = p.intents.size();
8726            int j;
8727            for (j = 0; j < NI; j++) {
8728                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8729                if (DEBUG_SHOW_INFO) {
8730                    Log.v(TAG, "    IntentFilter:");
8731                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8732                }
8733                removeFilter(intent);
8734            }
8735        }
8736
8737        @Override
8738        protected boolean allowFilterResult(
8739                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8740            ProviderInfo filterPi = filter.provider.info;
8741            for (int i = dest.size() - 1; i >= 0; i--) {
8742                ProviderInfo destPi = dest.get(i).providerInfo;
8743                if (destPi.name == filterPi.name
8744                        && destPi.packageName == filterPi.packageName) {
8745                    return false;
8746                }
8747            }
8748            return true;
8749        }
8750
8751        @Override
8752        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8753            return new PackageParser.ProviderIntentInfo[size];
8754        }
8755
8756        @Override
8757        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8758            if (!sUserManager.exists(userId))
8759                return true;
8760            PackageParser.Package p = filter.provider.owner;
8761            if (p != null) {
8762                PackageSetting ps = (PackageSetting) p.mExtras;
8763                if (ps != null) {
8764                    // System apps are never considered stopped for purposes of
8765                    // filtering, because there may be no way for the user to
8766                    // actually re-launch them.
8767                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8768                            && ps.getStopped(userId);
8769                }
8770            }
8771            return false;
8772        }
8773
8774        @Override
8775        protected boolean isPackageForFilter(String packageName,
8776                PackageParser.ProviderIntentInfo info) {
8777            return packageName.equals(info.provider.owner.packageName);
8778        }
8779
8780        @Override
8781        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8782                int match, int userId) {
8783            if (!sUserManager.exists(userId))
8784                return null;
8785            final PackageParser.ProviderIntentInfo info = filter;
8786            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8787                return null;
8788            }
8789            final PackageParser.Provider provider = info.provider;
8790            if (mSafeMode && (provider.info.applicationInfo.flags
8791                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8792                return null;
8793            }
8794            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8795            if (ps == null) {
8796                return null;
8797            }
8798            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8799                    ps.readUserState(userId), userId);
8800            if (pi == null) {
8801                return null;
8802            }
8803            final ResolveInfo res = new ResolveInfo();
8804            res.providerInfo = pi;
8805            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8806                res.filter = filter;
8807            }
8808            res.priority = info.getPriority();
8809            res.preferredOrder = provider.owner.mPreferredOrder;
8810            res.match = match;
8811            res.isDefault = info.hasDefault;
8812            res.labelRes = info.labelRes;
8813            res.nonLocalizedLabel = info.nonLocalizedLabel;
8814            res.icon = info.icon;
8815            res.system = res.providerInfo.applicationInfo.isSystemApp();
8816            return res;
8817        }
8818
8819        @Override
8820        protected void sortResults(List<ResolveInfo> results) {
8821            Collections.sort(results, mResolvePrioritySorter);
8822        }
8823
8824        @Override
8825        protected void dumpFilter(PrintWriter out, String prefix,
8826                PackageParser.ProviderIntentInfo filter) {
8827            out.print(prefix);
8828            out.print(
8829                    Integer.toHexString(System.identityHashCode(filter.provider)));
8830            out.print(' ');
8831            filter.provider.printComponentShortName(out);
8832            out.print(" filter ");
8833            out.println(Integer.toHexString(System.identityHashCode(filter)));
8834        }
8835
8836        @Override
8837        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8838            return filter.provider;
8839        }
8840
8841        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8842            PackageParser.Provider provider = (PackageParser.Provider)label;
8843            out.print(prefix); out.print(
8844                    Integer.toHexString(System.identityHashCode(provider)));
8845                    out.print(' ');
8846                    provider.printComponentShortName(out);
8847            if (count > 1) {
8848                out.print(" ("); out.print(count); out.print(" filters)");
8849            }
8850            out.println();
8851        }
8852
8853        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8854                = new ArrayMap<ComponentName, PackageParser.Provider>();
8855        private int mFlags;
8856    };
8857
8858    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8859            new Comparator<ResolveInfo>() {
8860        public int compare(ResolveInfo r1, ResolveInfo r2) {
8861            int v1 = r1.priority;
8862            int v2 = r2.priority;
8863            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8864            if (v1 != v2) {
8865                return (v1 > v2) ? -1 : 1;
8866            }
8867            v1 = r1.preferredOrder;
8868            v2 = r2.preferredOrder;
8869            if (v1 != v2) {
8870                return (v1 > v2) ? -1 : 1;
8871            }
8872            if (r1.isDefault != r2.isDefault) {
8873                return r1.isDefault ? -1 : 1;
8874            }
8875            v1 = r1.match;
8876            v2 = r2.match;
8877            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8878            if (v1 != v2) {
8879                return (v1 > v2) ? -1 : 1;
8880            }
8881            if (r1.system != r2.system) {
8882                return r1.system ? -1 : 1;
8883            }
8884            return 0;
8885        }
8886    };
8887
8888    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8889            new Comparator<ProviderInfo>() {
8890        public int compare(ProviderInfo p1, ProviderInfo p2) {
8891            final int v1 = p1.initOrder;
8892            final int v2 = p2.initOrder;
8893            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8894        }
8895    };
8896
8897    final void sendPackageBroadcast(final String action, final String pkg,
8898            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
8899            final int[] userIds) {
8900        mHandler.post(new Runnable() {
8901            @Override
8902            public void run() {
8903                try {
8904                    final IActivityManager am = ActivityManagerNative.getDefault();
8905                    if (am == null) return;
8906                    final int[] resolvedUserIds;
8907                    if (userIds == null) {
8908                        resolvedUserIds = am.getRunningUserIds();
8909                    } else {
8910                        resolvedUserIds = userIds;
8911                    }
8912                    for (int id : resolvedUserIds) {
8913                        final Intent intent = new Intent(action,
8914                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
8915                        if (extras != null) {
8916                            intent.putExtras(extras);
8917                        }
8918                        if (targetPkg != null) {
8919                            intent.setPackage(targetPkg);
8920                        }
8921                        // Modify the UID when posting to other users
8922                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8923                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
8924                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8925                            intent.putExtra(Intent.EXTRA_UID, uid);
8926                        }
8927                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8928                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8929                        if (DEBUG_BROADCASTS) {
8930                            RuntimeException here = new RuntimeException("here");
8931                            here.fillInStackTrace();
8932                            Slog.d(TAG, "Sending to user " + id + ": "
8933                                    + intent.toShortString(false, true, false, false)
8934                                    + " " + intent.getExtras(), here);
8935                        }
8936                        am.broadcastIntent(null, intent, null, finishedReceiver,
8937                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
8938                                null, finishedReceiver != null, false, id);
8939                    }
8940                } catch (RemoteException ex) {
8941                }
8942            }
8943        });
8944    }
8945
8946    /**
8947     * Check if the external storage media is available. This is true if there
8948     * is a mounted external storage medium or if the external storage is
8949     * emulated.
8950     */
8951    private boolean isExternalMediaAvailable() {
8952        return mMediaMounted || Environment.isExternalStorageEmulated();
8953    }
8954
8955    @Override
8956    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8957        // writer
8958        synchronized (mPackages) {
8959            if (!isExternalMediaAvailable()) {
8960                // If the external storage is no longer mounted at this point,
8961                // the caller may not have been able to delete all of this
8962                // packages files and can not delete any more.  Bail.
8963                return null;
8964            }
8965            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8966            if (lastPackage != null) {
8967                pkgs.remove(lastPackage);
8968            }
8969            if (pkgs.size() > 0) {
8970                return pkgs.get(0);
8971            }
8972        }
8973        return null;
8974    }
8975
8976    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8977        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8978                userId, andCode ? 1 : 0, packageName);
8979        if (mSystemReady) {
8980            msg.sendToTarget();
8981        } else {
8982            if (mPostSystemReadyMessages == null) {
8983                mPostSystemReadyMessages = new ArrayList<>();
8984            }
8985            mPostSystemReadyMessages.add(msg);
8986        }
8987    }
8988
8989    void startCleaningPackages() {
8990        // reader
8991        synchronized (mPackages) {
8992            if (!isExternalMediaAvailable()) {
8993                return;
8994            }
8995            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8996                return;
8997            }
8998        }
8999        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9000        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9001        IActivityManager am = ActivityManagerNative.getDefault();
9002        if (am != null) {
9003            try {
9004                am.startService(null, intent, null, UserHandle.USER_OWNER);
9005            } catch (RemoteException e) {
9006            }
9007        }
9008    }
9009
9010    @Override
9011    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9012            int installFlags, String installerPackageName, VerificationParams verificationParams,
9013            String packageAbiOverride) {
9014        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9015                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9016    }
9017
9018    @Override
9019    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9020            int installFlags, String installerPackageName, VerificationParams verificationParams,
9021            String packageAbiOverride, int userId) {
9022        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9023
9024        final int callingUid = Binder.getCallingUid();
9025        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9026
9027        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9028            try {
9029                if (observer != null) {
9030                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9031                }
9032            } catch (RemoteException re) {
9033            }
9034            return;
9035        }
9036
9037        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9038            installFlags |= PackageManager.INSTALL_FROM_ADB;
9039
9040        } else {
9041            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9042            // about installerPackageName.
9043
9044            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9045            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9046        }
9047
9048        UserHandle user;
9049        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9050            user = UserHandle.ALL;
9051        } else {
9052            user = new UserHandle(userId);
9053        }
9054
9055        // Only system components can circumvent runtime permissions when installing.
9056        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9057                && mContext.checkCallingOrSelfPermission(Manifest.permission
9058                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9059            throw new SecurityException("You need the "
9060                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9061                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9062        }
9063
9064        verificationParams.setInstallerUid(callingUid);
9065
9066        final File originFile = new File(originPath);
9067        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9068
9069        final Message msg = mHandler.obtainMessage(INIT_COPY);
9070        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9071                null, verificationParams, user, packageAbiOverride);
9072        mHandler.sendMessage(msg);
9073    }
9074
9075    void installStage(String packageName, File stagedDir, String stagedCid,
9076            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9077            String installerPackageName, int installerUid, UserHandle user) {
9078        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9079                params.referrerUri, installerUid, null);
9080
9081        final OriginInfo origin;
9082        if (stagedDir != null) {
9083            origin = OriginInfo.fromStagedFile(stagedDir);
9084        } else {
9085            origin = OriginInfo.fromStagedContainer(stagedCid);
9086        }
9087
9088        final Message msg = mHandler.obtainMessage(INIT_COPY);
9089        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9090                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9091        mHandler.sendMessage(msg);
9092    }
9093
9094    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9095        Bundle extras = new Bundle(1);
9096        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9097
9098        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9099                packageName, extras, null, null, new int[] {userId});
9100        try {
9101            IActivityManager am = ActivityManagerNative.getDefault();
9102            final boolean isSystem =
9103                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9104            if (isSystem && am.isUserRunning(userId, false)) {
9105                // The just-installed/enabled app is bundled on the system, so presumed
9106                // to be able to run automatically without needing an explicit launch.
9107                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9108                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9109                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9110                        .setPackage(packageName);
9111                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9112                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9113            }
9114        } catch (RemoteException e) {
9115            // shouldn't happen
9116            Slog.w(TAG, "Unable to bootstrap installed package", e);
9117        }
9118    }
9119
9120    @Override
9121    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9122            int userId) {
9123        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9124        PackageSetting pkgSetting;
9125        final int uid = Binder.getCallingUid();
9126        enforceCrossUserPermission(uid, userId, true, true,
9127                "setApplicationHiddenSetting for user " + userId);
9128
9129        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9130            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9131            return false;
9132        }
9133
9134        long callingId = Binder.clearCallingIdentity();
9135        try {
9136            boolean sendAdded = false;
9137            boolean sendRemoved = false;
9138            // writer
9139            synchronized (mPackages) {
9140                pkgSetting = mSettings.mPackages.get(packageName);
9141                if (pkgSetting == null) {
9142                    return false;
9143                }
9144                if (pkgSetting.getHidden(userId) != hidden) {
9145                    pkgSetting.setHidden(hidden, userId);
9146                    mSettings.writePackageRestrictionsLPr(userId);
9147                    if (hidden) {
9148                        sendRemoved = true;
9149                    } else {
9150                        sendAdded = true;
9151                    }
9152                }
9153            }
9154            if (sendAdded) {
9155                sendPackageAddedForUser(packageName, pkgSetting, userId);
9156                return true;
9157            }
9158            if (sendRemoved) {
9159                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9160                        "hiding pkg");
9161                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9162            }
9163        } finally {
9164            Binder.restoreCallingIdentity(callingId);
9165        }
9166        return false;
9167    }
9168
9169    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9170            int userId) {
9171        final PackageRemovedInfo info = new PackageRemovedInfo();
9172        info.removedPackage = packageName;
9173        info.removedUsers = new int[] {userId};
9174        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9175        info.sendBroadcast(false, false, false);
9176    }
9177
9178    /**
9179     * Returns true if application is not found or there was an error. Otherwise it returns
9180     * the hidden state of the package for the given user.
9181     */
9182    @Override
9183    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9184        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9185        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9186                false, "getApplicationHidden for user " + userId);
9187        PackageSetting pkgSetting;
9188        long callingId = Binder.clearCallingIdentity();
9189        try {
9190            // writer
9191            synchronized (mPackages) {
9192                pkgSetting = mSettings.mPackages.get(packageName);
9193                if (pkgSetting == null) {
9194                    return true;
9195                }
9196                return pkgSetting.getHidden(userId);
9197            }
9198        } finally {
9199            Binder.restoreCallingIdentity(callingId);
9200        }
9201    }
9202
9203    /**
9204     * @hide
9205     */
9206    @Override
9207    public int installExistingPackageAsUser(String packageName, int userId) {
9208        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9209                null);
9210        PackageSetting pkgSetting;
9211        final int uid = Binder.getCallingUid();
9212        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9213                + userId);
9214        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9215            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9216        }
9217
9218        long callingId = Binder.clearCallingIdentity();
9219        try {
9220            boolean sendAdded = false;
9221
9222            // writer
9223            synchronized (mPackages) {
9224                pkgSetting = mSettings.mPackages.get(packageName);
9225                if (pkgSetting == null) {
9226                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9227                }
9228                if (!pkgSetting.getInstalled(userId)) {
9229                    pkgSetting.setInstalled(true, userId);
9230                    pkgSetting.setHidden(false, userId);
9231                    mSettings.writePackageRestrictionsLPr(userId);
9232                    sendAdded = true;
9233                }
9234            }
9235
9236            if (sendAdded) {
9237                sendPackageAddedForUser(packageName, pkgSetting, userId);
9238            }
9239        } finally {
9240            Binder.restoreCallingIdentity(callingId);
9241        }
9242
9243        return PackageManager.INSTALL_SUCCEEDED;
9244    }
9245
9246    boolean isUserRestricted(int userId, String restrictionKey) {
9247        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9248        if (restrictions.getBoolean(restrictionKey, false)) {
9249            Log.w(TAG, "User is restricted: " + restrictionKey);
9250            return true;
9251        }
9252        return false;
9253    }
9254
9255    @Override
9256    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9257        mContext.enforceCallingOrSelfPermission(
9258                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9259                "Only package verification agents can verify applications");
9260
9261        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9262        final PackageVerificationResponse response = new PackageVerificationResponse(
9263                verificationCode, Binder.getCallingUid());
9264        msg.arg1 = id;
9265        msg.obj = response;
9266        mHandler.sendMessage(msg);
9267    }
9268
9269    @Override
9270    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9271            long millisecondsToDelay) {
9272        mContext.enforceCallingOrSelfPermission(
9273                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9274                "Only package verification agents can extend verification timeouts");
9275
9276        final PackageVerificationState state = mPendingVerification.get(id);
9277        final PackageVerificationResponse response = new PackageVerificationResponse(
9278                verificationCodeAtTimeout, Binder.getCallingUid());
9279
9280        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9281            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9282        }
9283        if (millisecondsToDelay < 0) {
9284            millisecondsToDelay = 0;
9285        }
9286        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9287                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9288            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9289        }
9290
9291        if ((state != null) && !state.timeoutExtended()) {
9292            state.extendTimeout();
9293
9294            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9295            msg.arg1 = id;
9296            msg.obj = response;
9297            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9298        }
9299    }
9300
9301    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9302            int verificationCode, UserHandle user) {
9303        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9304        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9305        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9306        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9307        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9308
9309        mContext.sendBroadcastAsUser(intent, user,
9310                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9311    }
9312
9313    private ComponentName matchComponentForVerifier(String packageName,
9314            List<ResolveInfo> receivers) {
9315        ActivityInfo targetReceiver = null;
9316
9317        final int NR = receivers.size();
9318        for (int i = 0; i < NR; i++) {
9319            final ResolveInfo info = receivers.get(i);
9320            if (info.activityInfo == null) {
9321                continue;
9322            }
9323
9324            if (packageName.equals(info.activityInfo.packageName)) {
9325                targetReceiver = info.activityInfo;
9326                break;
9327            }
9328        }
9329
9330        if (targetReceiver == null) {
9331            return null;
9332        }
9333
9334        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9335    }
9336
9337    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9338            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9339        if (pkgInfo.verifiers.length == 0) {
9340            return null;
9341        }
9342
9343        final int N = pkgInfo.verifiers.length;
9344        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9345        for (int i = 0; i < N; i++) {
9346            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9347
9348            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9349                    receivers);
9350            if (comp == null) {
9351                continue;
9352            }
9353
9354            final int verifierUid = getUidForVerifier(verifierInfo);
9355            if (verifierUid == -1) {
9356                continue;
9357            }
9358
9359            if (DEBUG_VERIFY) {
9360                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9361                        + " with the correct signature");
9362            }
9363            sufficientVerifiers.add(comp);
9364            verificationState.addSufficientVerifier(verifierUid);
9365        }
9366
9367        return sufficientVerifiers;
9368    }
9369
9370    private int getUidForVerifier(VerifierInfo verifierInfo) {
9371        synchronized (mPackages) {
9372            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9373            if (pkg == null) {
9374                return -1;
9375            } else if (pkg.mSignatures.length != 1) {
9376                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9377                        + " has more than one signature; ignoring");
9378                return -1;
9379            }
9380
9381            /*
9382             * If the public key of the package's signature does not match
9383             * our expected public key, then this is a different package and
9384             * we should skip.
9385             */
9386
9387            final byte[] expectedPublicKey;
9388            try {
9389                final Signature verifierSig = pkg.mSignatures[0];
9390                final PublicKey publicKey = verifierSig.getPublicKey();
9391                expectedPublicKey = publicKey.getEncoded();
9392            } catch (CertificateException e) {
9393                return -1;
9394            }
9395
9396            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9397
9398            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9399                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9400                        + " does not have the expected public key; ignoring");
9401                return -1;
9402            }
9403
9404            return pkg.applicationInfo.uid;
9405        }
9406    }
9407
9408    @Override
9409    public void finishPackageInstall(int token) {
9410        enforceSystemOrRoot("Only the system is allowed to finish installs");
9411
9412        if (DEBUG_INSTALL) {
9413            Slog.v(TAG, "BM finishing package install for " + token);
9414        }
9415
9416        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9417        mHandler.sendMessage(msg);
9418    }
9419
9420    /**
9421     * Get the verification agent timeout.
9422     *
9423     * @return verification timeout in milliseconds
9424     */
9425    private long getVerificationTimeout() {
9426        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9427                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9428                DEFAULT_VERIFICATION_TIMEOUT);
9429    }
9430
9431    /**
9432     * Get the default verification agent response code.
9433     *
9434     * @return default verification response code
9435     */
9436    private int getDefaultVerificationResponse() {
9437        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9438                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9439                DEFAULT_VERIFICATION_RESPONSE);
9440    }
9441
9442    /**
9443     * Check whether or not package verification has been enabled.
9444     *
9445     * @return true if verification should be performed
9446     */
9447    private boolean isVerificationEnabled(int userId, int installFlags) {
9448        if (!DEFAULT_VERIFY_ENABLE) {
9449            return false;
9450        }
9451
9452        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9453
9454        // Check if installing from ADB
9455        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9456            // Do not run verification in a test harness environment
9457            if (ActivityManager.isRunningInTestHarness()) {
9458                return false;
9459            }
9460            if (ensureVerifyAppsEnabled) {
9461                return true;
9462            }
9463            // Check if the developer does not want package verification for ADB installs
9464            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9465                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9466                return false;
9467            }
9468        }
9469
9470        if (ensureVerifyAppsEnabled) {
9471            return true;
9472        }
9473
9474        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9475                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9476    }
9477
9478    @Override
9479    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9480            throws RemoteException {
9481        mContext.enforceCallingOrSelfPermission(
9482                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9483                "Only intentfilter verification agents can verify applications");
9484
9485        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9486        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9487                Binder.getCallingUid(), verificationCode, failedDomains);
9488        msg.arg1 = id;
9489        msg.obj = response;
9490        mHandler.sendMessage(msg);
9491    }
9492
9493    @Override
9494    public int getIntentVerificationStatus(String packageName, int userId) {
9495        synchronized (mPackages) {
9496            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9497        }
9498    }
9499
9500    @Override
9501    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9502        boolean result = false;
9503        synchronized (mPackages) {
9504            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9505        }
9506        if (result) {
9507            scheduleWritePackageRestrictionsLocked(userId);
9508        }
9509        return result;
9510    }
9511
9512    @Override
9513    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9514        synchronized (mPackages) {
9515            return mSettings.getIntentFilterVerificationsLPr(packageName);
9516        }
9517    }
9518
9519    @Override
9520    public List<IntentFilter> getAllIntentFilters(String packageName) {
9521        if (TextUtils.isEmpty(packageName)) {
9522            return Collections.<IntentFilter>emptyList();
9523        }
9524        synchronized (mPackages) {
9525            PackageParser.Package pkg = mPackages.get(packageName);
9526            if (pkg == null || pkg.activities == null) {
9527                return Collections.<IntentFilter>emptyList();
9528            }
9529            final int count = pkg.activities.size();
9530            ArrayList<IntentFilter> result = new ArrayList<>();
9531            for (int n=0; n<count; n++) {
9532                PackageParser.Activity activity = pkg.activities.get(n);
9533                if (activity.intents != null || activity.intents.size() > 0) {
9534                    result.addAll(activity.intents);
9535                }
9536            }
9537            return result;
9538        }
9539    }
9540
9541    @Override
9542    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9543        synchronized (mPackages) {
9544            boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9545            if (packageName != null) {
9546                result |= updateIntentVerificationStatus(packageName,
9547                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9548                        UserHandle.myUserId());
9549            }
9550            return result;
9551        }
9552    }
9553
9554    @Override
9555    public String getDefaultBrowserPackageName(int userId) {
9556        synchronized (mPackages) {
9557            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9558        }
9559    }
9560
9561    /**
9562     * Get the "allow unknown sources" setting.
9563     *
9564     * @return the current "allow unknown sources" setting
9565     */
9566    private int getUnknownSourcesSettings() {
9567        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9568                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9569                -1);
9570    }
9571
9572    @Override
9573    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9574        final int uid = Binder.getCallingUid();
9575        // writer
9576        synchronized (mPackages) {
9577            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9578            if (targetPackageSetting == null) {
9579                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9580            }
9581
9582            PackageSetting installerPackageSetting;
9583            if (installerPackageName != null) {
9584                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9585                if (installerPackageSetting == null) {
9586                    throw new IllegalArgumentException("Unknown installer package: "
9587                            + installerPackageName);
9588                }
9589            } else {
9590                installerPackageSetting = null;
9591            }
9592
9593            Signature[] callerSignature;
9594            Object obj = mSettings.getUserIdLPr(uid);
9595            if (obj != null) {
9596                if (obj instanceof SharedUserSetting) {
9597                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9598                } else if (obj instanceof PackageSetting) {
9599                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9600                } else {
9601                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9602                }
9603            } else {
9604                throw new SecurityException("Unknown calling uid " + uid);
9605            }
9606
9607            // Verify: can't set installerPackageName to a package that is
9608            // not signed with the same cert as the caller.
9609            if (installerPackageSetting != null) {
9610                if (compareSignatures(callerSignature,
9611                        installerPackageSetting.signatures.mSignatures)
9612                        != PackageManager.SIGNATURE_MATCH) {
9613                    throw new SecurityException(
9614                            "Caller does not have same cert as new installer package "
9615                            + installerPackageName);
9616                }
9617            }
9618
9619            // Verify: if target already has an installer package, it must
9620            // be signed with the same cert as the caller.
9621            if (targetPackageSetting.installerPackageName != null) {
9622                PackageSetting setting = mSettings.mPackages.get(
9623                        targetPackageSetting.installerPackageName);
9624                // If the currently set package isn't valid, then it's always
9625                // okay to change it.
9626                if (setting != null) {
9627                    if (compareSignatures(callerSignature,
9628                            setting.signatures.mSignatures)
9629                            != PackageManager.SIGNATURE_MATCH) {
9630                        throw new SecurityException(
9631                                "Caller does not have same cert as old installer package "
9632                                + targetPackageSetting.installerPackageName);
9633                    }
9634                }
9635            }
9636
9637            // Okay!
9638            targetPackageSetting.installerPackageName = installerPackageName;
9639            scheduleWriteSettingsLocked();
9640        }
9641    }
9642
9643    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9644        // Queue up an async operation since the package installation may take a little while.
9645        mHandler.post(new Runnable() {
9646            public void run() {
9647                mHandler.removeCallbacks(this);
9648                 // Result object to be returned
9649                PackageInstalledInfo res = new PackageInstalledInfo();
9650                res.returnCode = currentStatus;
9651                res.uid = -1;
9652                res.pkg = null;
9653                res.removedInfo = new PackageRemovedInfo();
9654                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9655                    args.doPreInstall(res.returnCode);
9656                    synchronized (mInstallLock) {
9657                        installPackageLI(args, res);
9658                    }
9659                    args.doPostInstall(res.returnCode, res.uid);
9660                }
9661
9662                // A restore should be performed at this point if (a) the install
9663                // succeeded, (b) the operation is not an update, and (c) the new
9664                // package has not opted out of backup participation.
9665                final boolean update = res.removedInfo.removedPackage != null;
9666                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9667                boolean doRestore = !update
9668                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9669
9670                // Set up the post-install work request bookkeeping.  This will be used
9671                // and cleaned up by the post-install event handling regardless of whether
9672                // there's a restore pass performed.  Token values are >= 1.
9673                int token;
9674                if (mNextInstallToken < 0) mNextInstallToken = 1;
9675                token = mNextInstallToken++;
9676
9677                PostInstallData data = new PostInstallData(args, res);
9678                mRunningInstalls.put(token, data);
9679                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9680
9681                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9682                    // Pass responsibility to the Backup Manager.  It will perform a
9683                    // restore if appropriate, then pass responsibility back to the
9684                    // Package Manager to run the post-install observer callbacks
9685                    // and broadcasts.
9686                    IBackupManager bm = IBackupManager.Stub.asInterface(
9687                            ServiceManager.getService(Context.BACKUP_SERVICE));
9688                    if (bm != null) {
9689                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9690                                + " to BM for possible restore");
9691                        try {
9692                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9693                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9694                            } else {
9695                                doRestore = false;
9696                            }
9697                        } catch (RemoteException e) {
9698                            // can't happen; the backup manager is local
9699                        } catch (Exception e) {
9700                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9701                            doRestore = false;
9702                        }
9703                    } else {
9704                        Slog.e(TAG, "Backup Manager not found!");
9705                        doRestore = false;
9706                    }
9707                }
9708
9709                if (!doRestore) {
9710                    // No restore possible, or the Backup Manager was mysteriously not
9711                    // available -- just fire the post-install work request directly.
9712                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9713                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9714                    mHandler.sendMessage(msg);
9715                }
9716            }
9717        });
9718    }
9719
9720    private abstract class HandlerParams {
9721        private static final int MAX_RETRIES = 4;
9722
9723        /**
9724         * Number of times startCopy() has been attempted and had a non-fatal
9725         * error.
9726         */
9727        private int mRetries = 0;
9728
9729        /** User handle for the user requesting the information or installation. */
9730        private final UserHandle mUser;
9731
9732        HandlerParams(UserHandle user) {
9733            mUser = user;
9734        }
9735
9736        UserHandle getUser() {
9737            return mUser;
9738        }
9739
9740        final boolean startCopy() {
9741            boolean res;
9742            try {
9743                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9744
9745                if (++mRetries > MAX_RETRIES) {
9746                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9747                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9748                    handleServiceError();
9749                    return false;
9750                } else {
9751                    handleStartCopy();
9752                    res = true;
9753                }
9754            } catch (RemoteException e) {
9755                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9756                mHandler.sendEmptyMessage(MCS_RECONNECT);
9757                res = false;
9758            }
9759            handleReturnCode();
9760            return res;
9761        }
9762
9763        final void serviceError() {
9764            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9765            handleServiceError();
9766            handleReturnCode();
9767        }
9768
9769        abstract void handleStartCopy() throws RemoteException;
9770        abstract void handleServiceError();
9771        abstract void handleReturnCode();
9772    }
9773
9774    class MeasureParams extends HandlerParams {
9775        private final PackageStats mStats;
9776        private boolean mSuccess;
9777
9778        private final IPackageStatsObserver mObserver;
9779
9780        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9781            super(new UserHandle(stats.userHandle));
9782            mObserver = observer;
9783            mStats = stats;
9784        }
9785
9786        @Override
9787        public String toString() {
9788            return "MeasureParams{"
9789                + Integer.toHexString(System.identityHashCode(this))
9790                + " " + mStats.packageName + "}";
9791        }
9792
9793        @Override
9794        void handleStartCopy() throws RemoteException {
9795            synchronized (mInstallLock) {
9796                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9797            }
9798
9799            if (mSuccess) {
9800                final boolean mounted;
9801                if (Environment.isExternalStorageEmulated()) {
9802                    mounted = true;
9803                } else {
9804                    final String status = Environment.getExternalStorageState();
9805                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9806                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9807                }
9808
9809                if (mounted) {
9810                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9811
9812                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9813                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9814
9815                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9816                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9817
9818                    // Always subtract cache size, since it's a subdirectory
9819                    mStats.externalDataSize -= mStats.externalCacheSize;
9820
9821                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9822                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9823
9824                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9825                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9826                }
9827            }
9828        }
9829
9830        @Override
9831        void handleReturnCode() {
9832            if (mObserver != null) {
9833                try {
9834                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9835                } catch (RemoteException e) {
9836                    Slog.i(TAG, "Observer no longer exists.");
9837                }
9838            }
9839        }
9840
9841        @Override
9842        void handleServiceError() {
9843            Slog.e(TAG, "Could not measure application " + mStats.packageName
9844                            + " external storage");
9845        }
9846    }
9847
9848    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9849            throws RemoteException {
9850        long result = 0;
9851        for (File path : paths) {
9852            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9853        }
9854        return result;
9855    }
9856
9857    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9858        for (File path : paths) {
9859            try {
9860                mcs.clearDirectory(path.getAbsolutePath());
9861            } catch (RemoteException e) {
9862            }
9863        }
9864    }
9865
9866    static class OriginInfo {
9867        /**
9868         * Location where install is coming from, before it has been
9869         * copied/renamed into place. This could be a single monolithic APK
9870         * file, or a cluster directory. This location may be untrusted.
9871         */
9872        final File file;
9873        final String cid;
9874
9875        /**
9876         * Flag indicating that {@link #file} or {@link #cid} has already been
9877         * staged, meaning downstream users don't need to defensively copy the
9878         * contents.
9879         */
9880        final boolean staged;
9881
9882        /**
9883         * Flag indicating that {@link #file} or {@link #cid} is an already
9884         * installed app that is being moved.
9885         */
9886        final boolean existing;
9887
9888        final String resolvedPath;
9889        final File resolvedFile;
9890
9891        static OriginInfo fromNothing() {
9892            return new OriginInfo(null, null, false, false);
9893        }
9894
9895        static OriginInfo fromUntrustedFile(File file) {
9896            return new OriginInfo(file, null, false, false);
9897        }
9898
9899        static OriginInfo fromExistingFile(File file) {
9900            return new OriginInfo(file, null, false, true);
9901        }
9902
9903        static OriginInfo fromStagedFile(File file) {
9904            return new OriginInfo(file, null, true, false);
9905        }
9906
9907        static OriginInfo fromStagedContainer(String cid) {
9908            return new OriginInfo(null, cid, true, false);
9909        }
9910
9911        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9912            this.file = file;
9913            this.cid = cid;
9914            this.staged = staged;
9915            this.existing = existing;
9916
9917            if (cid != null) {
9918                resolvedPath = PackageHelper.getSdDir(cid);
9919                resolvedFile = new File(resolvedPath);
9920            } else if (file != null) {
9921                resolvedPath = file.getAbsolutePath();
9922                resolvedFile = file;
9923            } else {
9924                resolvedPath = null;
9925                resolvedFile = null;
9926            }
9927        }
9928    }
9929
9930    class MoveInfo {
9931        final int moveId;
9932        final String fromUuid;
9933        final String toUuid;
9934        final String packageName;
9935        final String dataAppName;
9936        final int appId;
9937        final String seinfo;
9938
9939        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
9940                String dataAppName, int appId, String seinfo) {
9941            this.moveId = moveId;
9942            this.fromUuid = fromUuid;
9943            this.toUuid = toUuid;
9944            this.packageName = packageName;
9945            this.dataAppName = dataAppName;
9946            this.appId = appId;
9947            this.seinfo = seinfo;
9948        }
9949    }
9950
9951    class InstallParams extends HandlerParams {
9952        final OriginInfo origin;
9953        final MoveInfo move;
9954        final IPackageInstallObserver2 observer;
9955        int installFlags;
9956        final String installerPackageName;
9957        final String volumeUuid;
9958        final VerificationParams verificationParams;
9959        private InstallArgs mArgs;
9960        private int mRet;
9961        final String packageAbiOverride;
9962
9963        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
9964                int installFlags, String installerPackageName, String volumeUuid,
9965                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9966            super(user);
9967            this.origin = origin;
9968            this.move = move;
9969            this.observer = observer;
9970            this.installFlags = installFlags;
9971            this.installerPackageName = installerPackageName;
9972            this.volumeUuid = volumeUuid;
9973            this.verificationParams = verificationParams;
9974            this.packageAbiOverride = packageAbiOverride;
9975        }
9976
9977        @Override
9978        public String toString() {
9979            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9980                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9981        }
9982
9983        public ManifestDigest getManifestDigest() {
9984            if (verificationParams == null) {
9985                return null;
9986            }
9987            return verificationParams.getManifestDigest();
9988        }
9989
9990        private int installLocationPolicy(PackageInfoLite pkgLite) {
9991            String packageName = pkgLite.packageName;
9992            int installLocation = pkgLite.installLocation;
9993            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9994            // reader
9995            synchronized (mPackages) {
9996                PackageParser.Package pkg = mPackages.get(packageName);
9997                if (pkg != null) {
9998                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9999                        // Check for downgrading.
10000                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10001                            try {
10002                                checkDowngrade(pkg, pkgLite);
10003                            } catch (PackageManagerException e) {
10004                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10005                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10006                            }
10007                        }
10008                        // Check for updated system application.
10009                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10010                            if (onSd) {
10011                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10012                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10013                            }
10014                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10015                        } else {
10016                            if (onSd) {
10017                                // Install flag overrides everything.
10018                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10019                            }
10020                            // If current upgrade specifies particular preference
10021                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10022                                // Application explicitly specified internal.
10023                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10024                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10025                                // App explictly prefers external. Let policy decide
10026                            } else {
10027                                // Prefer previous location
10028                                if (isExternal(pkg)) {
10029                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10030                                }
10031                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10032                            }
10033                        }
10034                    } else {
10035                        // Invalid install. Return error code
10036                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10037                    }
10038                }
10039            }
10040            // All the special cases have been taken care of.
10041            // Return result based on recommended install location.
10042            if (onSd) {
10043                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10044            }
10045            return pkgLite.recommendedInstallLocation;
10046        }
10047
10048        /*
10049         * Invoke remote method to get package information and install
10050         * location values. Override install location based on default
10051         * policy if needed and then create install arguments based
10052         * on the install location.
10053         */
10054        public void handleStartCopy() throws RemoteException {
10055            int ret = PackageManager.INSTALL_SUCCEEDED;
10056
10057            // If we're already staged, we've firmly committed to an install location
10058            if (origin.staged) {
10059                if (origin.file != null) {
10060                    installFlags |= PackageManager.INSTALL_INTERNAL;
10061                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10062                } else if (origin.cid != null) {
10063                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10064                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10065                } else {
10066                    throw new IllegalStateException("Invalid stage location");
10067                }
10068            }
10069
10070            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10071            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10072
10073            PackageInfoLite pkgLite = null;
10074
10075            if (onInt && onSd) {
10076                // Check if both bits are set.
10077                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10078                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10079            } else {
10080                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10081                        packageAbiOverride);
10082
10083                /*
10084                 * If we have too little free space, try to free cache
10085                 * before giving up.
10086                 */
10087                if (!origin.staged && pkgLite.recommendedInstallLocation
10088                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10089                    // TODO: focus freeing disk space on the target device
10090                    final StorageManager storage = StorageManager.from(mContext);
10091                    final long lowThreshold = storage.getStorageLowBytes(
10092                            Environment.getDataDirectory());
10093
10094                    final long sizeBytes = mContainerService.calculateInstalledSize(
10095                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10096
10097                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10098                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10099                                installFlags, packageAbiOverride);
10100                    }
10101
10102                    /*
10103                     * The cache free must have deleted the file we
10104                     * downloaded to install.
10105                     *
10106                     * TODO: fix the "freeCache" call to not delete
10107                     *       the file we care about.
10108                     */
10109                    if (pkgLite.recommendedInstallLocation
10110                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10111                        pkgLite.recommendedInstallLocation
10112                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10113                    }
10114                }
10115            }
10116
10117            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10118                int loc = pkgLite.recommendedInstallLocation;
10119                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10120                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10121                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10122                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10123                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10124                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10125                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10126                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10127                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10128                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10129                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10130                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10131                } else {
10132                    // Override with defaults if needed.
10133                    loc = installLocationPolicy(pkgLite);
10134                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10135                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10136                    } else if (!onSd && !onInt) {
10137                        // Override install location with flags
10138                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10139                            // Set the flag to install on external media.
10140                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10141                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10142                        } else {
10143                            // Make sure the flag for installing on external
10144                            // media is unset
10145                            installFlags |= PackageManager.INSTALL_INTERNAL;
10146                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10147                        }
10148                    }
10149                }
10150            }
10151
10152            final InstallArgs args = createInstallArgs(this);
10153            mArgs = args;
10154
10155            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10156                 /*
10157                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10158                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10159                 */
10160                int userIdentifier = getUser().getIdentifier();
10161                if (userIdentifier == UserHandle.USER_ALL
10162                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10163                    userIdentifier = UserHandle.USER_OWNER;
10164                }
10165
10166                /*
10167                 * Determine if we have any installed package verifiers. If we
10168                 * do, then we'll defer to them to verify the packages.
10169                 */
10170                final int requiredUid = mRequiredVerifierPackage == null ? -1
10171                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10172                if (!origin.existing && requiredUid != -1
10173                        && isVerificationEnabled(userIdentifier, installFlags)) {
10174                    final Intent verification = new Intent(
10175                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10176                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10177                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10178                            PACKAGE_MIME_TYPE);
10179                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10180
10181                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10182                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10183                            0 /* TODO: Which userId? */);
10184
10185                    if (DEBUG_VERIFY) {
10186                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10187                                + verification.toString() + " with " + pkgLite.verifiers.length
10188                                + " optional verifiers");
10189                    }
10190
10191                    final int verificationId = mPendingVerificationToken++;
10192
10193                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10194
10195                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10196                            installerPackageName);
10197
10198                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10199                            installFlags);
10200
10201                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10202                            pkgLite.packageName);
10203
10204                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10205                            pkgLite.versionCode);
10206
10207                    if (verificationParams != null) {
10208                        if (verificationParams.getVerificationURI() != null) {
10209                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10210                                 verificationParams.getVerificationURI());
10211                        }
10212                        if (verificationParams.getOriginatingURI() != null) {
10213                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10214                                  verificationParams.getOriginatingURI());
10215                        }
10216                        if (verificationParams.getReferrer() != null) {
10217                            verification.putExtra(Intent.EXTRA_REFERRER,
10218                                  verificationParams.getReferrer());
10219                        }
10220                        if (verificationParams.getOriginatingUid() >= 0) {
10221                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10222                                  verificationParams.getOriginatingUid());
10223                        }
10224                        if (verificationParams.getInstallerUid() >= 0) {
10225                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10226                                  verificationParams.getInstallerUid());
10227                        }
10228                    }
10229
10230                    final PackageVerificationState verificationState = new PackageVerificationState(
10231                            requiredUid, args);
10232
10233                    mPendingVerification.append(verificationId, verificationState);
10234
10235                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10236                            receivers, verificationState);
10237
10238                    /*
10239                     * If any sufficient verifiers were listed in the package
10240                     * manifest, attempt to ask them.
10241                     */
10242                    if (sufficientVerifiers != null) {
10243                        final int N = sufficientVerifiers.size();
10244                        if (N == 0) {
10245                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10246                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10247                        } else {
10248                            for (int i = 0; i < N; i++) {
10249                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10250
10251                                final Intent sufficientIntent = new Intent(verification);
10252                                sufficientIntent.setComponent(verifierComponent);
10253
10254                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10255                            }
10256                        }
10257                    }
10258
10259                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10260                            mRequiredVerifierPackage, receivers);
10261                    if (ret == PackageManager.INSTALL_SUCCEEDED
10262                            && mRequiredVerifierPackage != null) {
10263                        /*
10264                         * Send the intent to the required verification agent,
10265                         * but only start the verification timeout after the
10266                         * target BroadcastReceivers have run.
10267                         */
10268                        verification.setComponent(requiredVerifierComponent);
10269                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10270                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10271                                new BroadcastReceiver() {
10272                                    @Override
10273                                    public void onReceive(Context context, Intent intent) {
10274                                        final Message msg = mHandler
10275                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10276                                        msg.arg1 = verificationId;
10277                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10278                                    }
10279                                }, null, 0, null, null);
10280
10281                        /*
10282                         * We don't want the copy to proceed until verification
10283                         * succeeds, so null out this field.
10284                         */
10285                        mArgs = null;
10286                    }
10287                } else {
10288                    /*
10289                     * No package verification is enabled, so immediately start
10290                     * the remote call to initiate copy using temporary file.
10291                     */
10292                    ret = args.copyApk(mContainerService, true);
10293                }
10294            }
10295
10296            mRet = ret;
10297        }
10298
10299        @Override
10300        void handleReturnCode() {
10301            // If mArgs is null, then MCS couldn't be reached. When it
10302            // reconnects, it will try again to install. At that point, this
10303            // will succeed.
10304            if (mArgs != null) {
10305                processPendingInstall(mArgs, mRet);
10306            }
10307        }
10308
10309        @Override
10310        void handleServiceError() {
10311            mArgs = createInstallArgs(this);
10312            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10313        }
10314
10315        public boolean isForwardLocked() {
10316            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10317        }
10318    }
10319
10320    /**
10321     * Used during creation of InstallArgs
10322     *
10323     * @param installFlags package installation flags
10324     * @return true if should be installed on external storage
10325     */
10326    private static boolean installOnExternalAsec(int installFlags) {
10327        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10328            return false;
10329        }
10330        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10331            return true;
10332        }
10333        return false;
10334    }
10335
10336    /**
10337     * Used during creation of InstallArgs
10338     *
10339     * @param installFlags package installation flags
10340     * @return true if should be installed as forward locked
10341     */
10342    private static boolean installForwardLocked(int installFlags) {
10343        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10344    }
10345
10346    private InstallArgs createInstallArgs(InstallParams params) {
10347        if (params.move != null) {
10348            return new MoveInstallArgs(params);
10349        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10350            return new AsecInstallArgs(params);
10351        } else {
10352            return new FileInstallArgs(params);
10353        }
10354    }
10355
10356    /**
10357     * Create args that describe an existing installed package. Typically used
10358     * when cleaning up old installs, or used as a move source.
10359     */
10360    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10361            String resourcePath, String[] instructionSets) {
10362        final boolean isInAsec;
10363        if (installOnExternalAsec(installFlags)) {
10364            /* Apps on SD card are always in ASEC containers. */
10365            isInAsec = true;
10366        } else if (installForwardLocked(installFlags)
10367                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10368            /*
10369             * Forward-locked apps are only in ASEC containers if they're the
10370             * new style
10371             */
10372            isInAsec = true;
10373        } else {
10374            isInAsec = false;
10375        }
10376
10377        if (isInAsec) {
10378            return new AsecInstallArgs(codePath, instructionSets,
10379                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10380        } else {
10381            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10382        }
10383    }
10384
10385    static abstract class InstallArgs {
10386        /** @see InstallParams#origin */
10387        final OriginInfo origin;
10388        /** @see InstallParams#move */
10389        final MoveInfo move;
10390
10391        final IPackageInstallObserver2 observer;
10392        // Always refers to PackageManager flags only
10393        final int installFlags;
10394        final String installerPackageName;
10395        final String volumeUuid;
10396        final ManifestDigest manifestDigest;
10397        final UserHandle user;
10398        final String abiOverride;
10399
10400        // The list of instruction sets supported by this app. This is currently
10401        // only used during the rmdex() phase to clean up resources. We can get rid of this
10402        // if we move dex files under the common app path.
10403        /* nullable */ String[] instructionSets;
10404
10405        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10406                int installFlags, String installerPackageName, String volumeUuid,
10407                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10408                String abiOverride) {
10409            this.origin = origin;
10410            this.move = move;
10411            this.installFlags = installFlags;
10412            this.observer = observer;
10413            this.installerPackageName = installerPackageName;
10414            this.volumeUuid = volumeUuid;
10415            this.manifestDigest = manifestDigest;
10416            this.user = user;
10417            this.instructionSets = instructionSets;
10418            this.abiOverride = abiOverride;
10419        }
10420
10421        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10422        abstract int doPreInstall(int status);
10423
10424        /**
10425         * Rename package into final resting place. All paths on the given
10426         * scanned package should be updated to reflect the rename.
10427         */
10428        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10429        abstract int doPostInstall(int status, int uid);
10430
10431        /** @see PackageSettingBase#codePathString */
10432        abstract String getCodePath();
10433        /** @see PackageSettingBase#resourcePathString */
10434        abstract String getResourcePath();
10435
10436        // Need installer lock especially for dex file removal.
10437        abstract void cleanUpResourcesLI();
10438        abstract boolean doPostDeleteLI(boolean delete);
10439
10440        /**
10441         * Called before the source arguments are copied. This is used mostly
10442         * for MoveParams when it needs to read the source file to put it in the
10443         * destination.
10444         */
10445        int doPreCopy() {
10446            return PackageManager.INSTALL_SUCCEEDED;
10447        }
10448
10449        /**
10450         * Called after the source arguments are copied. This is used mostly for
10451         * MoveParams when it needs to read the source file to put it in the
10452         * destination.
10453         *
10454         * @return
10455         */
10456        int doPostCopy(int uid) {
10457            return PackageManager.INSTALL_SUCCEEDED;
10458        }
10459
10460        protected boolean isFwdLocked() {
10461            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10462        }
10463
10464        protected boolean isExternalAsec() {
10465            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10466        }
10467
10468        UserHandle getUser() {
10469            return user;
10470        }
10471    }
10472
10473    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10474        if (!allCodePaths.isEmpty()) {
10475            if (instructionSets == null) {
10476                throw new IllegalStateException("instructionSet == null");
10477            }
10478            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10479            for (String codePath : allCodePaths) {
10480                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10481                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10482                    if (retCode < 0) {
10483                        Slog.w(TAG, "Couldn't remove dex file for package: "
10484                                + " at location " + codePath + ", retcode=" + retCode);
10485                        // we don't consider this to be a failure of the core package deletion
10486                    }
10487                }
10488            }
10489        }
10490    }
10491
10492    /**
10493     * Logic to handle installation of non-ASEC applications, including copying
10494     * and renaming logic.
10495     */
10496    class FileInstallArgs extends InstallArgs {
10497        private File codeFile;
10498        private File resourceFile;
10499
10500        // Example topology:
10501        // /data/app/com.example/base.apk
10502        // /data/app/com.example/split_foo.apk
10503        // /data/app/com.example/lib/arm/libfoo.so
10504        // /data/app/com.example/lib/arm64/libfoo.so
10505        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10506
10507        /** New install */
10508        FileInstallArgs(InstallParams params) {
10509            super(params.origin, params.move, params.observer, params.installFlags,
10510                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10511                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10512            if (isFwdLocked()) {
10513                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10514            }
10515        }
10516
10517        /** Existing install */
10518        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10519            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10520                    null);
10521            this.codeFile = (codePath != null) ? new File(codePath) : null;
10522            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10523        }
10524
10525        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10526            if (origin.staged) {
10527                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10528                codeFile = origin.file;
10529                resourceFile = origin.file;
10530                return PackageManager.INSTALL_SUCCEEDED;
10531            }
10532
10533            try {
10534                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10535                codeFile = tempDir;
10536                resourceFile = tempDir;
10537            } catch (IOException e) {
10538                Slog.w(TAG, "Failed to create copy file: " + e);
10539                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10540            }
10541
10542            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10543                @Override
10544                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10545                    if (!FileUtils.isValidExtFilename(name)) {
10546                        throw new IllegalArgumentException("Invalid filename: " + name);
10547                    }
10548                    try {
10549                        final File file = new File(codeFile, name);
10550                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10551                                O_RDWR | O_CREAT, 0644);
10552                        Os.chmod(file.getAbsolutePath(), 0644);
10553                        return new ParcelFileDescriptor(fd);
10554                    } catch (ErrnoException e) {
10555                        throw new RemoteException("Failed to open: " + e.getMessage());
10556                    }
10557                }
10558            };
10559
10560            int ret = PackageManager.INSTALL_SUCCEEDED;
10561            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10562            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10563                Slog.e(TAG, "Failed to copy package");
10564                return ret;
10565            }
10566
10567            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10568            NativeLibraryHelper.Handle handle = null;
10569            try {
10570                handle = NativeLibraryHelper.Handle.create(codeFile);
10571                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10572                        abiOverride);
10573            } catch (IOException e) {
10574                Slog.e(TAG, "Copying native libraries failed", e);
10575                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10576            } finally {
10577                IoUtils.closeQuietly(handle);
10578            }
10579
10580            return ret;
10581        }
10582
10583        int doPreInstall(int status) {
10584            if (status != PackageManager.INSTALL_SUCCEEDED) {
10585                cleanUp();
10586            }
10587            return status;
10588        }
10589
10590        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10591            if (status != PackageManager.INSTALL_SUCCEEDED) {
10592                cleanUp();
10593                return false;
10594            }
10595
10596            final File targetDir = codeFile.getParentFile();
10597            final File beforeCodeFile = codeFile;
10598            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10599
10600            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10601            try {
10602                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10603            } catch (ErrnoException e) {
10604                Slog.w(TAG, "Failed to rename", e);
10605                return false;
10606            }
10607
10608            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10609                Slog.w(TAG, "Failed to restorecon");
10610                return false;
10611            }
10612
10613            // Reflect the rename internally
10614            codeFile = afterCodeFile;
10615            resourceFile = afterCodeFile;
10616
10617            // Reflect the rename in scanned details
10618            pkg.codePath = afterCodeFile.getAbsolutePath();
10619            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10620                    pkg.baseCodePath);
10621            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10622                    pkg.splitCodePaths);
10623
10624            // Reflect the rename in app info
10625            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10626            pkg.applicationInfo.setCodePath(pkg.codePath);
10627            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10628            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10629            pkg.applicationInfo.setResourcePath(pkg.codePath);
10630            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10631            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10632
10633            return true;
10634        }
10635
10636        int doPostInstall(int status, int uid) {
10637            if (status != PackageManager.INSTALL_SUCCEEDED) {
10638                cleanUp();
10639            }
10640            return status;
10641        }
10642
10643        @Override
10644        String getCodePath() {
10645            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10646        }
10647
10648        @Override
10649        String getResourcePath() {
10650            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10651        }
10652
10653        private boolean cleanUp() {
10654            if (codeFile == null || !codeFile.exists()) {
10655                return false;
10656            }
10657
10658            if (codeFile.isDirectory()) {
10659                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10660            } else {
10661                codeFile.delete();
10662            }
10663
10664            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10665                resourceFile.delete();
10666            }
10667
10668            return true;
10669        }
10670
10671        void cleanUpResourcesLI() {
10672            // Try enumerating all code paths before deleting
10673            List<String> allCodePaths = Collections.EMPTY_LIST;
10674            if (codeFile != null && codeFile.exists()) {
10675                try {
10676                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10677                    allCodePaths = pkg.getAllCodePaths();
10678                } catch (PackageParserException e) {
10679                    // Ignored; we tried our best
10680                }
10681            }
10682
10683            cleanUp();
10684            removeDexFiles(allCodePaths, instructionSets);
10685        }
10686
10687        boolean doPostDeleteLI(boolean delete) {
10688            // XXX err, shouldn't we respect the delete flag?
10689            cleanUpResourcesLI();
10690            return true;
10691        }
10692    }
10693
10694    private boolean isAsecExternal(String cid) {
10695        final String asecPath = PackageHelper.getSdFilesystem(cid);
10696        return !asecPath.startsWith(mAsecInternalPath);
10697    }
10698
10699    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10700            PackageManagerException {
10701        if (copyRet < 0) {
10702            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10703                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10704                throw new PackageManagerException(copyRet, message);
10705            }
10706        }
10707    }
10708
10709    /**
10710     * Extract the MountService "container ID" from the full code path of an
10711     * .apk.
10712     */
10713    static String cidFromCodePath(String fullCodePath) {
10714        int eidx = fullCodePath.lastIndexOf("/");
10715        String subStr1 = fullCodePath.substring(0, eidx);
10716        int sidx = subStr1.lastIndexOf("/");
10717        return subStr1.substring(sidx+1, eidx);
10718    }
10719
10720    /**
10721     * Logic to handle installation of ASEC applications, including copying and
10722     * renaming logic.
10723     */
10724    class AsecInstallArgs extends InstallArgs {
10725        static final String RES_FILE_NAME = "pkg.apk";
10726        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10727
10728        String cid;
10729        String packagePath;
10730        String resourcePath;
10731
10732        /** New install */
10733        AsecInstallArgs(InstallParams params) {
10734            super(params.origin, params.move, params.observer, params.installFlags,
10735                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10736                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10737        }
10738
10739        /** Existing install */
10740        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10741                        boolean isExternal, boolean isForwardLocked) {
10742            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10743                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10744                    instructionSets, null);
10745            // Hackily pretend we're still looking at a full code path
10746            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10747                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10748            }
10749
10750            // Extract cid from fullCodePath
10751            int eidx = fullCodePath.lastIndexOf("/");
10752            String subStr1 = fullCodePath.substring(0, eidx);
10753            int sidx = subStr1.lastIndexOf("/");
10754            cid = subStr1.substring(sidx+1, eidx);
10755            setMountPath(subStr1);
10756        }
10757
10758        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10759            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10760                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10761                    instructionSets, null);
10762            this.cid = cid;
10763            setMountPath(PackageHelper.getSdDir(cid));
10764        }
10765
10766        void createCopyFile() {
10767            cid = mInstallerService.allocateExternalStageCidLegacy();
10768        }
10769
10770        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10771            if (origin.staged) {
10772                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
10773                cid = origin.cid;
10774                setMountPath(PackageHelper.getSdDir(cid));
10775                return PackageManager.INSTALL_SUCCEEDED;
10776            }
10777
10778            if (temp) {
10779                createCopyFile();
10780            } else {
10781                /*
10782                 * Pre-emptively destroy the container since it's destroyed if
10783                 * copying fails due to it existing anyway.
10784                 */
10785                PackageHelper.destroySdDir(cid);
10786            }
10787
10788            final String newMountPath = imcs.copyPackageToContainer(
10789                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10790                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10791
10792            if (newMountPath != null) {
10793                setMountPath(newMountPath);
10794                return PackageManager.INSTALL_SUCCEEDED;
10795            } else {
10796                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10797            }
10798        }
10799
10800        @Override
10801        String getCodePath() {
10802            return packagePath;
10803        }
10804
10805        @Override
10806        String getResourcePath() {
10807            return resourcePath;
10808        }
10809
10810        int doPreInstall(int status) {
10811            if (status != PackageManager.INSTALL_SUCCEEDED) {
10812                // Destroy container
10813                PackageHelper.destroySdDir(cid);
10814            } else {
10815                boolean mounted = PackageHelper.isContainerMounted(cid);
10816                if (!mounted) {
10817                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10818                            Process.SYSTEM_UID);
10819                    if (newMountPath != null) {
10820                        setMountPath(newMountPath);
10821                    } else {
10822                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10823                    }
10824                }
10825            }
10826            return status;
10827        }
10828
10829        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10830            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10831            String newMountPath = null;
10832            if (PackageHelper.isContainerMounted(cid)) {
10833                // Unmount the container
10834                if (!PackageHelper.unMountSdDir(cid)) {
10835                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10836                    return false;
10837                }
10838            }
10839            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10840                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10841                        " which might be stale. Will try to clean up.");
10842                // Clean up the stale container and proceed to recreate.
10843                if (!PackageHelper.destroySdDir(newCacheId)) {
10844                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10845                    return false;
10846                }
10847                // Successfully cleaned up stale container. Try to rename again.
10848                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10849                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10850                            + " inspite of cleaning it up.");
10851                    return false;
10852                }
10853            }
10854            if (!PackageHelper.isContainerMounted(newCacheId)) {
10855                Slog.w(TAG, "Mounting container " + newCacheId);
10856                newMountPath = PackageHelper.mountSdDir(newCacheId,
10857                        getEncryptKey(), Process.SYSTEM_UID);
10858            } else {
10859                newMountPath = PackageHelper.getSdDir(newCacheId);
10860            }
10861            if (newMountPath == null) {
10862                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10863                return false;
10864            }
10865            Log.i(TAG, "Succesfully renamed " + cid +
10866                    " to " + newCacheId +
10867                    " at new path: " + newMountPath);
10868            cid = newCacheId;
10869
10870            final File beforeCodeFile = new File(packagePath);
10871            setMountPath(newMountPath);
10872            final File afterCodeFile = new File(packagePath);
10873
10874            // Reflect the rename in scanned details
10875            pkg.codePath = afterCodeFile.getAbsolutePath();
10876            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10877                    pkg.baseCodePath);
10878            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10879                    pkg.splitCodePaths);
10880
10881            // Reflect the rename in app info
10882            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10883            pkg.applicationInfo.setCodePath(pkg.codePath);
10884            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10885            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10886            pkg.applicationInfo.setResourcePath(pkg.codePath);
10887            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10888            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10889
10890            return true;
10891        }
10892
10893        private void setMountPath(String mountPath) {
10894            final File mountFile = new File(mountPath);
10895
10896            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10897            if (monolithicFile.exists()) {
10898                packagePath = monolithicFile.getAbsolutePath();
10899                if (isFwdLocked()) {
10900                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10901                } else {
10902                    resourcePath = packagePath;
10903                }
10904            } else {
10905                packagePath = mountFile.getAbsolutePath();
10906                resourcePath = packagePath;
10907            }
10908        }
10909
10910        int doPostInstall(int status, int uid) {
10911            if (status != PackageManager.INSTALL_SUCCEEDED) {
10912                cleanUp();
10913            } else {
10914                final int groupOwner;
10915                final String protectedFile;
10916                if (isFwdLocked()) {
10917                    groupOwner = UserHandle.getSharedAppGid(uid);
10918                    protectedFile = RES_FILE_NAME;
10919                } else {
10920                    groupOwner = -1;
10921                    protectedFile = null;
10922                }
10923
10924                if (uid < Process.FIRST_APPLICATION_UID
10925                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10926                    Slog.e(TAG, "Failed to finalize " + cid);
10927                    PackageHelper.destroySdDir(cid);
10928                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10929                }
10930
10931                boolean mounted = PackageHelper.isContainerMounted(cid);
10932                if (!mounted) {
10933                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10934                }
10935            }
10936            return status;
10937        }
10938
10939        private void cleanUp() {
10940            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10941
10942            // Destroy secure container
10943            PackageHelper.destroySdDir(cid);
10944        }
10945
10946        private List<String> getAllCodePaths() {
10947            final File codeFile = new File(getCodePath());
10948            if (codeFile != null && codeFile.exists()) {
10949                try {
10950                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10951                    return pkg.getAllCodePaths();
10952                } catch (PackageParserException e) {
10953                    // Ignored; we tried our best
10954                }
10955            }
10956            return Collections.EMPTY_LIST;
10957        }
10958
10959        void cleanUpResourcesLI() {
10960            // Enumerate all code paths before deleting
10961            cleanUpResourcesLI(getAllCodePaths());
10962        }
10963
10964        private void cleanUpResourcesLI(List<String> allCodePaths) {
10965            cleanUp();
10966            removeDexFiles(allCodePaths, instructionSets);
10967        }
10968
10969        String getPackageName() {
10970            return getAsecPackageName(cid);
10971        }
10972
10973        boolean doPostDeleteLI(boolean delete) {
10974            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10975            final List<String> allCodePaths = getAllCodePaths();
10976            boolean mounted = PackageHelper.isContainerMounted(cid);
10977            if (mounted) {
10978                // Unmount first
10979                if (PackageHelper.unMountSdDir(cid)) {
10980                    mounted = false;
10981                }
10982            }
10983            if (!mounted && delete) {
10984                cleanUpResourcesLI(allCodePaths);
10985            }
10986            return !mounted;
10987        }
10988
10989        @Override
10990        int doPreCopy() {
10991            if (isFwdLocked()) {
10992                if (!PackageHelper.fixSdPermissions(cid,
10993                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10994                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10995                }
10996            }
10997
10998            return PackageManager.INSTALL_SUCCEEDED;
10999        }
11000
11001        @Override
11002        int doPostCopy(int uid) {
11003            if (isFwdLocked()) {
11004                if (uid < Process.FIRST_APPLICATION_UID
11005                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11006                                RES_FILE_NAME)) {
11007                    Slog.e(TAG, "Failed to finalize " + cid);
11008                    PackageHelper.destroySdDir(cid);
11009                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11010                }
11011            }
11012
11013            return PackageManager.INSTALL_SUCCEEDED;
11014        }
11015    }
11016
11017    /**
11018     * Logic to handle movement of existing installed applications.
11019     */
11020    class MoveInstallArgs extends InstallArgs {
11021        private File codeFile;
11022        private File resourceFile;
11023
11024        /** New install */
11025        MoveInstallArgs(InstallParams params) {
11026            super(params.origin, params.move, params.observer, params.installFlags,
11027                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11028                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11029        }
11030
11031        int copyApk(IMediaContainerService imcs, boolean temp) {
11032            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11033                    + move.fromUuid + " to " + move.toUuid);
11034            synchronized (mInstaller) {
11035                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11036                        move.dataAppName, move.appId, move.seinfo) != 0) {
11037                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11038                }
11039            }
11040
11041            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11042            resourceFile = codeFile;
11043            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11044
11045            return PackageManager.INSTALL_SUCCEEDED;
11046        }
11047
11048        int doPreInstall(int status) {
11049            if (status != PackageManager.INSTALL_SUCCEEDED) {
11050                cleanUp();
11051            }
11052            return status;
11053        }
11054
11055        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11056            if (status != PackageManager.INSTALL_SUCCEEDED) {
11057                cleanUp();
11058                return false;
11059            }
11060
11061            // Reflect the move in app info
11062            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11063            pkg.applicationInfo.setCodePath(pkg.codePath);
11064            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11065            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11066            pkg.applicationInfo.setResourcePath(pkg.codePath);
11067            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11068            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11069
11070            return true;
11071        }
11072
11073        int doPostInstall(int status, int uid) {
11074            if (status != PackageManager.INSTALL_SUCCEEDED) {
11075                cleanUp();
11076            }
11077            return status;
11078        }
11079
11080        @Override
11081        String getCodePath() {
11082            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11083        }
11084
11085        @Override
11086        String getResourcePath() {
11087            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11088        }
11089
11090        private boolean cleanUp() {
11091            if (codeFile == null || !codeFile.exists()) {
11092                return false;
11093            }
11094
11095            if (codeFile.isDirectory()) {
11096                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11097            } else {
11098                codeFile.delete();
11099            }
11100
11101            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11102                resourceFile.delete();
11103            }
11104
11105            return true;
11106        }
11107
11108        void cleanUpResourcesLI() {
11109            cleanUp();
11110        }
11111
11112        boolean doPostDeleteLI(boolean delete) {
11113            // XXX err, shouldn't we respect the delete flag?
11114            cleanUpResourcesLI();
11115            return true;
11116        }
11117    }
11118
11119    static String getAsecPackageName(String packageCid) {
11120        int idx = packageCid.lastIndexOf("-");
11121        if (idx == -1) {
11122            return packageCid;
11123        }
11124        return packageCid.substring(0, idx);
11125    }
11126
11127    // Utility method used to create code paths based on package name and available index.
11128    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11129        String idxStr = "";
11130        int idx = 1;
11131        // Fall back to default value of idx=1 if prefix is not
11132        // part of oldCodePath
11133        if (oldCodePath != null) {
11134            String subStr = oldCodePath;
11135            // Drop the suffix right away
11136            if (suffix != null && subStr.endsWith(suffix)) {
11137                subStr = subStr.substring(0, subStr.length() - suffix.length());
11138            }
11139            // If oldCodePath already contains prefix find out the
11140            // ending index to either increment or decrement.
11141            int sidx = subStr.lastIndexOf(prefix);
11142            if (sidx != -1) {
11143                subStr = subStr.substring(sidx + prefix.length());
11144                if (subStr != null) {
11145                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11146                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11147                    }
11148                    try {
11149                        idx = Integer.parseInt(subStr);
11150                        if (idx <= 1) {
11151                            idx++;
11152                        } else {
11153                            idx--;
11154                        }
11155                    } catch(NumberFormatException e) {
11156                    }
11157                }
11158            }
11159        }
11160        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11161        return prefix + idxStr;
11162    }
11163
11164    private File getNextCodePath(File targetDir, String packageName) {
11165        int suffix = 1;
11166        File result;
11167        do {
11168            result = new File(targetDir, packageName + "-" + suffix);
11169            suffix++;
11170        } while (result.exists());
11171        return result;
11172    }
11173
11174    // Utility method that returns the relative package path with respect
11175    // to the installation directory. Like say for /data/data/com.test-1.apk
11176    // string com.test-1 is returned.
11177    static String deriveCodePathName(String codePath) {
11178        if (codePath == null) {
11179            return null;
11180        }
11181        final File codeFile = new File(codePath);
11182        final String name = codeFile.getName();
11183        if (codeFile.isDirectory()) {
11184            return name;
11185        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11186            final int lastDot = name.lastIndexOf('.');
11187            return name.substring(0, lastDot);
11188        } else {
11189            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11190            return null;
11191        }
11192    }
11193
11194    class PackageInstalledInfo {
11195        String name;
11196        int uid;
11197        // The set of users that originally had this package installed.
11198        int[] origUsers;
11199        // The set of users that now have this package installed.
11200        int[] newUsers;
11201        PackageParser.Package pkg;
11202        int returnCode;
11203        String returnMsg;
11204        PackageRemovedInfo removedInfo;
11205
11206        public void setError(int code, String msg) {
11207            returnCode = code;
11208            returnMsg = msg;
11209            Slog.w(TAG, msg);
11210        }
11211
11212        public void setError(String msg, PackageParserException e) {
11213            returnCode = e.error;
11214            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11215            Slog.w(TAG, msg, e);
11216        }
11217
11218        public void setError(String msg, PackageManagerException e) {
11219            returnCode = e.error;
11220            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11221            Slog.w(TAG, msg, e);
11222        }
11223
11224        // In some error cases we want to convey more info back to the observer
11225        String origPackage;
11226        String origPermission;
11227    }
11228
11229    /*
11230     * Install a non-existing package.
11231     */
11232    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11233            UserHandle user, String installerPackageName, String volumeUuid,
11234            PackageInstalledInfo res) {
11235        // Remember this for later, in case we need to rollback this install
11236        String pkgName = pkg.packageName;
11237
11238        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11239        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
11240                UserHandle.USER_OWNER).exists();
11241        synchronized(mPackages) {
11242            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11243                // A package with the same name is already installed, though
11244                // it has been renamed to an older name.  The package we
11245                // are trying to install should be installed as an update to
11246                // the existing one, but that has not been requested, so bail.
11247                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11248                        + " without first uninstalling package running as "
11249                        + mSettings.mRenamedPackages.get(pkgName));
11250                return;
11251            }
11252            if (mPackages.containsKey(pkgName)) {
11253                // Don't allow installation over an existing package with the same name.
11254                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11255                        + " without first uninstalling.");
11256                return;
11257            }
11258        }
11259
11260        try {
11261            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11262                    System.currentTimeMillis(), user);
11263
11264            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11265            // delete the partially installed application. the data directory will have to be
11266            // restored if it was already existing
11267            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11268                // remove package from internal structures.  Note that we want deletePackageX to
11269                // delete the package data and cache directories that it created in
11270                // scanPackageLocked, unless those directories existed before we even tried to
11271                // install.
11272                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11273                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11274                                res.removedInfo, true);
11275            }
11276
11277        } catch (PackageManagerException e) {
11278            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11279        }
11280    }
11281
11282    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11283        // Can't rotate keys during boot or if sharedUser.
11284        if (oldPs == null || (scanFlags&SCAN_BOOTING) != 0 || oldPs.sharedUser != null
11285                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11286            return false;
11287        }
11288        // app is using upgradeKeySets; make sure all are valid
11289        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11290        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11291        for (int i = 0; i < upgradeKeySets.length; i++) {
11292            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11293                Slog.wtf(TAG, "Package "
11294                         + (oldPs.name != null ? oldPs.name : "<null>")
11295                         + " contains upgrade-key-set reference to unknown key-set: "
11296                         + upgradeKeySets[i]
11297                         + " reverting to signatures check.");
11298                return false;
11299            }
11300        }
11301        return true;
11302    }
11303
11304    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11305        // Upgrade keysets are being used.  Determine if new package has a superset of the
11306        // required keys.
11307        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11308        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11309        for (int i = 0; i < upgradeKeySets.length; i++) {
11310            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11311            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11312                return true;
11313            }
11314        }
11315        return false;
11316    }
11317
11318    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11319            UserHandle user, String installerPackageName, String volumeUuid,
11320            PackageInstalledInfo res) {
11321        final PackageParser.Package oldPackage;
11322        final String pkgName = pkg.packageName;
11323        final int[] allUsers;
11324        final boolean[] perUserInstalled;
11325        final boolean weFroze;
11326
11327        // First find the old package info and check signatures
11328        synchronized(mPackages) {
11329            oldPackage = mPackages.get(pkgName);
11330            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11331            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11332            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11333                if(!checkUpgradeKeySetLP(ps, pkg)) {
11334                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11335                            "New package not signed by keys specified by upgrade-keysets: "
11336                            + pkgName);
11337                    return;
11338                }
11339            } else {
11340                // default to original signature matching
11341                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11342                    != PackageManager.SIGNATURE_MATCH) {
11343                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11344                            "New package has a different signature: " + pkgName);
11345                    return;
11346                }
11347            }
11348
11349            // In case of rollback, remember per-user/profile install state
11350            allUsers = sUserManager.getUserIds();
11351            perUserInstalled = new boolean[allUsers.length];
11352            for (int i = 0; i < allUsers.length; i++) {
11353                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11354            }
11355
11356            // Mark the app as frozen to prevent launching during the upgrade
11357            // process, and then kill all running instances
11358            if (!ps.frozen) {
11359                ps.frozen = true;
11360                weFroze = true;
11361            } else {
11362                weFroze = false;
11363            }
11364        }
11365
11366        // Now that we're guarded by frozen state, kill app during upgrade
11367        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11368
11369        try {
11370            boolean sysPkg = (isSystemApp(oldPackage));
11371            if (sysPkg) {
11372                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11373                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11374            } else {
11375                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11376                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11377            }
11378        } finally {
11379            // Regardless of success or failure of upgrade steps above, always
11380            // unfreeze the package if we froze it
11381            if (weFroze) {
11382                unfreezePackage(pkgName);
11383            }
11384        }
11385    }
11386
11387    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11388            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11389            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11390            String volumeUuid, PackageInstalledInfo res) {
11391        String pkgName = deletedPackage.packageName;
11392        boolean deletedPkg = true;
11393        boolean updatedSettings = false;
11394
11395        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11396                + deletedPackage);
11397        long origUpdateTime;
11398        if (pkg.mExtras != null) {
11399            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11400        } else {
11401            origUpdateTime = 0;
11402        }
11403
11404        // First delete the existing package while retaining the data directory
11405        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11406                res.removedInfo, true)) {
11407            // If the existing package wasn't successfully deleted
11408            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11409            deletedPkg = false;
11410        } else {
11411            // Successfully deleted the old package; proceed with replace.
11412
11413            // If deleted package lived in a container, give users a chance to
11414            // relinquish resources before killing.
11415            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11416                if (DEBUG_INSTALL) {
11417                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11418                }
11419                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11420                final ArrayList<String> pkgList = new ArrayList<String>(1);
11421                pkgList.add(deletedPackage.applicationInfo.packageName);
11422                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11423            }
11424
11425            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11426            try {
11427                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11428                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11429                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11430                        perUserInstalled, res, user);
11431                updatedSettings = true;
11432            } catch (PackageManagerException e) {
11433                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11434            }
11435        }
11436
11437        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11438            // remove package from internal structures.  Note that we want deletePackageX to
11439            // delete the package data and cache directories that it created in
11440            // scanPackageLocked, unless those directories existed before we even tried to
11441            // install.
11442            if(updatedSettings) {
11443                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11444                deletePackageLI(
11445                        pkgName, null, true, allUsers, perUserInstalled,
11446                        PackageManager.DELETE_KEEP_DATA,
11447                                res.removedInfo, true);
11448            }
11449            // Since we failed to install the new package we need to restore the old
11450            // package that we deleted.
11451            if (deletedPkg) {
11452                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11453                File restoreFile = new File(deletedPackage.codePath);
11454                // Parse old package
11455                boolean oldExternal = isExternal(deletedPackage);
11456                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11457                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11458                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11459                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11460                try {
11461                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11462                } catch (PackageManagerException e) {
11463                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11464                            + e.getMessage());
11465                    return;
11466                }
11467                // Restore of old package succeeded. Update permissions.
11468                // writer
11469                synchronized (mPackages) {
11470                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11471                            UPDATE_PERMISSIONS_ALL);
11472                    // can downgrade to reader
11473                    mSettings.writeLPr();
11474                }
11475                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11476            }
11477        }
11478    }
11479
11480    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11481            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11482            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11483            String volumeUuid, PackageInstalledInfo res) {
11484        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11485                + ", old=" + deletedPackage);
11486        boolean disabledSystem = false;
11487        boolean updatedSettings = false;
11488        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11489        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11490                != 0) {
11491            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11492        }
11493        String packageName = deletedPackage.packageName;
11494        if (packageName == null) {
11495            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11496                    "Attempt to delete null packageName.");
11497            return;
11498        }
11499        PackageParser.Package oldPkg;
11500        PackageSetting oldPkgSetting;
11501        // reader
11502        synchronized (mPackages) {
11503            oldPkg = mPackages.get(packageName);
11504            oldPkgSetting = mSettings.mPackages.get(packageName);
11505            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11506                    (oldPkgSetting == null)) {
11507                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11508                        "Couldn't find package:" + packageName + " information");
11509                return;
11510            }
11511        }
11512
11513        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11514        res.removedInfo.removedPackage = packageName;
11515        // Remove existing system package
11516        removePackageLI(oldPkgSetting, true);
11517        // writer
11518        synchronized (mPackages) {
11519            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11520            if (!disabledSystem && deletedPackage != null) {
11521                // We didn't need to disable the .apk as a current system package,
11522                // which means we are replacing another update that is already
11523                // installed.  We need to make sure to delete the older one's .apk.
11524                res.removedInfo.args = createInstallArgsForExisting(0,
11525                        deletedPackage.applicationInfo.getCodePath(),
11526                        deletedPackage.applicationInfo.getResourcePath(),
11527                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11528            } else {
11529                res.removedInfo.args = null;
11530            }
11531        }
11532
11533        // Successfully disabled the old package. Now proceed with re-installation
11534        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11535
11536        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11537        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11538
11539        PackageParser.Package newPackage = null;
11540        try {
11541            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11542            if (newPackage.mExtras != null) {
11543                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11544                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11545                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11546
11547                // is the update attempting to change shared user? that isn't going to work...
11548                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11549                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11550                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11551                            + " to " + newPkgSetting.sharedUser);
11552                    updatedSettings = true;
11553                }
11554            }
11555
11556            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11557                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11558                        perUserInstalled, res, user);
11559                updatedSettings = true;
11560            }
11561
11562        } catch (PackageManagerException e) {
11563            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11564        }
11565
11566        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11567            // Re installation failed. Restore old information
11568            // Remove new pkg information
11569            if (newPackage != null) {
11570                removeInstalledPackageLI(newPackage, true);
11571            }
11572            // Add back the old system package
11573            try {
11574                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11575            } catch (PackageManagerException e) {
11576                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11577            }
11578            // Restore the old system information in Settings
11579            synchronized (mPackages) {
11580                if (disabledSystem) {
11581                    mSettings.enableSystemPackageLPw(packageName);
11582                }
11583                if (updatedSettings) {
11584                    mSettings.setInstallerPackageName(packageName,
11585                            oldPkgSetting.installerPackageName);
11586                }
11587                mSettings.writeLPr();
11588            }
11589        }
11590    }
11591
11592    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11593            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11594            UserHandle user) {
11595        String pkgName = newPackage.packageName;
11596        synchronized (mPackages) {
11597            //write settings. the installStatus will be incomplete at this stage.
11598            //note that the new package setting would have already been
11599            //added to mPackages. It hasn't been persisted yet.
11600            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11601            mSettings.writeLPr();
11602        }
11603
11604        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11605
11606        synchronized (mPackages) {
11607            updatePermissionsLPw(newPackage.packageName, newPackage,
11608                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11609                            ? UPDATE_PERMISSIONS_ALL : 0));
11610            // For system-bundled packages, we assume that installing an upgraded version
11611            // of the package implies that the user actually wants to run that new code,
11612            // so we enable the package.
11613            PackageSetting ps = mSettings.mPackages.get(pkgName);
11614            if (ps != null) {
11615                if (isSystemApp(newPackage)) {
11616                    // NB: implicit assumption that system package upgrades apply to all users
11617                    if (DEBUG_INSTALL) {
11618                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11619                    }
11620                    if (res.origUsers != null) {
11621                        for (int userHandle : res.origUsers) {
11622                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11623                                    userHandle, installerPackageName);
11624                        }
11625                    }
11626                    // Also convey the prior install/uninstall state
11627                    if (allUsers != null && perUserInstalled != null) {
11628                        for (int i = 0; i < allUsers.length; i++) {
11629                            if (DEBUG_INSTALL) {
11630                                Slog.d(TAG, "    user " + allUsers[i]
11631                                        + " => " + perUserInstalled[i]);
11632                            }
11633                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11634                        }
11635                        // these install state changes will be persisted in the
11636                        // upcoming call to mSettings.writeLPr().
11637                    }
11638                }
11639                // It's implied that when a user requests installation, they want the app to be
11640                // installed and enabled.
11641                int userId = user.getIdentifier();
11642                if (userId != UserHandle.USER_ALL) {
11643                    ps.setInstalled(true, userId);
11644                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11645                }
11646            }
11647            res.name = pkgName;
11648            res.uid = newPackage.applicationInfo.uid;
11649            res.pkg = newPackage;
11650            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11651            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11652            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11653            //to update install status
11654            mSettings.writeLPr();
11655        }
11656    }
11657
11658    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11659        final int installFlags = args.installFlags;
11660        final String installerPackageName = args.installerPackageName;
11661        final String volumeUuid = args.volumeUuid;
11662        final File tmpPackageFile = new File(args.getCodePath());
11663        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11664        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11665                || (args.volumeUuid != null));
11666        boolean replace = false;
11667        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11668        // Result object to be returned
11669        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11670
11671        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11672        // Retrieve PackageSettings and parse package
11673        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11674                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11675                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11676        PackageParser pp = new PackageParser();
11677        pp.setSeparateProcesses(mSeparateProcesses);
11678        pp.setDisplayMetrics(mMetrics);
11679
11680        final PackageParser.Package pkg;
11681        try {
11682            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11683        } catch (PackageParserException e) {
11684            res.setError("Failed parse during installPackageLI", e);
11685            return;
11686        }
11687
11688        // Mark that we have an install time CPU ABI override.
11689        pkg.cpuAbiOverride = args.abiOverride;
11690
11691        String pkgName = res.name = pkg.packageName;
11692        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11693            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11694                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11695                return;
11696            }
11697        }
11698
11699        try {
11700            pp.collectCertificates(pkg, parseFlags);
11701            pp.collectManifestDigest(pkg);
11702        } catch (PackageParserException e) {
11703            res.setError("Failed collect during installPackageLI", e);
11704            return;
11705        }
11706
11707        /* If the installer passed in a manifest digest, compare it now. */
11708        if (args.manifestDigest != null) {
11709            if (DEBUG_INSTALL) {
11710                final String parsedManifest = pkg.manifestDigest == null ? "null"
11711                        : pkg.manifestDigest.toString();
11712                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11713                        + parsedManifest);
11714            }
11715
11716            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11717                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11718                return;
11719            }
11720        } else if (DEBUG_INSTALL) {
11721            final String parsedManifest = pkg.manifestDigest == null
11722                    ? "null" : pkg.manifestDigest.toString();
11723            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11724        }
11725
11726        // Get rid of all references to package scan path via parser.
11727        pp = null;
11728        String oldCodePath = null;
11729        boolean systemApp = false;
11730        synchronized (mPackages) {
11731            // Check if installing already existing package
11732            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11733                String oldName = mSettings.mRenamedPackages.get(pkgName);
11734                if (pkg.mOriginalPackages != null
11735                        && pkg.mOriginalPackages.contains(oldName)
11736                        && mPackages.containsKey(oldName)) {
11737                    // This package is derived from an original package,
11738                    // and this device has been updating from that original
11739                    // name.  We must continue using the original name, so
11740                    // rename the new package here.
11741                    pkg.setPackageName(oldName);
11742                    pkgName = pkg.packageName;
11743                    replace = true;
11744                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11745                            + oldName + " pkgName=" + pkgName);
11746                } else if (mPackages.containsKey(pkgName)) {
11747                    // This package, under its official name, already exists
11748                    // on the device; we should replace it.
11749                    replace = true;
11750                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11751                }
11752
11753                // Prevent apps opting out from runtime permissions
11754                if (replace) {
11755                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11756                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11757                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11758                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11759                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11760                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11761                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11762                                        + " doesn't support runtime permissions but the old"
11763                                        + " target SDK " + oldTargetSdk + " does.");
11764                        return;
11765                    }
11766                }
11767            }
11768
11769            PackageSetting ps = mSettings.mPackages.get(pkgName);
11770            if (ps != null) {
11771                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11772
11773                // Quick sanity check that we're signed correctly if updating;
11774                // we'll check this again later when scanning, but we want to
11775                // bail early here before tripping over redefined permissions.
11776                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11777                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11778                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11779                                + pkg.packageName + " upgrade keys do not match the "
11780                                + "previously installed version");
11781                        return;
11782                    }
11783                } else {
11784                    try {
11785                        verifySignaturesLP(ps, pkg);
11786                    } catch (PackageManagerException e) {
11787                        res.setError(e.error, e.getMessage());
11788                        return;
11789                    }
11790                }
11791
11792                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11793                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11794                    systemApp = (ps.pkg.applicationInfo.flags &
11795                            ApplicationInfo.FLAG_SYSTEM) != 0;
11796                }
11797                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11798            }
11799
11800            // Check whether the newly-scanned package wants to define an already-defined perm
11801            int N = pkg.permissions.size();
11802            for (int i = N-1; i >= 0; i--) {
11803                PackageParser.Permission perm = pkg.permissions.get(i);
11804                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11805                if (bp != null) {
11806                    // If the defining package is signed with our cert, it's okay.  This
11807                    // also includes the "updating the same package" case, of course.
11808                    // "updating same package" could also involve key-rotation.
11809                    final boolean sigsOk;
11810                    if (bp.sourcePackage.equals(pkg.packageName)
11811                            && (bp.packageSetting instanceof PackageSetting)
11812                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
11813                                    scanFlags))) {
11814                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11815                    } else {
11816                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11817                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11818                    }
11819                    if (!sigsOk) {
11820                        // If the owning package is the system itself, we log but allow
11821                        // install to proceed; we fail the install on all other permission
11822                        // redefinitions.
11823                        if (!bp.sourcePackage.equals("android")) {
11824                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11825                                    + pkg.packageName + " attempting to redeclare permission "
11826                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11827                            res.origPermission = perm.info.name;
11828                            res.origPackage = bp.sourcePackage;
11829                            return;
11830                        } else {
11831                            Slog.w(TAG, "Package " + pkg.packageName
11832                                    + " attempting to redeclare system permission "
11833                                    + perm.info.name + "; ignoring new declaration");
11834                            pkg.permissions.remove(i);
11835                        }
11836                    }
11837                }
11838            }
11839
11840        }
11841
11842        if (systemApp && onExternal) {
11843            // Disable updates to system apps on sdcard
11844            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11845                    "Cannot install updates to system apps on sdcard");
11846            return;
11847        }
11848
11849        if (args.move != null) {
11850            // We did an in-place move, so dex is ready to roll
11851            scanFlags |= SCAN_NO_DEX;
11852            scanFlags |= SCAN_MOVE;
11853        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
11854            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
11855            scanFlags |= SCAN_NO_DEX;
11856
11857            try {
11858                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
11859                        true /* extract libs */);
11860            } catch (PackageManagerException pme) {
11861                Slog.e(TAG, "Error deriving application ABI", pme);
11862                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
11863                return;
11864            }
11865
11866            // Run dexopt before old package gets removed, to minimize time when app is unavailable
11867            int result = mPackageDexOptimizer
11868                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
11869                            false /* defer */, false /* inclDependencies */);
11870            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11871                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11872                return;
11873            }
11874        }
11875
11876        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11877            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11878            return;
11879        }
11880
11881        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
11882
11883        if (replace) {
11884            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
11885                    installerPackageName, volumeUuid, res);
11886        } else {
11887            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11888                    args.user, installerPackageName, volumeUuid, res);
11889        }
11890        synchronized (mPackages) {
11891            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11892            if (ps != null) {
11893                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11894            }
11895        }
11896    }
11897
11898    private void startIntentFilterVerifications(int userId, boolean replacing,
11899            PackageParser.Package pkg) {
11900        if (mIntentFilterVerifierComponent == null) {
11901            Slog.w(TAG, "No IntentFilter verification will not be done as "
11902                    + "there is no IntentFilterVerifier available!");
11903            return;
11904        }
11905
11906        final int verifierUid = getPackageUid(
11907                mIntentFilterVerifierComponent.getPackageName(),
11908                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11909
11910        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11911        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11912        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
11913        mHandler.sendMessage(msg);
11914    }
11915
11916    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
11917            PackageParser.Package pkg) {
11918        int size = pkg.activities.size();
11919        if (size == 0) {
11920            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11921                    "No activity, so no need to verify any IntentFilter!");
11922            return;
11923        }
11924
11925        final boolean hasDomainURLs = hasDomainURLs(pkg);
11926        if (!hasDomainURLs) {
11927            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11928                    "No domain URLs, so no need to verify any IntentFilter!");
11929            return;
11930        }
11931
11932        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
11933                + " if any IntentFilter from the " + size
11934                + " Activities needs verification ...");
11935
11936        int count = 0;
11937        final String packageName = pkg.packageName;
11938
11939        synchronized (mPackages) {
11940            // If this is a new install and we see that we've already run verification for this
11941            // package, we have nothing to do: it means the state was restored from backup.
11942            if (!replacing) {
11943                IntentFilterVerificationInfo ivi =
11944                        mSettings.getIntentFilterVerificationLPr(packageName);
11945                if (ivi != null) {
11946                    if (DEBUG_DOMAIN_VERIFICATION) {
11947                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
11948                                + ivi.getStatusString());
11949                    }
11950                    return;
11951                }
11952            }
11953
11954            // If any filters need to be verified, then all need to be.
11955            boolean needToVerify = false;
11956            for (PackageParser.Activity a : pkg.activities) {
11957                for (ActivityIntentInfo filter : a.intents) {
11958                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
11959                        if (DEBUG_DOMAIN_VERIFICATION) {
11960                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
11961                        }
11962                        needToVerify = true;
11963                        break;
11964                    }
11965                }
11966            }
11967
11968            if (needToVerify) {
11969                final int verificationId = mIntentFilterVerificationToken++;
11970                for (PackageParser.Activity a : pkg.activities) {
11971                    for (ActivityIntentInfo filter : a.intents) {
11972                        boolean needsFilterVerification = filter.hasWebDataURI();
11973                        if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11974                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11975                                    "Verification needed for IntentFilter:" + filter.toString());
11976                            mIntentFilterVerifier.addOneIntentFilterVerification(
11977                                    verifierUid, userId, verificationId, filter, packageName);
11978                            count++;
11979                        }
11980                    }
11981                }
11982            }
11983        }
11984
11985        if (count > 0) {
11986            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
11987                    + " IntentFilter verification" + (count > 1 ? "s" : "")
11988                    +  " for userId:" + userId);
11989            mIntentFilterVerifier.startVerifications(userId);
11990        } else {
11991            if (DEBUG_DOMAIN_VERIFICATION) {
11992                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
11993            }
11994        }
11995    }
11996
11997    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11998        final ComponentName cn  = filter.activity.getComponentName();
11999        final String packageName = cn.getPackageName();
12000
12001        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12002                packageName);
12003        if (ivi == null) {
12004            return true;
12005        }
12006        int status = ivi.getStatus();
12007        switch (status) {
12008            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12009            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12010                return true;
12011
12012            default:
12013                // Nothing to do
12014                return false;
12015        }
12016    }
12017
12018    private static boolean isMultiArch(PackageSetting ps) {
12019        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12020    }
12021
12022    private static boolean isMultiArch(ApplicationInfo info) {
12023        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12024    }
12025
12026    private static boolean isExternal(PackageParser.Package pkg) {
12027        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12028    }
12029
12030    private static boolean isExternal(PackageSetting ps) {
12031        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12032    }
12033
12034    private static boolean isExternal(ApplicationInfo info) {
12035        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12036    }
12037
12038    private static boolean isSystemApp(PackageParser.Package pkg) {
12039        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12040    }
12041
12042    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12043        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12044    }
12045
12046    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12047        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12048    }
12049
12050    private static boolean isSystemApp(PackageSetting ps) {
12051        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12052    }
12053
12054    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12055        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12056    }
12057
12058    private int packageFlagsToInstallFlags(PackageSetting ps) {
12059        int installFlags = 0;
12060        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12061            // This existing package was an external ASEC install when we have
12062            // the external flag without a UUID
12063            installFlags |= PackageManager.INSTALL_EXTERNAL;
12064        }
12065        if (ps.isForwardLocked()) {
12066            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12067        }
12068        return installFlags;
12069    }
12070
12071    private void deleteTempPackageFiles() {
12072        final FilenameFilter filter = new FilenameFilter() {
12073            public boolean accept(File dir, String name) {
12074                return name.startsWith("vmdl") && name.endsWith(".tmp");
12075            }
12076        };
12077        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12078            file.delete();
12079        }
12080    }
12081
12082    @Override
12083    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12084            int flags) {
12085        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12086                flags);
12087    }
12088
12089    @Override
12090    public void deletePackage(final String packageName,
12091            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12092        mContext.enforceCallingOrSelfPermission(
12093                android.Manifest.permission.DELETE_PACKAGES, null);
12094        final int uid = Binder.getCallingUid();
12095        if (UserHandle.getUserId(uid) != userId) {
12096            mContext.enforceCallingPermission(
12097                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12098                    "deletePackage for user " + userId);
12099        }
12100        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12101            try {
12102                observer.onPackageDeleted(packageName,
12103                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12104            } catch (RemoteException re) {
12105            }
12106            return;
12107        }
12108
12109        boolean uninstallBlocked = false;
12110        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12111            int[] users = sUserManager.getUserIds();
12112            for (int i = 0; i < users.length; ++i) {
12113                if (getBlockUninstallForUser(packageName, users[i])) {
12114                    uninstallBlocked = true;
12115                    break;
12116                }
12117            }
12118        } else {
12119            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12120        }
12121        if (uninstallBlocked) {
12122            try {
12123                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12124                        null);
12125            } catch (RemoteException re) {
12126            }
12127            return;
12128        }
12129
12130        if (DEBUG_REMOVE) {
12131            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12132        }
12133        // Queue up an async operation since the package deletion may take a little while.
12134        mHandler.post(new Runnable() {
12135            public void run() {
12136                mHandler.removeCallbacks(this);
12137                final int returnCode = deletePackageX(packageName, userId, flags);
12138                if (observer != null) {
12139                    try {
12140                        observer.onPackageDeleted(packageName, returnCode, null);
12141                    } catch (RemoteException e) {
12142                        Log.i(TAG, "Observer no longer exists.");
12143                    } //end catch
12144                } //end if
12145            } //end run
12146        });
12147    }
12148
12149    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12150        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12151                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12152        try {
12153            if (dpm != null) {
12154                if (dpm.isDeviceOwner(packageName)) {
12155                    return true;
12156                }
12157                int[] users;
12158                if (userId == UserHandle.USER_ALL) {
12159                    users = sUserManager.getUserIds();
12160                } else {
12161                    users = new int[]{userId};
12162                }
12163                for (int i = 0; i < users.length; ++i) {
12164                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12165                        return true;
12166                    }
12167                }
12168            }
12169        } catch (RemoteException e) {
12170        }
12171        return false;
12172    }
12173
12174    /**
12175     *  This method is an internal method that could be get invoked either
12176     *  to delete an installed package or to clean up a failed installation.
12177     *  After deleting an installed package, a broadcast is sent to notify any
12178     *  listeners that the package has been installed. For cleaning up a failed
12179     *  installation, the broadcast is not necessary since the package's
12180     *  installation wouldn't have sent the initial broadcast either
12181     *  The key steps in deleting a package are
12182     *  deleting the package information in internal structures like mPackages,
12183     *  deleting the packages base directories through installd
12184     *  updating mSettings to reflect current status
12185     *  persisting settings for later use
12186     *  sending a broadcast if necessary
12187     */
12188    private int deletePackageX(String packageName, int userId, int flags) {
12189        final PackageRemovedInfo info = new PackageRemovedInfo();
12190        final boolean res;
12191
12192        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12193                ? UserHandle.ALL : new UserHandle(userId);
12194
12195        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12196            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12197            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12198        }
12199
12200        boolean removedForAllUsers = false;
12201        boolean systemUpdate = false;
12202
12203        // for the uninstall-updates case and restricted profiles, remember the per-
12204        // userhandle installed state
12205        int[] allUsers;
12206        boolean[] perUserInstalled;
12207        synchronized (mPackages) {
12208            PackageSetting ps = mSettings.mPackages.get(packageName);
12209            allUsers = sUserManager.getUserIds();
12210            perUserInstalled = new boolean[allUsers.length];
12211            for (int i = 0; i < allUsers.length; i++) {
12212                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12213            }
12214        }
12215
12216        synchronized (mInstallLock) {
12217            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12218            res = deletePackageLI(packageName, removeForUser,
12219                    true, allUsers, perUserInstalled,
12220                    flags | REMOVE_CHATTY, info, true);
12221            systemUpdate = info.isRemovedPackageSystemUpdate;
12222            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12223                removedForAllUsers = true;
12224            }
12225            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12226                    + " removedForAllUsers=" + removedForAllUsers);
12227        }
12228
12229        if (res) {
12230            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12231
12232            // If the removed package was a system update, the old system package
12233            // was re-enabled; we need to broadcast this information
12234            if (systemUpdate) {
12235                Bundle extras = new Bundle(1);
12236                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12237                        ? info.removedAppId : info.uid);
12238                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12239
12240                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12241                        extras, null, null, null);
12242                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12243                        extras, null, null, null);
12244                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12245                        null, packageName, null, null);
12246            }
12247        }
12248        // Force a gc here.
12249        Runtime.getRuntime().gc();
12250        // Delete the resources here after sending the broadcast to let
12251        // other processes clean up before deleting resources.
12252        if (info.args != null) {
12253            synchronized (mInstallLock) {
12254                info.args.doPostDeleteLI(true);
12255            }
12256        }
12257
12258        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12259    }
12260
12261    class PackageRemovedInfo {
12262        String removedPackage;
12263        int uid = -1;
12264        int removedAppId = -1;
12265        int[] removedUsers = null;
12266        boolean isRemovedPackageSystemUpdate = false;
12267        // Clean up resources deleted packages.
12268        InstallArgs args = null;
12269
12270        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12271            Bundle extras = new Bundle(1);
12272            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12273            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12274            if (replacing) {
12275                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12276            }
12277            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12278            if (removedPackage != null) {
12279                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12280                        extras, null, null, removedUsers);
12281                if (fullRemove && !replacing) {
12282                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12283                            extras, null, null, removedUsers);
12284                }
12285            }
12286            if (removedAppId >= 0) {
12287                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12288                        removedUsers);
12289            }
12290        }
12291    }
12292
12293    /*
12294     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12295     * flag is not set, the data directory is removed as well.
12296     * make sure this flag is set for partially installed apps. If not its meaningless to
12297     * delete a partially installed application.
12298     */
12299    private void removePackageDataLI(PackageSetting ps,
12300            int[] allUserHandles, boolean[] perUserInstalled,
12301            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12302        String packageName = ps.name;
12303        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12304        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12305        // Retrieve object to delete permissions for shared user later on
12306        final PackageSetting deletedPs;
12307        // reader
12308        synchronized (mPackages) {
12309            deletedPs = mSettings.mPackages.get(packageName);
12310            if (outInfo != null) {
12311                outInfo.removedPackage = packageName;
12312                outInfo.removedUsers = deletedPs != null
12313                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12314                        : null;
12315            }
12316        }
12317        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12318            removeDataDirsLI(ps.volumeUuid, packageName);
12319            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12320        }
12321        // writer
12322        synchronized (mPackages) {
12323            if (deletedPs != null) {
12324                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12325                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12326                    clearDefaultBrowserIfNeeded(packageName);
12327                    if (outInfo != null) {
12328                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12329                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12330                    }
12331                    updatePermissionsLPw(deletedPs.name, null, 0);
12332                    if (deletedPs.sharedUser != null) {
12333                        // Remove permissions associated with package. Since runtime
12334                        // permissions are per user we have to kill the removed package
12335                        // or packages running under the shared user of the removed
12336                        // package if revoking the permissions requested only by the removed
12337                        // package is successful and this causes a change in gids.
12338                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12339                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12340                                    userId);
12341                            if (userIdToKill == UserHandle.USER_ALL
12342                                    || userIdToKill >= UserHandle.USER_OWNER) {
12343                                // If gids changed for this user, kill all affected packages.
12344                                mHandler.post(new Runnable() {
12345                                    @Override
12346                                    public void run() {
12347                                        // This has to happen with no lock held.
12348                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12349                                                KILL_APP_REASON_GIDS_CHANGED);
12350                                    }
12351                                });
12352                            break;
12353                            }
12354                        }
12355                    }
12356                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12357                }
12358                // make sure to preserve per-user disabled state if this removal was just
12359                // a downgrade of a system app to the factory package
12360                if (allUserHandles != null && perUserInstalled != null) {
12361                    if (DEBUG_REMOVE) {
12362                        Slog.d(TAG, "Propagating install state across downgrade");
12363                    }
12364                    for (int i = 0; i < allUserHandles.length; i++) {
12365                        if (DEBUG_REMOVE) {
12366                            Slog.d(TAG, "    user " + allUserHandles[i]
12367                                    + " => " + perUserInstalled[i]);
12368                        }
12369                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12370                    }
12371                }
12372            }
12373            // can downgrade to reader
12374            if (writeSettings) {
12375                // Save settings now
12376                mSettings.writeLPr();
12377            }
12378        }
12379        if (outInfo != null) {
12380            // A user ID was deleted here. Go through all users and remove it
12381            // from KeyStore.
12382            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12383        }
12384    }
12385
12386    static boolean locationIsPrivileged(File path) {
12387        try {
12388            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12389                    .getCanonicalPath();
12390            return path.getCanonicalPath().startsWith(privilegedAppDir);
12391        } catch (IOException e) {
12392            Slog.e(TAG, "Unable to access code path " + path);
12393        }
12394        return false;
12395    }
12396
12397    /*
12398     * Tries to delete system package.
12399     */
12400    private boolean deleteSystemPackageLI(PackageSetting newPs,
12401            int[] allUserHandles, boolean[] perUserInstalled,
12402            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12403        final boolean applyUserRestrictions
12404                = (allUserHandles != null) && (perUserInstalled != null);
12405        PackageSetting disabledPs = null;
12406        // Confirm if the system package has been updated
12407        // An updated system app can be deleted. This will also have to restore
12408        // the system pkg from system partition
12409        // reader
12410        synchronized (mPackages) {
12411            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12412        }
12413        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12414                + " disabledPs=" + disabledPs);
12415        if (disabledPs == null) {
12416            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12417            return false;
12418        } else if (DEBUG_REMOVE) {
12419            Slog.d(TAG, "Deleting system pkg from data partition");
12420        }
12421        if (DEBUG_REMOVE) {
12422            if (applyUserRestrictions) {
12423                Slog.d(TAG, "Remembering install states:");
12424                for (int i = 0; i < allUserHandles.length; i++) {
12425                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12426                }
12427            }
12428        }
12429        // Delete the updated package
12430        outInfo.isRemovedPackageSystemUpdate = true;
12431        if (disabledPs.versionCode < newPs.versionCode) {
12432            // Delete data for downgrades
12433            flags &= ~PackageManager.DELETE_KEEP_DATA;
12434        } else {
12435            // Preserve data by setting flag
12436            flags |= PackageManager.DELETE_KEEP_DATA;
12437        }
12438        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12439                allUserHandles, perUserInstalled, outInfo, writeSettings);
12440        if (!ret) {
12441            return false;
12442        }
12443        // writer
12444        synchronized (mPackages) {
12445            // Reinstate the old system package
12446            mSettings.enableSystemPackageLPw(newPs.name);
12447            // Remove any native libraries from the upgraded package.
12448            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12449        }
12450        // Install the system package
12451        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12452        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12453        if (locationIsPrivileged(disabledPs.codePath)) {
12454            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12455        }
12456
12457        final PackageParser.Package newPkg;
12458        try {
12459            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12460        } catch (PackageManagerException e) {
12461            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12462            return false;
12463        }
12464
12465        // writer
12466        synchronized (mPackages) {
12467            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12468            updatePermissionsLPw(newPkg.packageName, newPkg,
12469                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12470            if (applyUserRestrictions) {
12471                if (DEBUG_REMOVE) {
12472                    Slog.d(TAG, "Propagating install state across reinstall");
12473                }
12474                for (int i = 0; i < allUserHandles.length; i++) {
12475                    if (DEBUG_REMOVE) {
12476                        Slog.d(TAG, "    user " + allUserHandles[i]
12477                                + " => " + perUserInstalled[i]);
12478                    }
12479                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12480                }
12481                // Regardless of writeSettings we need to ensure that this restriction
12482                // state propagation is persisted
12483                mSettings.writeAllUsersPackageRestrictionsLPr();
12484            }
12485            // can downgrade to reader here
12486            if (writeSettings) {
12487                mSettings.writeLPr();
12488            }
12489        }
12490        return true;
12491    }
12492
12493    private boolean deleteInstalledPackageLI(PackageSetting ps,
12494            boolean deleteCodeAndResources, int flags,
12495            int[] allUserHandles, boolean[] perUserInstalled,
12496            PackageRemovedInfo outInfo, boolean writeSettings) {
12497        if (outInfo != null) {
12498            outInfo.uid = ps.appId;
12499        }
12500
12501        // Delete package data from internal structures and also remove data if flag is set
12502        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12503
12504        // Delete application code and resources
12505        if (deleteCodeAndResources && (outInfo != null)) {
12506            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12507                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12508            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12509        }
12510        return true;
12511    }
12512
12513    @Override
12514    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12515            int userId) {
12516        mContext.enforceCallingOrSelfPermission(
12517                android.Manifest.permission.DELETE_PACKAGES, null);
12518        synchronized (mPackages) {
12519            PackageSetting ps = mSettings.mPackages.get(packageName);
12520            if (ps == null) {
12521                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12522                return false;
12523            }
12524            if (!ps.getInstalled(userId)) {
12525                // Can't block uninstall for an app that is not installed or enabled.
12526                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12527                return false;
12528            }
12529            ps.setBlockUninstall(blockUninstall, userId);
12530            mSettings.writePackageRestrictionsLPr(userId);
12531        }
12532        return true;
12533    }
12534
12535    @Override
12536    public boolean getBlockUninstallForUser(String packageName, int userId) {
12537        synchronized (mPackages) {
12538            PackageSetting ps = mSettings.mPackages.get(packageName);
12539            if (ps == null) {
12540                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12541                return false;
12542            }
12543            return ps.getBlockUninstall(userId);
12544        }
12545    }
12546
12547    /*
12548     * This method handles package deletion in general
12549     */
12550    private boolean deletePackageLI(String packageName, UserHandle user,
12551            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12552            int flags, PackageRemovedInfo outInfo,
12553            boolean writeSettings) {
12554        if (packageName == null) {
12555            Slog.w(TAG, "Attempt to delete null packageName.");
12556            return false;
12557        }
12558        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12559        PackageSetting ps;
12560        boolean dataOnly = false;
12561        int removeUser = -1;
12562        int appId = -1;
12563        synchronized (mPackages) {
12564            ps = mSettings.mPackages.get(packageName);
12565            if (ps == null) {
12566                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12567                return false;
12568            }
12569            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12570                    && user.getIdentifier() != UserHandle.USER_ALL) {
12571                // The caller is asking that the package only be deleted for a single
12572                // user.  To do this, we just mark its uninstalled state and delete
12573                // its data.  If this is a system app, we only allow this to happen if
12574                // they have set the special DELETE_SYSTEM_APP which requests different
12575                // semantics than normal for uninstalling system apps.
12576                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12577                ps.setUserState(user.getIdentifier(),
12578                        COMPONENT_ENABLED_STATE_DEFAULT,
12579                        false, //installed
12580                        true,  //stopped
12581                        true,  //notLaunched
12582                        false, //hidden
12583                        null, null, null,
12584                        false, // blockUninstall
12585                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12586                if (!isSystemApp(ps)) {
12587                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12588                        // Other user still have this package installed, so all
12589                        // we need to do is clear this user's data and save that
12590                        // it is uninstalled.
12591                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12592                        removeUser = user.getIdentifier();
12593                        appId = ps.appId;
12594                        scheduleWritePackageRestrictionsLocked(removeUser);
12595                    } else {
12596                        // We need to set it back to 'installed' so the uninstall
12597                        // broadcasts will be sent correctly.
12598                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12599                        ps.setInstalled(true, user.getIdentifier());
12600                    }
12601                } else {
12602                    // This is a system app, so we assume that the
12603                    // other users still have this package installed, so all
12604                    // we need to do is clear this user's data and save that
12605                    // it is uninstalled.
12606                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12607                    removeUser = user.getIdentifier();
12608                    appId = ps.appId;
12609                    scheduleWritePackageRestrictionsLocked(removeUser);
12610                }
12611            }
12612        }
12613
12614        if (removeUser >= 0) {
12615            // From above, we determined that we are deleting this only
12616            // for a single user.  Continue the work here.
12617            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12618            if (outInfo != null) {
12619                outInfo.removedPackage = packageName;
12620                outInfo.removedAppId = appId;
12621                outInfo.removedUsers = new int[] {removeUser};
12622            }
12623            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12624            removeKeystoreDataIfNeeded(removeUser, appId);
12625            schedulePackageCleaning(packageName, removeUser, false);
12626            synchronized (mPackages) {
12627                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12628                    scheduleWritePackageRestrictionsLocked(removeUser);
12629                }
12630                revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(),
12631                        removeUser);
12632            }
12633            return true;
12634        }
12635
12636        if (dataOnly) {
12637            // Delete application data first
12638            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12639            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12640            return true;
12641        }
12642
12643        boolean ret = false;
12644        if (isSystemApp(ps)) {
12645            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12646            // When an updated system application is deleted we delete the existing resources as well and
12647            // fall back to existing code in system partition
12648            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12649                    flags, outInfo, writeSettings);
12650        } else {
12651            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12652            // Kill application pre-emptively especially for apps on sd.
12653            killApplication(packageName, ps.appId, "uninstall pkg");
12654            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12655                    allUserHandles, perUserInstalled,
12656                    outInfo, writeSettings);
12657        }
12658
12659        return ret;
12660    }
12661
12662    private final class ClearStorageConnection implements ServiceConnection {
12663        IMediaContainerService mContainerService;
12664
12665        @Override
12666        public void onServiceConnected(ComponentName name, IBinder service) {
12667            synchronized (this) {
12668                mContainerService = IMediaContainerService.Stub.asInterface(service);
12669                notifyAll();
12670            }
12671        }
12672
12673        @Override
12674        public void onServiceDisconnected(ComponentName name) {
12675        }
12676    }
12677
12678    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12679        final boolean mounted;
12680        if (Environment.isExternalStorageEmulated()) {
12681            mounted = true;
12682        } else {
12683            final String status = Environment.getExternalStorageState();
12684
12685            mounted = status.equals(Environment.MEDIA_MOUNTED)
12686                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12687        }
12688
12689        if (!mounted) {
12690            return;
12691        }
12692
12693        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12694        int[] users;
12695        if (userId == UserHandle.USER_ALL) {
12696            users = sUserManager.getUserIds();
12697        } else {
12698            users = new int[] { userId };
12699        }
12700        final ClearStorageConnection conn = new ClearStorageConnection();
12701        if (mContext.bindServiceAsUser(
12702                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12703            try {
12704                for (int curUser : users) {
12705                    long timeout = SystemClock.uptimeMillis() + 5000;
12706                    synchronized (conn) {
12707                        long now = SystemClock.uptimeMillis();
12708                        while (conn.mContainerService == null && now < timeout) {
12709                            try {
12710                                conn.wait(timeout - now);
12711                            } catch (InterruptedException e) {
12712                            }
12713                        }
12714                    }
12715                    if (conn.mContainerService == null) {
12716                        return;
12717                    }
12718
12719                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12720                    clearDirectory(conn.mContainerService,
12721                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12722                    if (allData) {
12723                        clearDirectory(conn.mContainerService,
12724                                userEnv.buildExternalStorageAppDataDirs(packageName));
12725                        clearDirectory(conn.mContainerService,
12726                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12727                    }
12728                }
12729            } finally {
12730                mContext.unbindService(conn);
12731            }
12732        }
12733    }
12734
12735    @Override
12736    public void clearApplicationUserData(final String packageName,
12737            final IPackageDataObserver observer, final int userId) {
12738        mContext.enforceCallingOrSelfPermission(
12739                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12740        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12741        // Queue up an async operation since the package deletion may take a little while.
12742        mHandler.post(new Runnable() {
12743            public void run() {
12744                mHandler.removeCallbacks(this);
12745                final boolean succeeded;
12746                synchronized (mInstallLock) {
12747                    succeeded = clearApplicationUserDataLI(packageName, userId);
12748                }
12749                clearExternalStorageDataSync(packageName, userId, true);
12750                if (succeeded) {
12751                    // invoke DeviceStorageMonitor's update method to clear any notifications
12752                    DeviceStorageMonitorInternal
12753                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12754                    if (dsm != null) {
12755                        dsm.checkMemory();
12756                    }
12757                }
12758                if(observer != null) {
12759                    try {
12760                        observer.onRemoveCompleted(packageName, succeeded);
12761                    } catch (RemoteException e) {
12762                        Log.i(TAG, "Observer no longer exists.");
12763                    }
12764                } //end if observer
12765            } //end run
12766        });
12767    }
12768
12769    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12770        if (packageName == null) {
12771            Slog.w(TAG, "Attempt to delete null packageName.");
12772            return false;
12773        }
12774
12775        // Try finding details about the requested package
12776        PackageParser.Package pkg;
12777        synchronized (mPackages) {
12778            pkg = mPackages.get(packageName);
12779            if (pkg == null) {
12780                final PackageSetting ps = mSettings.mPackages.get(packageName);
12781                if (ps != null) {
12782                    pkg = ps.pkg;
12783                }
12784            }
12785
12786            if (pkg == null) {
12787                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12788                return false;
12789            }
12790
12791            PackageSetting ps = (PackageSetting) pkg.mExtras;
12792            PermissionsState permissionsState = ps.getPermissionsState();
12793            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
12794        }
12795
12796        // Always delete data directories for package, even if we found no other
12797        // record of app. This helps users recover from UID mismatches without
12798        // resorting to a full data wipe.
12799        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12800        if (retCode < 0) {
12801            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12802            return false;
12803        }
12804
12805        final int appId = pkg.applicationInfo.uid;
12806        removeKeystoreDataIfNeeded(userId, appId);
12807
12808        // Create a native library symlink only if we have native libraries
12809        // and if the native libraries are 32 bit libraries. We do not provide
12810        // this symlink for 64 bit libraries.
12811        if (pkg.applicationInfo.primaryCpuAbi != null &&
12812                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12813            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12814            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12815                    nativeLibPath, userId) < 0) {
12816                Slog.w(TAG, "Failed linking native library dir");
12817                return false;
12818            }
12819        }
12820
12821        return true;
12822    }
12823
12824
12825    /**
12826     * Revokes granted runtime permissions and clears resettable flags
12827     * which are flags that can be set by a user interaction.
12828     *
12829     * @param permissionsState The permission state to reset.
12830     * @param userId The device user for which to do a reset.
12831     */
12832    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
12833            PermissionsState permissionsState, int userId) {
12834        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
12835                | PackageManager.FLAG_PERMISSION_USER_FIXED
12836                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12837
12838        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags);
12839    }
12840
12841    /**
12842     * Revokes granted runtime permissions and clears all flags.
12843     *
12844     * @param permissionsState The permission state to reset.
12845     * @param userId The device user for which to do a reset.
12846     */
12847    private void revokeRuntimePermissionsAndClearAllFlagsLocked(
12848            PermissionsState permissionsState, int userId) {
12849        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId,
12850                PackageManager.MASK_PERMISSION_FLAGS);
12851    }
12852
12853    /**
12854     * Revokes granted runtime permissions and clears certain flags.
12855     *
12856     * @param permissionsState The permission state to reset.
12857     * @param userId The device user for which to do a reset.
12858     * @param flags The flags that is going to be reset.
12859     */
12860    private void revokeRuntimePermissionsAndClearFlagsLocked(
12861            PermissionsState permissionsState, int userId, int flags) {
12862        boolean needsWrite = false;
12863
12864        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
12865            BasePermission bp = mSettings.mPermissions.get(state.getName());
12866            if (bp != null) {
12867                permissionsState.revokeRuntimePermission(bp, userId);
12868                permissionsState.updatePermissionFlags(bp, userId, flags, 0);
12869                needsWrite = true;
12870            }
12871        }
12872
12873        // Ensure default permissions are never cleared.
12874        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
12875
12876        if (needsWrite) {
12877            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
12878        }
12879    }
12880
12881    /**
12882     * Remove entries from the keystore daemon. Will only remove it if the
12883     * {@code appId} is valid.
12884     */
12885    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12886        if (appId < 0) {
12887            return;
12888        }
12889
12890        final KeyStore keyStore = KeyStore.getInstance();
12891        if (keyStore != null) {
12892            if (userId == UserHandle.USER_ALL) {
12893                for (final int individual : sUserManager.getUserIds()) {
12894                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12895                }
12896            } else {
12897                keyStore.clearUid(UserHandle.getUid(userId, appId));
12898            }
12899        } else {
12900            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12901        }
12902    }
12903
12904    @Override
12905    public void deleteApplicationCacheFiles(final String packageName,
12906            final IPackageDataObserver observer) {
12907        mContext.enforceCallingOrSelfPermission(
12908                android.Manifest.permission.DELETE_CACHE_FILES, null);
12909        // Queue up an async operation since the package deletion may take a little while.
12910        final int userId = UserHandle.getCallingUserId();
12911        mHandler.post(new Runnable() {
12912            public void run() {
12913                mHandler.removeCallbacks(this);
12914                final boolean succeded;
12915                synchronized (mInstallLock) {
12916                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12917                }
12918                clearExternalStorageDataSync(packageName, userId, false);
12919                if (observer != null) {
12920                    try {
12921                        observer.onRemoveCompleted(packageName, succeded);
12922                    } catch (RemoteException e) {
12923                        Log.i(TAG, "Observer no longer exists.");
12924                    }
12925                } //end if observer
12926            } //end run
12927        });
12928    }
12929
12930    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12931        if (packageName == null) {
12932            Slog.w(TAG, "Attempt to delete null packageName.");
12933            return false;
12934        }
12935        PackageParser.Package p;
12936        synchronized (mPackages) {
12937            p = mPackages.get(packageName);
12938        }
12939        if (p == null) {
12940            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12941            return false;
12942        }
12943        final ApplicationInfo applicationInfo = p.applicationInfo;
12944        if (applicationInfo == null) {
12945            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12946            return false;
12947        }
12948        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
12949        if (retCode < 0) {
12950            Slog.w(TAG, "Couldn't remove cache files for package: "
12951                       + packageName + " u" + userId);
12952            return false;
12953        }
12954        return true;
12955    }
12956
12957    @Override
12958    public void getPackageSizeInfo(final String packageName, int userHandle,
12959            final IPackageStatsObserver observer) {
12960        mContext.enforceCallingOrSelfPermission(
12961                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12962        if (packageName == null) {
12963            throw new IllegalArgumentException("Attempt to get size of null packageName");
12964        }
12965
12966        PackageStats stats = new PackageStats(packageName, userHandle);
12967
12968        /*
12969         * Queue up an async operation since the package measurement may take a
12970         * little while.
12971         */
12972        Message msg = mHandler.obtainMessage(INIT_COPY);
12973        msg.obj = new MeasureParams(stats, observer);
12974        mHandler.sendMessage(msg);
12975    }
12976
12977    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12978            PackageStats pStats) {
12979        if (packageName == null) {
12980            Slog.w(TAG, "Attempt to get size of null packageName.");
12981            return false;
12982        }
12983        PackageParser.Package p;
12984        boolean dataOnly = false;
12985        String libDirRoot = null;
12986        String asecPath = null;
12987        PackageSetting ps = null;
12988        synchronized (mPackages) {
12989            p = mPackages.get(packageName);
12990            ps = mSettings.mPackages.get(packageName);
12991            if(p == null) {
12992                dataOnly = true;
12993                if((ps == null) || (ps.pkg == null)) {
12994                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12995                    return false;
12996                }
12997                p = ps.pkg;
12998            }
12999            if (ps != null) {
13000                libDirRoot = ps.legacyNativeLibraryPathString;
13001            }
13002            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13003                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13004                if (secureContainerId != null) {
13005                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13006                }
13007            }
13008        }
13009        String publicSrcDir = null;
13010        if(!dataOnly) {
13011            final ApplicationInfo applicationInfo = p.applicationInfo;
13012            if (applicationInfo == null) {
13013                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13014                return false;
13015            }
13016            if (p.isForwardLocked()) {
13017                publicSrcDir = applicationInfo.getBaseResourcePath();
13018            }
13019        }
13020        // TODO: extend to measure size of split APKs
13021        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13022        // not just the first level.
13023        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13024        // just the primary.
13025        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13026        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13027                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13028        if (res < 0) {
13029            return false;
13030        }
13031
13032        // Fix-up for forward-locked applications in ASEC containers.
13033        if (!isExternal(p)) {
13034            pStats.codeSize += pStats.externalCodeSize;
13035            pStats.externalCodeSize = 0L;
13036        }
13037
13038        return true;
13039    }
13040
13041
13042    @Override
13043    public void addPackageToPreferred(String packageName) {
13044        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13045    }
13046
13047    @Override
13048    public void removePackageFromPreferred(String packageName) {
13049        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13050    }
13051
13052    @Override
13053    public List<PackageInfo> getPreferredPackages(int flags) {
13054        return new ArrayList<PackageInfo>();
13055    }
13056
13057    private int getUidTargetSdkVersionLockedLPr(int uid) {
13058        Object obj = mSettings.getUserIdLPr(uid);
13059        if (obj instanceof SharedUserSetting) {
13060            final SharedUserSetting sus = (SharedUserSetting) obj;
13061            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13062            final Iterator<PackageSetting> it = sus.packages.iterator();
13063            while (it.hasNext()) {
13064                final PackageSetting ps = it.next();
13065                if (ps.pkg != null) {
13066                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13067                    if (v < vers) vers = v;
13068                }
13069            }
13070            return vers;
13071        } else if (obj instanceof PackageSetting) {
13072            final PackageSetting ps = (PackageSetting) obj;
13073            if (ps.pkg != null) {
13074                return ps.pkg.applicationInfo.targetSdkVersion;
13075            }
13076        }
13077        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13078    }
13079
13080    @Override
13081    public void addPreferredActivity(IntentFilter filter, int match,
13082            ComponentName[] set, ComponentName activity, int userId) {
13083        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13084                "Adding preferred");
13085    }
13086
13087    private void addPreferredActivityInternal(IntentFilter filter, int match,
13088            ComponentName[] set, ComponentName activity, boolean always, int userId,
13089            String opname) {
13090        // writer
13091        int callingUid = Binder.getCallingUid();
13092        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13093        if (filter.countActions() == 0) {
13094            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13095            return;
13096        }
13097        synchronized (mPackages) {
13098            if (mContext.checkCallingOrSelfPermission(
13099                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13100                    != PackageManager.PERMISSION_GRANTED) {
13101                if (getUidTargetSdkVersionLockedLPr(callingUid)
13102                        < Build.VERSION_CODES.FROYO) {
13103                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13104                            + callingUid);
13105                    return;
13106                }
13107                mContext.enforceCallingOrSelfPermission(
13108                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13109            }
13110
13111            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13112            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13113                    + userId + ":");
13114            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13115            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13116            scheduleWritePackageRestrictionsLocked(userId);
13117        }
13118    }
13119
13120    @Override
13121    public void replacePreferredActivity(IntentFilter filter, int match,
13122            ComponentName[] set, ComponentName activity, int userId) {
13123        if (filter.countActions() != 1) {
13124            throw new IllegalArgumentException(
13125                    "replacePreferredActivity expects filter to have only 1 action.");
13126        }
13127        if (filter.countDataAuthorities() != 0
13128                || filter.countDataPaths() != 0
13129                || filter.countDataSchemes() > 1
13130                || filter.countDataTypes() != 0) {
13131            throw new IllegalArgumentException(
13132                    "replacePreferredActivity expects filter to have no data authorities, " +
13133                    "paths, or types; and at most one scheme.");
13134        }
13135
13136        final int callingUid = Binder.getCallingUid();
13137        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13138        synchronized (mPackages) {
13139            if (mContext.checkCallingOrSelfPermission(
13140                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13141                    != PackageManager.PERMISSION_GRANTED) {
13142                if (getUidTargetSdkVersionLockedLPr(callingUid)
13143                        < Build.VERSION_CODES.FROYO) {
13144                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13145                            + Binder.getCallingUid());
13146                    return;
13147                }
13148                mContext.enforceCallingOrSelfPermission(
13149                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13150            }
13151
13152            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13153            if (pir != null) {
13154                // Get all of the existing entries that exactly match this filter.
13155                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13156                if (existing != null && existing.size() == 1) {
13157                    PreferredActivity cur = existing.get(0);
13158                    if (DEBUG_PREFERRED) {
13159                        Slog.i(TAG, "Checking replace of preferred:");
13160                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13161                        if (!cur.mPref.mAlways) {
13162                            Slog.i(TAG, "  -- CUR; not mAlways!");
13163                        } else {
13164                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13165                            Slog.i(TAG, "  -- CUR: mSet="
13166                                    + Arrays.toString(cur.mPref.mSetComponents));
13167                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13168                            Slog.i(TAG, "  -- NEW: mMatch="
13169                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13170                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13171                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13172                        }
13173                    }
13174                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13175                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13176                            && cur.mPref.sameSet(set)) {
13177                        // Setting the preferred activity to what it happens to be already
13178                        if (DEBUG_PREFERRED) {
13179                            Slog.i(TAG, "Replacing with same preferred activity "
13180                                    + cur.mPref.mShortComponent + " for user "
13181                                    + userId + ":");
13182                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13183                        }
13184                        return;
13185                    }
13186                }
13187
13188                if (existing != null) {
13189                    if (DEBUG_PREFERRED) {
13190                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13191                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13192                    }
13193                    for (int i = 0; i < existing.size(); i++) {
13194                        PreferredActivity pa = existing.get(i);
13195                        if (DEBUG_PREFERRED) {
13196                            Slog.i(TAG, "Removing existing preferred activity "
13197                                    + pa.mPref.mComponent + ":");
13198                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13199                        }
13200                        pir.removeFilter(pa);
13201                    }
13202                }
13203            }
13204            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13205                    "Replacing preferred");
13206        }
13207    }
13208
13209    @Override
13210    public void clearPackagePreferredActivities(String packageName) {
13211        final int uid = Binder.getCallingUid();
13212        // writer
13213        synchronized (mPackages) {
13214            PackageParser.Package pkg = mPackages.get(packageName);
13215            if (pkg == null || pkg.applicationInfo.uid != uid) {
13216                if (mContext.checkCallingOrSelfPermission(
13217                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13218                        != PackageManager.PERMISSION_GRANTED) {
13219                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13220                            < Build.VERSION_CODES.FROYO) {
13221                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13222                                + Binder.getCallingUid());
13223                        return;
13224                    }
13225                    mContext.enforceCallingOrSelfPermission(
13226                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13227                }
13228            }
13229
13230            int user = UserHandle.getCallingUserId();
13231            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13232                scheduleWritePackageRestrictionsLocked(user);
13233            }
13234        }
13235    }
13236
13237    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13238    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13239        ArrayList<PreferredActivity> removed = null;
13240        boolean changed = false;
13241        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13242            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13243            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13244            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13245                continue;
13246            }
13247            Iterator<PreferredActivity> it = pir.filterIterator();
13248            while (it.hasNext()) {
13249                PreferredActivity pa = it.next();
13250                // Mark entry for removal only if it matches the package name
13251                // and the entry is of type "always".
13252                if (packageName == null ||
13253                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13254                                && pa.mPref.mAlways)) {
13255                    if (removed == null) {
13256                        removed = new ArrayList<PreferredActivity>();
13257                    }
13258                    removed.add(pa);
13259                }
13260            }
13261            if (removed != null) {
13262                for (int j=0; j<removed.size(); j++) {
13263                    PreferredActivity pa = removed.get(j);
13264                    pir.removeFilter(pa);
13265                }
13266                changed = true;
13267            }
13268        }
13269        return changed;
13270    }
13271
13272    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13273    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13274        if (userId == UserHandle.USER_ALL) {
13275            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13276                    sUserManager.getUserIds())) {
13277                for (int oneUserId : sUserManager.getUserIds()) {
13278                    scheduleWritePackageRestrictionsLocked(oneUserId);
13279                }
13280            }
13281        } else {
13282            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13283                scheduleWritePackageRestrictionsLocked(userId);
13284            }
13285        }
13286    }
13287
13288
13289    void clearDefaultBrowserIfNeeded(String packageName) {
13290        for (int oneUserId : sUserManager.getUserIds()) {
13291            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13292            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13293            if (packageName.equals(defaultBrowserPackageName)) {
13294                setDefaultBrowserPackageName(null, oneUserId);
13295            }
13296        }
13297    }
13298
13299    @Override
13300    public void resetPreferredActivities(int userId) {
13301        /* TODO: Actually use userId. Why is it being passed in? */
13302        mContext.enforceCallingOrSelfPermission(
13303                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13304        // writer
13305        synchronized (mPackages) {
13306            int user = UserHandle.getCallingUserId();
13307            clearPackagePreferredActivitiesLPw(null, user);
13308            mSettings.readDefaultPreferredAppsLPw(this, user);
13309            scheduleWritePackageRestrictionsLocked(user);
13310        }
13311    }
13312
13313    @Override
13314    public int getPreferredActivities(List<IntentFilter> outFilters,
13315            List<ComponentName> outActivities, String packageName) {
13316
13317        int num = 0;
13318        final int userId = UserHandle.getCallingUserId();
13319        // reader
13320        synchronized (mPackages) {
13321            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13322            if (pir != null) {
13323                final Iterator<PreferredActivity> it = pir.filterIterator();
13324                while (it.hasNext()) {
13325                    final PreferredActivity pa = it.next();
13326                    if (packageName == null
13327                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13328                                    && pa.mPref.mAlways)) {
13329                        if (outFilters != null) {
13330                            outFilters.add(new IntentFilter(pa));
13331                        }
13332                        if (outActivities != null) {
13333                            outActivities.add(pa.mPref.mComponent);
13334                        }
13335                    }
13336                }
13337            }
13338        }
13339
13340        return num;
13341    }
13342
13343    @Override
13344    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13345            int userId) {
13346        int callingUid = Binder.getCallingUid();
13347        if (callingUid != Process.SYSTEM_UID) {
13348            throw new SecurityException(
13349                    "addPersistentPreferredActivity can only be run by the system");
13350        }
13351        if (filter.countActions() == 0) {
13352            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13353            return;
13354        }
13355        synchronized (mPackages) {
13356            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13357                    " :");
13358            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13359            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13360                    new PersistentPreferredActivity(filter, activity));
13361            scheduleWritePackageRestrictionsLocked(userId);
13362        }
13363    }
13364
13365    @Override
13366    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13367        int callingUid = Binder.getCallingUid();
13368        if (callingUid != Process.SYSTEM_UID) {
13369            throw new SecurityException(
13370                    "clearPackagePersistentPreferredActivities can only be run by the system");
13371        }
13372        ArrayList<PersistentPreferredActivity> removed = null;
13373        boolean changed = false;
13374        synchronized (mPackages) {
13375            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13376                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13377                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13378                        .valueAt(i);
13379                if (userId != thisUserId) {
13380                    continue;
13381                }
13382                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13383                while (it.hasNext()) {
13384                    PersistentPreferredActivity ppa = it.next();
13385                    // Mark entry for removal only if it matches the package name.
13386                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13387                        if (removed == null) {
13388                            removed = new ArrayList<PersistentPreferredActivity>();
13389                        }
13390                        removed.add(ppa);
13391                    }
13392                }
13393                if (removed != null) {
13394                    for (int j=0; j<removed.size(); j++) {
13395                        PersistentPreferredActivity ppa = removed.get(j);
13396                        ppir.removeFilter(ppa);
13397                    }
13398                    changed = true;
13399                }
13400            }
13401
13402            if (changed) {
13403                scheduleWritePackageRestrictionsLocked(userId);
13404            }
13405        }
13406    }
13407
13408    /**
13409     * Common machinery for picking apart a restored XML blob and passing
13410     * it to a caller-supplied functor to be applied to the running system.
13411     */
13412    private void restoreFromXml(XmlPullParser parser, int userId,
13413            String expectedStartTag, BlobXmlRestorer functor)
13414            throws IOException, XmlPullParserException {
13415        int type;
13416        while ((type = parser.next()) != XmlPullParser.START_TAG
13417                && type != XmlPullParser.END_DOCUMENT) {
13418        }
13419        if (type != XmlPullParser.START_TAG) {
13420            // oops didn't find a start tag?!
13421            if (DEBUG_BACKUP) {
13422                Slog.e(TAG, "Didn't find start tag during restore");
13423            }
13424            return;
13425        }
13426
13427        // this is supposed to be TAG_PREFERRED_BACKUP
13428        if (!expectedStartTag.equals(parser.getName())) {
13429            if (DEBUG_BACKUP) {
13430                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13431            }
13432            return;
13433        }
13434
13435        // skip interfering stuff, then we're aligned with the backing implementation
13436        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13437        functor.apply(parser, userId);
13438    }
13439
13440    private interface BlobXmlRestorer {
13441        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13442    }
13443
13444    /**
13445     * Non-Binder method, support for the backup/restore mechanism: write the
13446     * full set of preferred activities in its canonical XML format.  Returns the
13447     * XML output as a byte array, or null if there is none.
13448     */
13449    @Override
13450    public byte[] getPreferredActivityBackup(int userId) {
13451        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13452            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13453        }
13454
13455        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13456        try {
13457            final XmlSerializer serializer = new FastXmlSerializer();
13458            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13459            serializer.startDocument(null, true);
13460            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13461
13462            synchronized (mPackages) {
13463                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13464            }
13465
13466            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13467            serializer.endDocument();
13468            serializer.flush();
13469        } catch (Exception e) {
13470            if (DEBUG_BACKUP) {
13471                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13472            }
13473            return null;
13474        }
13475
13476        return dataStream.toByteArray();
13477    }
13478
13479    @Override
13480    public void restorePreferredActivities(byte[] backup, int userId) {
13481        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13482            throw new SecurityException("Only the system may call restorePreferredActivities()");
13483        }
13484
13485        try {
13486            final XmlPullParser parser = Xml.newPullParser();
13487            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13488            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13489                    new BlobXmlRestorer() {
13490                        @Override
13491                        public void apply(XmlPullParser parser, int userId)
13492                                throws XmlPullParserException, IOException {
13493                            synchronized (mPackages) {
13494                                mSettings.readPreferredActivitiesLPw(parser, userId);
13495                            }
13496                        }
13497                    } );
13498        } catch (Exception e) {
13499            if (DEBUG_BACKUP) {
13500                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13501            }
13502        }
13503    }
13504
13505    /**
13506     * Non-Binder method, support for the backup/restore mechanism: write the
13507     * default browser (etc) settings in its canonical XML format.  Returns the default
13508     * browser XML representation as a byte array, or null if there is none.
13509     */
13510    @Override
13511    public byte[] getDefaultAppsBackup(int userId) {
13512        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13513            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13514        }
13515
13516        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13517        try {
13518            final XmlSerializer serializer = new FastXmlSerializer();
13519            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13520            serializer.startDocument(null, true);
13521            serializer.startTag(null, TAG_DEFAULT_APPS);
13522
13523            synchronized (mPackages) {
13524                mSettings.writeDefaultAppsLPr(serializer, userId);
13525            }
13526
13527            serializer.endTag(null, TAG_DEFAULT_APPS);
13528            serializer.endDocument();
13529            serializer.flush();
13530        } catch (Exception e) {
13531            if (DEBUG_BACKUP) {
13532                Slog.e(TAG, "Unable to write default apps for backup", e);
13533            }
13534            return null;
13535        }
13536
13537        return dataStream.toByteArray();
13538    }
13539
13540    @Override
13541    public void restoreDefaultApps(byte[] backup, int userId) {
13542        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13543            throw new SecurityException("Only the system may call restoreDefaultApps()");
13544        }
13545
13546        try {
13547            final XmlPullParser parser = Xml.newPullParser();
13548            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13549            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13550                    new BlobXmlRestorer() {
13551                        @Override
13552                        public void apply(XmlPullParser parser, int userId)
13553                                throws XmlPullParserException, IOException {
13554                            synchronized (mPackages) {
13555                                mSettings.readDefaultAppsLPw(parser, userId);
13556                            }
13557                        }
13558                    } );
13559        } catch (Exception e) {
13560            if (DEBUG_BACKUP) {
13561                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13562            }
13563        }
13564    }
13565
13566    @Override
13567    public byte[] getIntentFilterVerificationBackup(int userId) {
13568        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13569            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
13570        }
13571
13572        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13573        try {
13574            final XmlSerializer serializer = new FastXmlSerializer();
13575            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13576            serializer.startDocument(null, true);
13577            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
13578
13579            synchronized (mPackages) {
13580                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
13581            }
13582
13583            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
13584            serializer.endDocument();
13585            serializer.flush();
13586        } catch (Exception e) {
13587            if (DEBUG_BACKUP) {
13588                Slog.e(TAG, "Unable to write default apps for backup", e);
13589            }
13590            return null;
13591        }
13592
13593        return dataStream.toByteArray();
13594    }
13595
13596    @Override
13597    public void restoreIntentFilterVerification(byte[] backup, int userId) {
13598        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13599            throw new SecurityException("Only the system may call restorePreferredActivities()");
13600        }
13601
13602        try {
13603            final XmlPullParser parser = Xml.newPullParser();
13604            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13605            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
13606                    new BlobXmlRestorer() {
13607                        @Override
13608                        public void apply(XmlPullParser parser, int userId)
13609                                throws XmlPullParserException, IOException {
13610                            synchronized (mPackages) {
13611                                mSettings.readAllDomainVerificationsLPr(parser, userId);
13612                                mSettings.writeLPr();
13613                            }
13614                        }
13615                    } );
13616        } catch (Exception e) {
13617            if (DEBUG_BACKUP) {
13618                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13619            }
13620        }
13621    }
13622
13623    @Override
13624    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13625            int sourceUserId, int targetUserId, int flags) {
13626        mContext.enforceCallingOrSelfPermission(
13627                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13628        int callingUid = Binder.getCallingUid();
13629        enforceOwnerRights(ownerPackage, callingUid);
13630        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13631        if (intentFilter.countActions() == 0) {
13632            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13633            return;
13634        }
13635        synchronized (mPackages) {
13636            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13637                    ownerPackage, targetUserId, flags);
13638            CrossProfileIntentResolver resolver =
13639                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13640            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13641            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13642            if (existing != null) {
13643                int size = existing.size();
13644                for (int i = 0; i < size; i++) {
13645                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13646                        return;
13647                    }
13648                }
13649            }
13650            resolver.addFilter(newFilter);
13651            scheduleWritePackageRestrictionsLocked(sourceUserId);
13652        }
13653    }
13654
13655    @Override
13656    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13657        mContext.enforceCallingOrSelfPermission(
13658                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13659        int callingUid = Binder.getCallingUid();
13660        enforceOwnerRights(ownerPackage, callingUid);
13661        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13662        synchronized (mPackages) {
13663            CrossProfileIntentResolver resolver =
13664                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13665            ArraySet<CrossProfileIntentFilter> set =
13666                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13667            for (CrossProfileIntentFilter filter : set) {
13668                if (filter.getOwnerPackage().equals(ownerPackage)) {
13669                    resolver.removeFilter(filter);
13670                }
13671            }
13672            scheduleWritePackageRestrictionsLocked(sourceUserId);
13673        }
13674    }
13675
13676    // Enforcing that callingUid is owning pkg on userId
13677    private void enforceOwnerRights(String pkg, int callingUid) {
13678        // The system owns everything.
13679        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13680            return;
13681        }
13682        int callingUserId = UserHandle.getUserId(callingUid);
13683        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13684        if (pi == null) {
13685            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13686                    + callingUserId);
13687        }
13688        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13689            throw new SecurityException("Calling uid " + callingUid
13690                    + " does not own package " + pkg);
13691        }
13692    }
13693
13694    @Override
13695    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13696        Intent intent = new Intent(Intent.ACTION_MAIN);
13697        intent.addCategory(Intent.CATEGORY_HOME);
13698
13699        final int callingUserId = UserHandle.getCallingUserId();
13700        List<ResolveInfo> list = queryIntentActivities(intent, null,
13701                PackageManager.GET_META_DATA, callingUserId);
13702        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13703                true, false, false, callingUserId);
13704
13705        allHomeCandidates.clear();
13706        if (list != null) {
13707            for (ResolveInfo ri : list) {
13708                allHomeCandidates.add(ri);
13709            }
13710        }
13711        return (preferred == null || preferred.activityInfo == null)
13712                ? null
13713                : new ComponentName(preferred.activityInfo.packageName,
13714                        preferred.activityInfo.name);
13715    }
13716
13717    @Override
13718    public void setApplicationEnabledSetting(String appPackageName,
13719            int newState, int flags, int userId, String callingPackage) {
13720        if (!sUserManager.exists(userId)) return;
13721        if (callingPackage == null) {
13722            callingPackage = Integer.toString(Binder.getCallingUid());
13723        }
13724        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13725    }
13726
13727    @Override
13728    public void setComponentEnabledSetting(ComponentName componentName,
13729            int newState, int flags, int userId) {
13730        if (!sUserManager.exists(userId)) return;
13731        setEnabledSetting(componentName.getPackageName(),
13732                componentName.getClassName(), newState, flags, userId, null);
13733    }
13734
13735    private void setEnabledSetting(final String packageName, String className, int newState,
13736            final int flags, int userId, String callingPackage) {
13737        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13738              || newState == COMPONENT_ENABLED_STATE_ENABLED
13739              || newState == COMPONENT_ENABLED_STATE_DISABLED
13740              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13741              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13742            throw new IllegalArgumentException("Invalid new component state: "
13743                    + newState);
13744        }
13745        PackageSetting pkgSetting;
13746        final int uid = Binder.getCallingUid();
13747        final int permission = mContext.checkCallingOrSelfPermission(
13748                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13749        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13750        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13751        boolean sendNow = false;
13752        boolean isApp = (className == null);
13753        String componentName = isApp ? packageName : className;
13754        int packageUid = -1;
13755        ArrayList<String> components;
13756
13757        // writer
13758        synchronized (mPackages) {
13759            pkgSetting = mSettings.mPackages.get(packageName);
13760            if (pkgSetting == null) {
13761                if (className == null) {
13762                    throw new IllegalArgumentException(
13763                            "Unknown package: " + packageName);
13764                }
13765                throw new IllegalArgumentException(
13766                        "Unknown component: " + packageName
13767                        + "/" + className);
13768            }
13769            // Allow root and verify that userId is not being specified by a different user
13770            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13771                throw new SecurityException(
13772                        "Permission Denial: attempt to change component state from pid="
13773                        + Binder.getCallingPid()
13774                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13775            }
13776            if (className == null) {
13777                // We're dealing with an application/package level state change
13778                if (pkgSetting.getEnabled(userId) == newState) {
13779                    // Nothing to do
13780                    return;
13781                }
13782                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13783                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13784                    // Don't care about who enables an app.
13785                    callingPackage = null;
13786                }
13787                pkgSetting.setEnabled(newState, userId, callingPackage);
13788                // pkgSetting.pkg.mSetEnabled = newState;
13789            } else {
13790                // We're dealing with a component level state change
13791                // First, verify that this is a valid class name.
13792                PackageParser.Package pkg = pkgSetting.pkg;
13793                if (pkg == null || !pkg.hasComponentClassName(className)) {
13794                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13795                        throw new IllegalArgumentException("Component class " + className
13796                                + " does not exist in " + packageName);
13797                    } else {
13798                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13799                                + className + " does not exist in " + packageName);
13800                    }
13801                }
13802                switch (newState) {
13803                case COMPONENT_ENABLED_STATE_ENABLED:
13804                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13805                        return;
13806                    }
13807                    break;
13808                case COMPONENT_ENABLED_STATE_DISABLED:
13809                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13810                        return;
13811                    }
13812                    break;
13813                case COMPONENT_ENABLED_STATE_DEFAULT:
13814                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13815                        return;
13816                    }
13817                    break;
13818                default:
13819                    Slog.e(TAG, "Invalid new component state: " + newState);
13820                    return;
13821                }
13822            }
13823            scheduleWritePackageRestrictionsLocked(userId);
13824            components = mPendingBroadcasts.get(userId, packageName);
13825            final boolean newPackage = components == null;
13826            if (newPackage) {
13827                components = new ArrayList<String>();
13828            }
13829            if (!components.contains(componentName)) {
13830                components.add(componentName);
13831            }
13832            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
13833                sendNow = true;
13834                // Purge entry from pending broadcast list if another one exists already
13835                // since we are sending one right away.
13836                mPendingBroadcasts.remove(userId, packageName);
13837            } else {
13838                if (newPackage) {
13839                    mPendingBroadcasts.put(userId, packageName, components);
13840                }
13841                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
13842                    // Schedule a message
13843                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
13844                }
13845            }
13846        }
13847
13848        long callingId = Binder.clearCallingIdentity();
13849        try {
13850            if (sendNow) {
13851                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13852                sendPackageChangedBroadcast(packageName,
13853                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13854            }
13855        } finally {
13856            Binder.restoreCallingIdentity(callingId);
13857        }
13858    }
13859
13860    private void sendPackageChangedBroadcast(String packageName,
13861            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13862        if (DEBUG_INSTALL)
13863            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13864                    + componentNames);
13865        Bundle extras = new Bundle(4);
13866        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13867        String nameList[] = new String[componentNames.size()];
13868        componentNames.toArray(nameList);
13869        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13870        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13871        extras.putInt(Intent.EXTRA_UID, packageUid);
13872        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13873                new int[] {UserHandle.getUserId(packageUid)});
13874    }
13875
13876    @Override
13877    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13878        if (!sUserManager.exists(userId)) return;
13879        final int uid = Binder.getCallingUid();
13880        final int permission = mContext.checkCallingOrSelfPermission(
13881                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13882        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13883        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13884        // writer
13885        synchronized (mPackages) {
13886            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
13887                    allowedByPermission, uid, userId)) {
13888                scheduleWritePackageRestrictionsLocked(userId);
13889            }
13890        }
13891    }
13892
13893    @Override
13894    public String getInstallerPackageName(String packageName) {
13895        // reader
13896        synchronized (mPackages) {
13897            return mSettings.getInstallerPackageNameLPr(packageName);
13898        }
13899    }
13900
13901    @Override
13902    public int getApplicationEnabledSetting(String packageName, int userId) {
13903        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13904        int uid = Binder.getCallingUid();
13905        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13906        // reader
13907        synchronized (mPackages) {
13908            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13909        }
13910    }
13911
13912    @Override
13913    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13914        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13915        int uid = Binder.getCallingUid();
13916        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13917        // reader
13918        synchronized (mPackages) {
13919            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13920        }
13921    }
13922
13923    @Override
13924    public void enterSafeMode() {
13925        enforceSystemOrRoot("Only the system can request entering safe mode");
13926
13927        if (!mSystemReady) {
13928            mSafeMode = true;
13929        }
13930    }
13931
13932    @Override
13933    public void systemReady() {
13934        mSystemReady = true;
13935
13936        // Read the compatibilty setting when the system is ready.
13937        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13938                mContext.getContentResolver(),
13939                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13940        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13941        if (DEBUG_SETTINGS) {
13942            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13943        }
13944
13945        synchronized (mPackages) {
13946            // Verify that all of the preferred activity components actually
13947            // exist.  It is possible for applications to be updated and at
13948            // that point remove a previously declared activity component that
13949            // had been set as a preferred activity.  We try to clean this up
13950            // the next time we encounter that preferred activity, but it is
13951            // possible for the user flow to never be able to return to that
13952            // situation so here we do a sanity check to make sure we haven't
13953            // left any junk around.
13954            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13955            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13956                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13957                removed.clear();
13958                for (PreferredActivity pa : pir.filterSet()) {
13959                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13960                        removed.add(pa);
13961                    }
13962                }
13963                if (removed.size() > 0) {
13964                    for (int r=0; r<removed.size(); r++) {
13965                        PreferredActivity pa = removed.get(r);
13966                        Slog.w(TAG, "Removing dangling preferred activity: "
13967                                + pa.mPref.mComponent);
13968                        pir.removeFilter(pa);
13969                    }
13970                    mSettings.writePackageRestrictionsLPr(
13971                            mSettings.mPreferredActivities.keyAt(i));
13972                }
13973            }
13974        }
13975        sUserManager.systemReady();
13976
13977        // If we upgraded grant all default permissions before kicking off.
13978        if (isFirstBoot() || (CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE && mIsUpgrade)) {
13979            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
13980            for (int userId : UserManagerService.getInstance().getUserIds()) {
13981                mDefaultPermissionPolicy.grantDefaultPermissions(userId);
13982            }
13983        }
13984
13985        // Kick off any messages waiting for system ready
13986        if (mPostSystemReadyMessages != null) {
13987            for (Message msg : mPostSystemReadyMessages) {
13988                msg.sendToTarget();
13989            }
13990            mPostSystemReadyMessages = null;
13991        }
13992
13993        // Watch for external volumes that come and go over time
13994        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13995        storage.registerListener(mStorageListener);
13996
13997        mInstallerService.systemReady();
13998        mPackageDexOptimizer.systemReady();
13999    }
14000
14001    @Override
14002    public boolean isSafeMode() {
14003        return mSafeMode;
14004    }
14005
14006    @Override
14007    public boolean hasSystemUidErrors() {
14008        return mHasSystemUidErrors;
14009    }
14010
14011    static String arrayToString(int[] array) {
14012        StringBuffer buf = new StringBuffer(128);
14013        buf.append('[');
14014        if (array != null) {
14015            for (int i=0; i<array.length; i++) {
14016                if (i > 0) buf.append(", ");
14017                buf.append(array[i]);
14018            }
14019        }
14020        buf.append(']');
14021        return buf.toString();
14022    }
14023
14024    static class DumpState {
14025        public static final int DUMP_LIBS = 1 << 0;
14026        public static final int DUMP_FEATURES = 1 << 1;
14027        public static final int DUMP_RESOLVERS = 1 << 2;
14028        public static final int DUMP_PERMISSIONS = 1 << 3;
14029        public static final int DUMP_PACKAGES = 1 << 4;
14030        public static final int DUMP_SHARED_USERS = 1 << 5;
14031        public static final int DUMP_MESSAGES = 1 << 6;
14032        public static final int DUMP_PROVIDERS = 1 << 7;
14033        public static final int DUMP_VERIFIERS = 1 << 8;
14034        public static final int DUMP_PREFERRED = 1 << 9;
14035        public static final int DUMP_PREFERRED_XML = 1 << 10;
14036        public static final int DUMP_KEYSETS = 1 << 11;
14037        public static final int DUMP_VERSION = 1 << 12;
14038        public static final int DUMP_INSTALLS = 1 << 13;
14039        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14040        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14041
14042        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14043
14044        private int mTypes;
14045
14046        private int mOptions;
14047
14048        private boolean mTitlePrinted;
14049
14050        private SharedUserSetting mSharedUser;
14051
14052        public boolean isDumping(int type) {
14053            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14054                return true;
14055            }
14056
14057            return (mTypes & type) != 0;
14058        }
14059
14060        public void setDump(int type) {
14061            mTypes |= type;
14062        }
14063
14064        public boolean isOptionEnabled(int option) {
14065            return (mOptions & option) != 0;
14066        }
14067
14068        public void setOptionEnabled(int option) {
14069            mOptions |= option;
14070        }
14071
14072        public boolean onTitlePrinted() {
14073            final boolean printed = mTitlePrinted;
14074            mTitlePrinted = true;
14075            return printed;
14076        }
14077
14078        public boolean getTitlePrinted() {
14079            return mTitlePrinted;
14080        }
14081
14082        public void setTitlePrinted(boolean enabled) {
14083            mTitlePrinted = enabled;
14084        }
14085
14086        public SharedUserSetting getSharedUser() {
14087            return mSharedUser;
14088        }
14089
14090        public void setSharedUser(SharedUserSetting user) {
14091            mSharedUser = user;
14092        }
14093    }
14094
14095    @Override
14096    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14097        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14098                != PackageManager.PERMISSION_GRANTED) {
14099            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14100                    + Binder.getCallingPid()
14101                    + ", uid=" + Binder.getCallingUid()
14102                    + " without permission "
14103                    + android.Manifest.permission.DUMP);
14104            return;
14105        }
14106
14107        DumpState dumpState = new DumpState();
14108        boolean fullPreferred = false;
14109        boolean checkin = false;
14110
14111        String packageName = null;
14112
14113        int opti = 0;
14114        while (opti < args.length) {
14115            String opt = args[opti];
14116            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14117                break;
14118            }
14119            opti++;
14120
14121            if ("-a".equals(opt)) {
14122                // Right now we only know how to print all.
14123            } else if ("-h".equals(opt)) {
14124                pw.println("Package manager dump options:");
14125                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14126                pw.println("    --checkin: dump for a checkin");
14127                pw.println("    -f: print details of intent filters");
14128                pw.println("    -h: print this help");
14129                pw.println("  cmd may be one of:");
14130                pw.println("    l[ibraries]: list known shared libraries");
14131                pw.println("    f[ibraries]: list device features");
14132                pw.println("    k[eysets]: print known keysets");
14133                pw.println("    r[esolvers]: dump intent resolvers");
14134                pw.println("    perm[issions]: dump permissions");
14135                pw.println("    pref[erred]: print preferred package settings");
14136                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14137                pw.println("    prov[iders]: dump content providers");
14138                pw.println("    p[ackages]: dump installed packages");
14139                pw.println("    s[hared-users]: dump shared user IDs");
14140                pw.println("    m[essages]: print collected runtime messages");
14141                pw.println("    v[erifiers]: print package verifier info");
14142                pw.println("    version: print database version info");
14143                pw.println("    write: write current settings now");
14144                pw.println("    <package.name>: info about given package");
14145                pw.println("    installs: details about install sessions");
14146                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14147                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14148                return;
14149            } else if ("--checkin".equals(opt)) {
14150                checkin = true;
14151            } else if ("-f".equals(opt)) {
14152                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14153            } else {
14154                pw.println("Unknown argument: " + opt + "; use -h for help");
14155            }
14156        }
14157
14158        // Is the caller requesting to dump a particular piece of data?
14159        if (opti < args.length) {
14160            String cmd = args[opti];
14161            opti++;
14162            // Is this a package name?
14163            if ("android".equals(cmd) || cmd.contains(".")) {
14164                packageName = cmd;
14165                // When dumping a single package, we always dump all of its
14166                // filter information since the amount of data will be reasonable.
14167                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14168            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14169                dumpState.setDump(DumpState.DUMP_LIBS);
14170            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14171                dumpState.setDump(DumpState.DUMP_FEATURES);
14172            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14173                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14174            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14175                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14176            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14177                dumpState.setDump(DumpState.DUMP_PREFERRED);
14178            } else if ("preferred-xml".equals(cmd)) {
14179                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14180                if (opti < args.length && "--full".equals(args[opti])) {
14181                    fullPreferred = true;
14182                    opti++;
14183                }
14184            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14185                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14186            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14187                dumpState.setDump(DumpState.DUMP_PACKAGES);
14188            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14189                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14190            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14191                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14192            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14193                dumpState.setDump(DumpState.DUMP_MESSAGES);
14194            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14195                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14196            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14197                    || "intent-filter-verifiers".equals(cmd)) {
14198                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14199            } else if ("version".equals(cmd)) {
14200                dumpState.setDump(DumpState.DUMP_VERSION);
14201            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14202                dumpState.setDump(DumpState.DUMP_KEYSETS);
14203            } else if ("installs".equals(cmd)) {
14204                dumpState.setDump(DumpState.DUMP_INSTALLS);
14205            } else if ("write".equals(cmd)) {
14206                synchronized (mPackages) {
14207                    mSettings.writeLPr();
14208                    pw.println("Settings written.");
14209                    return;
14210                }
14211            }
14212        }
14213
14214        if (checkin) {
14215            pw.println("vers,1");
14216        }
14217
14218        // reader
14219        synchronized (mPackages) {
14220            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14221                if (!checkin) {
14222                    if (dumpState.onTitlePrinted())
14223                        pw.println();
14224                    pw.println("Database versions:");
14225                    pw.print("  SDK Version:");
14226                    pw.print(" internal=");
14227                    pw.print(mSettings.mInternalSdkPlatform);
14228                    pw.print(" external=");
14229                    pw.println(mSettings.mExternalSdkPlatform);
14230                    pw.print("  DB Version:");
14231                    pw.print(" internal=");
14232                    pw.print(mSettings.mInternalDatabaseVersion);
14233                    pw.print(" external=");
14234                    pw.println(mSettings.mExternalDatabaseVersion);
14235                }
14236            }
14237
14238            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14239                if (!checkin) {
14240                    if (dumpState.onTitlePrinted())
14241                        pw.println();
14242                    pw.println("Verifiers:");
14243                    pw.print("  Required: ");
14244                    pw.print(mRequiredVerifierPackage);
14245                    pw.print(" (uid=");
14246                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14247                    pw.println(")");
14248                } else if (mRequiredVerifierPackage != null) {
14249                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14250                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14251                }
14252            }
14253
14254            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14255                    packageName == null) {
14256                if (mIntentFilterVerifierComponent != null) {
14257                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14258                    if (!checkin) {
14259                        if (dumpState.onTitlePrinted())
14260                            pw.println();
14261                        pw.println("Intent Filter Verifier:");
14262                        pw.print("  Using: ");
14263                        pw.print(verifierPackageName);
14264                        pw.print(" (uid=");
14265                        pw.print(getPackageUid(verifierPackageName, 0));
14266                        pw.println(")");
14267                    } else if (verifierPackageName != null) {
14268                        pw.print("ifv,"); pw.print(verifierPackageName);
14269                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14270                    }
14271                } else {
14272                    pw.println();
14273                    pw.println("No Intent Filter Verifier available!");
14274                }
14275            }
14276
14277            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14278                boolean printedHeader = false;
14279                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14280                while (it.hasNext()) {
14281                    String name = it.next();
14282                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14283                    if (!checkin) {
14284                        if (!printedHeader) {
14285                            if (dumpState.onTitlePrinted())
14286                                pw.println();
14287                            pw.println("Libraries:");
14288                            printedHeader = true;
14289                        }
14290                        pw.print("  ");
14291                    } else {
14292                        pw.print("lib,");
14293                    }
14294                    pw.print(name);
14295                    if (!checkin) {
14296                        pw.print(" -> ");
14297                    }
14298                    if (ent.path != null) {
14299                        if (!checkin) {
14300                            pw.print("(jar) ");
14301                            pw.print(ent.path);
14302                        } else {
14303                            pw.print(",jar,");
14304                            pw.print(ent.path);
14305                        }
14306                    } else {
14307                        if (!checkin) {
14308                            pw.print("(apk) ");
14309                            pw.print(ent.apk);
14310                        } else {
14311                            pw.print(",apk,");
14312                            pw.print(ent.apk);
14313                        }
14314                    }
14315                    pw.println();
14316                }
14317            }
14318
14319            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14320                if (dumpState.onTitlePrinted())
14321                    pw.println();
14322                if (!checkin) {
14323                    pw.println("Features:");
14324                }
14325                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14326                while (it.hasNext()) {
14327                    String name = it.next();
14328                    if (!checkin) {
14329                        pw.print("  ");
14330                    } else {
14331                        pw.print("feat,");
14332                    }
14333                    pw.println(name);
14334                }
14335            }
14336
14337            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14338                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14339                        : "Activity Resolver Table:", "  ", packageName,
14340                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14341                    dumpState.setTitlePrinted(true);
14342                }
14343                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14344                        : "Receiver Resolver Table:", "  ", packageName,
14345                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14346                    dumpState.setTitlePrinted(true);
14347                }
14348                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14349                        : "Service Resolver Table:", "  ", packageName,
14350                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14351                    dumpState.setTitlePrinted(true);
14352                }
14353                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14354                        : "Provider Resolver Table:", "  ", packageName,
14355                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14356                    dumpState.setTitlePrinted(true);
14357                }
14358            }
14359
14360            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14361                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14362                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14363                    int user = mSettings.mPreferredActivities.keyAt(i);
14364                    if (pir.dump(pw,
14365                            dumpState.getTitlePrinted()
14366                                ? "\nPreferred Activities User " + user + ":"
14367                                : "Preferred Activities User " + user + ":", "  ",
14368                            packageName, true, false)) {
14369                        dumpState.setTitlePrinted(true);
14370                    }
14371                }
14372            }
14373
14374            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14375                pw.flush();
14376                FileOutputStream fout = new FileOutputStream(fd);
14377                BufferedOutputStream str = new BufferedOutputStream(fout);
14378                XmlSerializer serializer = new FastXmlSerializer();
14379                try {
14380                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14381                    serializer.startDocument(null, true);
14382                    serializer.setFeature(
14383                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14384                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14385                    serializer.endDocument();
14386                    serializer.flush();
14387                } catch (IllegalArgumentException e) {
14388                    pw.println("Failed writing: " + e);
14389                } catch (IllegalStateException e) {
14390                    pw.println("Failed writing: " + e);
14391                } catch (IOException e) {
14392                    pw.println("Failed writing: " + e);
14393                }
14394            }
14395
14396            if (!checkin
14397                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14398                    && packageName == null) {
14399                pw.println();
14400                int count = mSettings.mPackages.size();
14401                if (count == 0) {
14402                    pw.println("No domain preferred apps!");
14403                    pw.println();
14404                } else {
14405                    final String prefix = "  ";
14406                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14407                    if (allPackageSettings.size() == 0) {
14408                        pw.println("No domain preferred apps!");
14409                        pw.println();
14410                    } else {
14411                        pw.println("Domain preferred apps status:");
14412                        pw.println();
14413                        count = 0;
14414                        for (PackageSetting ps : allPackageSettings) {
14415                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14416                            if (ivi == null || ivi.getPackageName() == null) continue;
14417                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14418                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14419                            pw.println(prefix + "Status: " + ivi.getStatusString());
14420                            pw.println();
14421                            count++;
14422                        }
14423                        if (count == 0) {
14424                            pw.println(prefix + "No domain preferred app status!");
14425                            pw.println();
14426                        }
14427                        for (int userId : sUserManager.getUserIds()) {
14428                            pw.println("Domain preferred apps for User " + userId + ":");
14429                            pw.println();
14430                            count = 0;
14431                            for (PackageSetting ps : allPackageSettings) {
14432                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14433                                if (ivi == null || ivi.getPackageName() == null) {
14434                                    continue;
14435                                }
14436                                final int status = ps.getDomainVerificationStatusForUser(userId);
14437                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14438                                    continue;
14439                                }
14440                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14441                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14442                                String statusStr = IntentFilterVerificationInfo.
14443                                        getStatusStringFromValue(status);
14444                                pw.println(prefix + "Status: " + statusStr);
14445                                pw.println();
14446                                count++;
14447                            }
14448                            if (count == 0) {
14449                                pw.println(prefix + "No domain preferred apps!");
14450                                pw.println();
14451                            }
14452                        }
14453                    }
14454                }
14455            }
14456
14457            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14458                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
14459                if (packageName == null) {
14460                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14461                        if (iperm == 0) {
14462                            if (dumpState.onTitlePrinted())
14463                                pw.println();
14464                            pw.println("AppOp Permissions:");
14465                        }
14466                        pw.print("  AppOp Permission ");
14467                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14468                        pw.println(":");
14469                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14470                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14471                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14472                        }
14473                    }
14474                }
14475            }
14476
14477            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14478                boolean printedSomething = false;
14479                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14480                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14481                        continue;
14482                    }
14483                    if (!printedSomething) {
14484                        if (dumpState.onTitlePrinted())
14485                            pw.println();
14486                        pw.println("Registered ContentProviders:");
14487                        printedSomething = true;
14488                    }
14489                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14490                    pw.print("    "); pw.println(p.toString());
14491                }
14492                printedSomething = false;
14493                for (Map.Entry<String, PackageParser.Provider> entry :
14494                        mProvidersByAuthority.entrySet()) {
14495                    PackageParser.Provider p = entry.getValue();
14496                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14497                        continue;
14498                    }
14499                    if (!printedSomething) {
14500                        if (dumpState.onTitlePrinted())
14501                            pw.println();
14502                        pw.println("ContentProvider Authorities:");
14503                        printedSomething = true;
14504                    }
14505                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14506                    pw.print("    "); pw.println(p.toString());
14507                    if (p.info != null && p.info.applicationInfo != null) {
14508                        final String appInfo = p.info.applicationInfo.toString();
14509                        pw.print("      applicationInfo="); pw.println(appInfo);
14510                    }
14511                }
14512            }
14513
14514            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14515                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14516            }
14517
14518            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14519                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
14520            }
14521
14522            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14523                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
14524            }
14525
14526            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14527                // XXX should handle packageName != null by dumping only install data that
14528                // the given package is involved with.
14529                if (dumpState.onTitlePrinted()) pw.println();
14530                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14531            }
14532
14533            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14534                if (dumpState.onTitlePrinted()) pw.println();
14535                mSettings.dumpReadMessagesLPr(pw, dumpState);
14536
14537                pw.println();
14538                pw.println("Package warning messages:");
14539                BufferedReader in = null;
14540                String line = null;
14541                try {
14542                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14543                    while ((line = in.readLine()) != null) {
14544                        if (line.contains("ignored: updated version")) continue;
14545                        pw.println(line);
14546                    }
14547                } catch (IOException ignored) {
14548                } finally {
14549                    IoUtils.closeQuietly(in);
14550                }
14551            }
14552
14553            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14554                BufferedReader in = null;
14555                String line = null;
14556                try {
14557                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14558                    while ((line = in.readLine()) != null) {
14559                        if (line.contains("ignored: updated version")) continue;
14560                        pw.print("msg,");
14561                        pw.println(line);
14562                    }
14563                } catch (IOException ignored) {
14564                } finally {
14565                    IoUtils.closeQuietly(in);
14566                }
14567            }
14568        }
14569    }
14570
14571    // ------- apps on sdcard specific code -------
14572    static final boolean DEBUG_SD_INSTALL = false;
14573
14574    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14575
14576    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14577
14578    private boolean mMediaMounted = false;
14579
14580    static String getEncryptKey() {
14581        try {
14582            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14583                    SD_ENCRYPTION_KEYSTORE_NAME);
14584            if (sdEncKey == null) {
14585                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14586                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14587                if (sdEncKey == null) {
14588                    Slog.e(TAG, "Failed to create encryption keys");
14589                    return null;
14590                }
14591            }
14592            return sdEncKey;
14593        } catch (NoSuchAlgorithmException nsae) {
14594            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14595            return null;
14596        } catch (IOException ioe) {
14597            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14598            return null;
14599        }
14600    }
14601
14602    /*
14603     * Update media status on PackageManager.
14604     */
14605    @Override
14606    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14607        int callingUid = Binder.getCallingUid();
14608        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14609            throw new SecurityException("Media status can only be updated by the system");
14610        }
14611        // reader; this apparently protects mMediaMounted, but should probably
14612        // be a different lock in that case.
14613        synchronized (mPackages) {
14614            Log.i(TAG, "Updating external media status from "
14615                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14616                    + (mediaStatus ? "mounted" : "unmounted"));
14617            if (DEBUG_SD_INSTALL)
14618                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14619                        + ", mMediaMounted=" + mMediaMounted);
14620            if (mediaStatus == mMediaMounted) {
14621                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14622                        : 0, -1);
14623                mHandler.sendMessage(msg);
14624                return;
14625            }
14626            mMediaMounted = mediaStatus;
14627        }
14628        // Queue up an async operation since the package installation may take a
14629        // little while.
14630        mHandler.post(new Runnable() {
14631            public void run() {
14632                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14633            }
14634        });
14635    }
14636
14637    /**
14638     * Called by MountService when the initial ASECs to scan are available.
14639     * Should block until all the ASEC containers are finished being scanned.
14640     */
14641    public void scanAvailableAsecs() {
14642        updateExternalMediaStatusInner(true, false, false);
14643        if (mShouldRestoreconData) {
14644            SELinuxMMAC.setRestoreconDone();
14645            mShouldRestoreconData = false;
14646        }
14647    }
14648
14649    /*
14650     * Collect information of applications on external media, map them against
14651     * existing containers and update information based on current mount status.
14652     * Please note that we always have to report status if reportStatus has been
14653     * set to true especially when unloading packages.
14654     */
14655    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14656            boolean externalStorage) {
14657        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14658        int[] uidArr = EmptyArray.INT;
14659
14660        final String[] list = PackageHelper.getSecureContainerList();
14661        if (ArrayUtils.isEmpty(list)) {
14662            Log.i(TAG, "No secure containers found");
14663        } else {
14664            // Process list of secure containers and categorize them
14665            // as active or stale based on their package internal state.
14666
14667            // reader
14668            synchronized (mPackages) {
14669                for (String cid : list) {
14670                    // Leave stages untouched for now; installer service owns them
14671                    if (PackageInstallerService.isStageName(cid)) continue;
14672
14673                    if (DEBUG_SD_INSTALL)
14674                        Log.i(TAG, "Processing container " + cid);
14675                    String pkgName = getAsecPackageName(cid);
14676                    if (pkgName == null) {
14677                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14678                        continue;
14679                    }
14680                    if (DEBUG_SD_INSTALL)
14681                        Log.i(TAG, "Looking for pkg : " + pkgName);
14682
14683                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14684                    if (ps == null) {
14685                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14686                        continue;
14687                    }
14688
14689                    /*
14690                     * Skip packages that are not external if we're unmounting
14691                     * external storage.
14692                     */
14693                    if (externalStorage && !isMounted && !isExternal(ps)) {
14694                        continue;
14695                    }
14696
14697                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14698                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14699                    // The package status is changed only if the code path
14700                    // matches between settings and the container id.
14701                    if (ps.codePathString != null
14702                            && ps.codePathString.startsWith(args.getCodePath())) {
14703                        if (DEBUG_SD_INSTALL) {
14704                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14705                                    + " at code path: " + ps.codePathString);
14706                        }
14707
14708                        // We do have a valid package installed on sdcard
14709                        processCids.put(args, ps.codePathString);
14710                        final int uid = ps.appId;
14711                        if (uid != -1) {
14712                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14713                        }
14714                    } else {
14715                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14716                                + ps.codePathString);
14717                    }
14718                }
14719            }
14720
14721            Arrays.sort(uidArr);
14722        }
14723
14724        // Process packages with valid entries.
14725        if (isMounted) {
14726            if (DEBUG_SD_INSTALL)
14727                Log.i(TAG, "Loading packages");
14728            loadMediaPackages(processCids, uidArr);
14729            startCleaningPackages();
14730            mInstallerService.onSecureContainersAvailable();
14731        } else {
14732            if (DEBUG_SD_INSTALL)
14733                Log.i(TAG, "Unloading packages");
14734            unloadMediaPackages(processCids, uidArr, reportStatus);
14735        }
14736    }
14737
14738    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14739            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14740        final int size = infos.size();
14741        final String[] packageNames = new String[size];
14742        final int[] packageUids = new int[size];
14743        for (int i = 0; i < size; i++) {
14744            final ApplicationInfo info = infos.get(i);
14745            packageNames[i] = info.packageName;
14746            packageUids[i] = info.uid;
14747        }
14748        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14749                finishedReceiver);
14750    }
14751
14752    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14753            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14754        sendResourcesChangedBroadcast(mediaStatus, replacing,
14755                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14756    }
14757
14758    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14759            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14760        int size = pkgList.length;
14761        if (size > 0) {
14762            // Send broadcasts here
14763            Bundle extras = new Bundle();
14764            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14765            if (uidArr != null) {
14766                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14767            }
14768            if (replacing) {
14769                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14770            }
14771            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14772                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14773            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14774        }
14775    }
14776
14777   /*
14778     * Look at potentially valid container ids from processCids If package
14779     * information doesn't match the one on record or package scanning fails,
14780     * the cid is added to list of removeCids. We currently don't delete stale
14781     * containers.
14782     */
14783    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14784        ArrayList<String> pkgList = new ArrayList<String>();
14785        Set<AsecInstallArgs> keys = processCids.keySet();
14786
14787        for (AsecInstallArgs args : keys) {
14788            String codePath = processCids.get(args);
14789            if (DEBUG_SD_INSTALL)
14790                Log.i(TAG, "Loading container : " + args.cid);
14791            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14792            try {
14793                // Make sure there are no container errors first.
14794                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14795                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14796                            + " when installing from sdcard");
14797                    continue;
14798                }
14799                // Check code path here.
14800                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14801                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14802                            + " does not match one in settings " + codePath);
14803                    continue;
14804                }
14805                // Parse package
14806                int parseFlags = mDefParseFlags;
14807                if (args.isExternalAsec()) {
14808                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
14809                }
14810                if (args.isFwdLocked()) {
14811                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
14812                }
14813
14814                synchronized (mInstallLock) {
14815                    PackageParser.Package pkg = null;
14816                    try {
14817                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
14818                    } catch (PackageManagerException e) {
14819                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
14820                    }
14821                    // Scan the package
14822                    if (pkg != null) {
14823                        /*
14824                         * TODO why is the lock being held? doPostInstall is
14825                         * called in other places without the lock. This needs
14826                         * to be straightened out.
14827                         */
14828                        // writer
14829                        synchronized (mPackages) {
14830                            retCode = PackageManager.INSTALL_SUCCEEDED;
14831                            pkgList.add(pkg.packageName);
14832                            // Post process args
14833                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
14834                                    pkg.applicationInfo.uid);
14835                        }
14836                    } else {
14837                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
14838                    }
14839                }
14840
14841            } finally {
14842                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
14843                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
14844                }
14845            }
14846        }
14847        // writer
14848        synchronized (mPackages) {
14849            // If the platform SDK has changed since the last time we booted,
14850            // we need to re-grant app permission to catch any new ones that
14851            // appear. This is really a hack, and means that apps can in some
14852            // cases get permissions that the user didn't initially explicitly
14853            // allow... it would be nice to have some better way to handle
14854            // this situation.
14855            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
14856            if (regrantPermissions)
14857                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
14858                        + mSdkVersion + "; regranting permissions for external storage");
14859            mSettings.mExternalSdkPlatform = mSdkVersion;
14860
14861            // Make sure group IDs have been assigned, and any permission
14862            // changes in other apps are accounted for
14863            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14864                    | (regrantPermissions
14865                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14866                            : 0));
14867
14868            mSettings.updateExternalDatabaseVersion();
14869
14870            // can downgrade to reader
14871            // Persist settings
14872            mSettings.writeLPr();
14873        }
14874        // Send a broadcast to let everyone know we are done processing
14875        if (pkgList.size() > 0) {
14876            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14877        }
14878    }
14879
14880   /*
14881     * Utility method to unload a list of specified containers
14882     */
14883    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14884        // Just unmount all valid containers.
14885        for (AsecInstallArgs arg : cidArgs) {
14886            synchronized (mInstallLock) {
14887                arg.doPostDeleteLI(false);
14888           }
14889       }
14890   }
14891
14892    /*
14893     * Unload packages mounted on external media. This involves deleting package
14894     * data from internal structures, sending broadcasts about diabled packages,
14895     * gc'ing to free up references, unmounting all secure containers
14896     * corresponding to packages on external media, and posting a
14897     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14898     * that we always have to post this message if status has been requested no
14899     * matter what.
14900     */
14901    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14902            final boolean reportStatus) {
14903        if (DEBUG_SD_INSTALL)
14904            Log.i(TAG, "unloading media packages");
14905        ArrayList<String> pkgList = new ArrayList<String>();
14906        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14907        final Set<AsecInstallArgs> keys = processCids.keySet();
14908        for (AsecInstallArgs args : keys) {
14909            String pkgName = args.getPackageName();
14910            if (DEBUG_SD_INSTALL)
14911                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14912            // Delete package internally
14913            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14914            synchronized (mInstallLock) {
14915                boolean res = deletePackageLI(pkgName, null, false, null, null,
14916                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14917                if (res) {
14918                    pkgList.add(pkgName);
14919                } else {
14920                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14921                    failedList.add(args);
14922                }
14923            }
14924        }
14925
14926        // reader
14927        synchronized (mPackages) {
14928            // We didn't update the settings after removing each package;
14929            // write them now for all packages.
14930            mSettings.writeLPr();
14931        }
14932
14933        // We have to absolutely send UPDATED_MEDIA_STATUS only
14934        // after confirming that all the receivers processed the ordered
14935        // broadcast when packages get disabled, force a gc to clean things up.
14936        // and unload all the containers.
14937        if (pkgList.size() > 0) {
14938            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14939                    new IIntentReceiver.Stub() {
14940                public void performReceive(Intent intent, int resultCode, String data,
14941                        Bundle extras, boolean ordered, boolean sticky,
14942                        int sendingUser) throws RemoteException {
14943                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14944                            reportStatus ? 1 : 0, 1, keys);
14945                    mHandler.sendMessage(msg);
14946                }
14947            });
14948        } else {
14949            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14950                    keys);
14951            mHandler.sendMessage(msg);
14952        }
14953    }
14954
14955    private void loadPrivatePackages(VolumeInfo vol) {
14956        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14957        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14958        synchronized (mInstallLock) {
14959        synchronized (mPackages) {
14960            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14961            for (PackageSetting ps : packages) {
14962                final PackageParser.Package pkg;
14963                try {
14964                    pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14965                    loaded.add(pkg.applicationInfo);
14966                } catch (PackageManagerException e) {
14967                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14968                }
14969            }
14970
14971            // TODO: regrant any permissions that changed based since original install
14972
14973            mSettings.writeLPr();
14974        }
14975        }
14976
14977        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
14978        sendResourcesChangedBroadcast(true, false, loaded, null);
14979    }
14980
14981    private void unloadPrivatePackages(VolumeInfo vol) {
14982        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14983        synchronized (mInstallLock) {
14984        synchronized (mPackages) {
14985            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14986            for (PackageSetting ps : packages) {
14987                if (ps.pkg == null) continue;
14988
14989                final ApplicationInfo info = ps.pkg.applicationInfo;
14990                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14991                if (deletePackageLI(ps.name, null, false, null, null,
14992                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14993                    unloaded.add(info);
14994                } else {
14995                    Slog.w(TAG, "Failed to unload " + ps.codePath);
14996                }
14997            }
14998
14999            mSettings.writeLPr();
15000        }
15001        }
15002
15003        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15004        sendResourcesChangedBroadcast(false, false, unloaded, null);
15005    }
15006
15007    private void unfreezePackage(String packageName) {
15008        synchronized (mPackages) {
15009            final PackageSetting ps = mSettings.mPackages.get(packageName);
15010            if (ps != null) {
15011                ps.frozen = false;
15012            }
15013        }
15014    }
15015
15016    @Override
15017    public int movePackage(final String packageName, final String volumeUuid) {
15018        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15019
15020        final int moveId = mNextMoveId.getAndIncrement();
15021        try {
15022            movePackageInternal(packageName, volumeUuid, moveId);
15023        } catch (PackageManagerException e) {
15024            Slog.w(TAG, "Failed to move " + packageName, e);
15025            mMoveCallbacks.notifyStatusChanged(moveId,
15026                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15027        }
15028        return moveId;
15029    }
15030
15031    private void movePackageInternal(final String packageName, final String volumeUuid,
15032            final int moveId) throws PackageManagerException {
15033        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15034        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15035        final PackageManager pm = mContext.getPackageManager();
15036
15037        final boolean currentAsec;
15038        final String currentVolumeUuid;
15039        final File codeFile;
15040        final String installerPackageName;
15041        final String packageAbiOverride;
15042        final int appId;
15043        final String seinfo;
15044        final String label;
15045
15046        // reader
15047        synchronized (mPackages) {
15048            final PackageParser.Package pkg = mPackages.get(packageName);
15049            final PackageSetting ps = mSettings.mPackages.get(packageName);
15050            if (pkg == null || ps == null) {
15051                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15052            }
15053
15054            if (pkg.applicationInfo.isSystemApp()) {
15055                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15056                        "Cannot move system application");
15057            }
15058
15059            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15060                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15061                        "Package already moved to " + volumeUuid);
15062            }
15063
15064            final File probe = new File(pkg.codePath);
15065            final File probeOat = new File(probe, "oat");
15066            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15067                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15068                        "Move only supported for modern cluster style installs");
15069            }
15070
15071            if (ps.frozen) {
15072                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15073                        "Failed to move already frozen package");
15074            }
15075            ps.frozen = true;
15076
15077            currentAsec = pkg.applicationInfo.isForwardLocked()
15078                    || pkg.applicationInfo.isExternalAsec();
15079            currentVolumeUuid = ps.volumeUuid;
15080            codeFile = new File(pkg.codePath);
15081            installerPackageName = ps.installerPackageName;
15082            packageAbiOverride = ps.cpuAbiOverrideString;
15083            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15084            seinfo = pkg.applicationInfo.seinfo;
15085            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15086        }
15087
15088        // Now that we're guarded by frozen state, kill app during move
15089        killApplication(packageName, appId, "move pkg");
15090
15091        final Bundle extras = new Bundle();
15092        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15093        extras.putString(Intent.EXTRA_TITLE, label);
15094        mMoveCallbacks.notifyCreated(moveId, extras);
15095
15096        int installFlags;
15097        final boolean moveCompleteApp;
15098        final File measurePath;
15099
15100        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15101            installFlags = INSTALL_INTERNAL;
15102            moveCompleteApp = !currentAsec;
15103            measurePath = Environment.getDataAppDirectory(volumeUuid);
15104        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15105            installFlags = INSTALL_EXTERNAL;
15106            moveCompleteApp = false;
15107            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15108        } else {
15109            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15110            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15111                    || !volume.isMountedWritable()) {
15112                unfreezePackage(packageName);
15113                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15114                        "Move location not mounted private volume");
15115            }
15116
15117            Preconditions.checkState(!currentAsec);
15118
15119            installFlags = INSTALL_INTERNAL;
15120            moveCompleteApp = true;
15121            measurePath = Environment.getDataAppDirectory(volumeUuid);
15122        }
15123
15124        final PackageStats stats = new PackageStats(null, -1);
15125        synchronized (mInstaller) {
15126            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15127                unfreezePackage(packageName);
15128                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15129                        "Failed to measure package size");
15130            }
15131        }
15132
15133        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15134                + stats.dataSize);
15135
15136        final long startFreeBytes = measurePath.getFreeSpace();
15137        final long sizeBytes;
15138        if (moveCompleteApp) {
15139            sizeBytes = stats.codeSize + stats.dataSize;
15140        } else {
15141            sizeBytes = stats.codeSize;
15142        }
15143
15144        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15145            unfreezePackage(packageName);
15146            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15147                    "Not enough free space to move");
15148        }
15149
15150        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15151
15152        final CountDownLatch installedLatch = new CountDownLatch(1);
15153        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15154            @Override
15155            public void onUserActionRequired(Intent intent) throws RemoteException {
15156                throw new IllegalStateException();
15157            }
15158
15159            @Override
15160            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15161                    Bundle extras) throws RemoteException {
15162                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15163                        + PackageManager.installStatusToString(returnCode, msg));
15164
15165                installedLatch.countDown();
15166
15167                // Regardless of success or failure of the move operation,
15168                // always unfreeze the package
15169                unfreezePackage(packageName);
15170
15171                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15172                switch (status) {
15173                    case PackageInstaller.STATUS_SUCCESS:
15174                        mMoveCallbacks.notifyStatusChanged(moveId,
15175                                PackageManager.MOVE_SUCCEEDED);
15176                        break;
15177                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15178                        mMoveCallbacks.notifyStatusChanged(moveId,
15179                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15180                        break;
15181                    default:
15182                        mMoveCallbacks.notifyStatusChanged(moveId,
15183                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15184                        break;
15185                }
15186            }
15187        };
15188
15189        final MoveInfo move;
15190        if (moveCompleteApp) {
15191            // Kick off a thread to report progress estimates
15192            new Thread() {
15193                @Override
15194                public void run() {
15195                    while (true) {
15196                        try {
15197                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15198                                break;
15199                            }
15200                        } catch (InterruptedException ignored) {
15201                        }
15202
15203                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15204                        final int progress = 10 + (int) MathUtils.constrain(
15205                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15206                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15207                    }
15208                }
15209            }.start();
15210
15211            final String dataAppName = codeFile.getName();
15212            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15213                    dataAppName, appId, seinfo);
15214        } else {
15215            move = null;
15216        }
15217
15218        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15219
15220        final Message msg = mHandler.obtainMessage(INIT_COPY);
15221        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15222        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15223                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15224        mHandler.sendMessage(msg);
15225    }
15226
15227    @Override
15228    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15229        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15230
15231        final int realMoveId = mNextMoveId.getAndIncrement();
15232        final Bundle extras = new Bundle();
15233        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15234        mMoveCallbacks.notifyCreated(realMoveId, extras);
15235
15236        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15237            @Override
15238            public void onCreated(int moveId, Bundle extras) {
15239                // Ignored
15240            }
15241
15242            @Override
15243            public void onStatusChanged(int moveId, int status, long estMillis) {
15244                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15245            }
15246        };
15247
15248        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15249        storage.setPrimaryStorageUuid(volumeUuid, callback);
15250        return realMoveId;
15251    }
15252
15253    @Override
15254    public int getMoveStatus(int moveId) {
15255        mContext.enforceCallingOrSelfPermission(
15256                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15257        return mMoveCallbacks.mLastStatus.get(moveId);
15258    }
15259
15260    @Override
15261    public void registerMoveCallback(IPackageMoveObserver callback) {
15262        mContext.enforceCallingOrSelfPermission(
15263                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15264        mMoveCallbacks.register(callback);
15265    }
15266
15267    @Override
15268    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15269        mContext.enforceCallingOrSelfPermission(
15270                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15271        mMoveCallbacks.unregister(callback);
15272    }
15273
15274    @Override
15275    public boolean setInstallLocation(int loc) {
15276        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15277                null);
15278        if (getInstallLocation() == loc) {
15279            return true;
15280        }
15281        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15282                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15283            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15284                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15285            return true;
15286        }
15287        return false;
15288   }
15289
15290    @Override
15291    public int getInstallLocation() {
15292        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15293                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15294                PackageHelper.APP_INSTALL_AUTO);
15295    }
15296
15297    /** Called by UserManagerService */
15298    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15299        mDirtyUsers.remove(userHandle);
15300        mSettings.removeUserLPw(userHandle);
15301        mPendingBroadcasts.remove(userHandle);
15302        if (mInstaller != null) {
15303            // Technically, we shouldn't be doing this with the package lock
15304            // held.  However, this is very rare, and there is already so much
15305            // other disk I/O going on, that we'll let it slide for now.
15306            final StorageManager storage = StorageManager.from(mContext);
15307            final List<VolumeInfo> vols = storage.getVolumes();
15308            for (VolumeInfo vol : vols) {
15309                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
15310                    final String volumeUuid = vol.getFsUuid();
15311                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15312                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15313                }
15314            }
15315        }
15316        mUserNeedsBadging.delete(userHandle);
15317        removeUnusedPackagesLILPw(userManager, userHandle);
15318    }
15319
15320    /**
15321     * We're removing userHandle and would like to remove any downloaded packages
15322     * that are no longer in use by any other user.
15323     * @param userHandle the user being removed
15324     */
15325    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15326        final boolean DEBUG_CLEAN_APKS = false;
15327        int [] users = userManager.getUserIdsLPr();
15328        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15329        while (psit.hasNext()) {
15330            PackageSetting ps = psit.next();
15331            if (ps.pkg == null) {
15332                continue;
15333            }
15334            final String packageName = ps.pkg.packageName;
15335            // Skip over if system app
15336            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15337                continue;
15338            }
15339            if (DEBUG_CLEAN_APKS) {
15340                Slog.i(TAG, "Checking package " + packageName);
15341            }
15342            boolean keep = false;
15343            for (int i = 0; i < users.length; i++) {
15344                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15345                    keep = true;
15346                    if (DEBUG_CLEAN_APKS) {
15347                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15348                                + users[i]);
15349                    }
15350                    break;
15351                }
15352            }
15353            if (!keep) {
15354                if (DEBUG_CLEAN_APKS) {
15355                    Slog.i(TAG, "  Removing package " + packageName);
15356                }
15357                mHandler.post(new Runnable() {
15358                    public void run() {
15359                        deletePackageX(packageName, userHandle, 0);
15360                    } //end run
15361                });
15362            }
15363        }
15364    }
15365
15366    /** Called by UserManagerService */
15367    void createNewUserLILPw(int userHandle, File path) {
15368        if (mInstaller != null) {
15369            mInstaller.createUserConfig(userHandle);
15370            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
15371        }
15372    }
15373
15374    void newUserCreatedLILPw(final int userHandle) {
15375        // We cannot grant the default permissions with a lock held as
15376        // we query providers from other components for default handlers
15377        // such as enabled IMEs, etc.
15378        mHandler.post(new Runnable() {
15379            @Override
15380            public void run() {
15381                mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15382            }
15383        });
15384    }
15385
15386    @Override
15387    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15388        mContext.enforceCallingOrSelfPermission(
15389                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15390                "Only package verification agents can read the verifier device identity");
15391
15392        synchronized (mPackages) {
15393            return mSettings.getVerifierDeviceIdentityLPw();
15394        }
15395    }
15396
15397    @Override
15398    public void setPermissionEnforced(String permission, boolean enforced) {
15399        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15400        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15401            synchronized (mPackages) {
15402                if (mSettings.mReadExternalStorageEnforced == null
15403                        || mSettings.mReadExternalStorageEnforced != enforced) {
15404                    mSettings.mReadExternalStorageEnforced = enforced;
15405                    mSettings.writeLPr();
15406                }
15407            }
15408            // kill any non-foreground processes so we restart them and
15409            // grant/revoke the GID.
15410            final IActivityManager am = ActivityManagerNative.getDefault();
15411            if (am != null) {
15412                final long token = Binder.clearCallingIdentity();
15413                try {
15414                    am.killProcessesBelowForeground("setPermissionEnforcement");
15415                } catch (RemoteException e) {
15416                } finally {
15417                    Binder.restoreCallingIdentity(token);
15418                }
15419            }
15420        } else {
15421            throw new IllegalArgumentException("No selective enforcement for " + permission);
15422        }
15423    }
15424
15425    @Override
15426    @Deprecated
15427    public boolean isPermissionEnforced(String permission) {
15428        return true;
15429    }
15430
15431    @Override
15432    public boolean isStorageLow() {
15433        final long token = Binder.clearCallingIdentity();
15434        try {
15435            final DeviceStorageMonitorInternal
15436                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15437            if (dsm != null) {
15438                return dsm.isMemoryLow();
15439            } else {
15440                return false;
15441            }
15442        } finally {
15443            Binder.restoreCallingIdentity(token);
15444        }
15445    }
15446
15447    @Override
15448    public IPackageInstaller getPackageInstaller() {
15449        return mInstallerService;
15450    }
15451
15452    private boolean userNeedsBadging(int userId) {
15453        int index = mUserNeedsBadging.indexOfKey(userId);
15454        if (index < 0) {
15455            final UserInfo userInfo;
15456            final long token = Binder.clearCallingIdentity();
15457            try {
15458                userInfo = sUserManager.getUserInfo(userId);
15459            } finally {
15460                Binder.restoreCallingIdentity(token);
15461            }
15462            final boolean b;
15463            if (userInfo != null && userInfo.isManagedProfile()) {
15464                b = true;
15465            } else {
15466                b = false;
15467            }
15468            mUserNeedsBadging.put(userId, b);
15469            return b;
15470        }
15471        return mUserNeedsBadging.valueAt(index);
15472    }
15473
15474    @Override
15475    public KeySet getKeySetByAlias(String packageName, String alias) {
15476        if (packageName == null || alias == null) {
15477            return null;
15478        }
15479        synchronized(mPackages) {
15480            final PackageParser.Package pkg = mPackages.get(packageName);
15481            if (pkg == null) {
15482                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15483                throw new IllegalArgumentException("Unknown package: " + packageName);
15484            }
15485            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15486            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15487        }
15488    }
15489
15490    @Override
15491    public KeySet getSigningKeySet(String packageName) {
15492        if (packageName == null) {
15493            return null;
15494        }
15495        synchronized(mPackages) {
15496            final PackageParser.Package pkg = mPackages.get(packageName);
15497            if (pkg == null) {
15498                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15499                throw new IllegalArgumentException("Unknown package: " + packageName);
15500            }
15501            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15502                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15503                throw new SecurityException("May not access signing KeySet of other apps.");
15504            }
15505            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15506            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15507        }
15508    }
15509
15510    @Override
15511    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15512        if (packageName == null || ks == null) {
15513            return false;
15514        }
15515        synchronized(mPackages) {
15516            final PackageParser.Package pkg = mPackages.get(packageName);
15517            if (pkg == null) {
15518                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15519                throw new IllegalArgumentException("Unknown package: " + packageName);
15520            }
15521            IBinder ksh = ks.getToken();
15522            if (ksh instanceof KeySetHandle) {
15523                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15524                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15525            }
15526            return false;
15527        }
15528    }
15529
15530    @Override
15531    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15532        if (packageName == null || ks == null) {
15533            return false;
15534        }
15535        synchronized(mPackages) {
15536            final PackageParser.Package pkg = mPackages.get(packageName);
15537            if (pkg == null) {
15538                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15539                throw new IllegalArgumentException("Unknown package: " + packageName);
15540            }
15541            IBinder ksh = ks.getToken();
15542            if (ksh instanceof KeySetHandle) {
15543                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15544                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15545            }
15546            return false;
15547        }
15548    }
15549
15550    public void getUsageStatsIfNoPackageUsageInfo() {
15551        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15552            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15553            if (usm == null) {
15554                throw new IllegalStateException("UsageStatsManager must be initialized");
15555            }
15556            long now = System.currentTimeMillis();
15557            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15558            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15559                String packageName = entry.getKey();
15560                PackageParser.Package pkg = mPackages.get(packageName);
15561                if (pkg == null) {
15562                    continue;
15563                }
15564                UsageStats usage = entry.getValue();
15565                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15566                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15567            }
15568        }
15569    }
15570
15571    /**
15572     * Check and throw if the given before/after packages would be considered a
15573     * downgrade.
15574     */
15575    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15576            throws PackageManagerException {
15577        if (after.versionCode < before.mVersionCode) {
15578            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15579                    "Update version code " + after.versionCode + " is older than current "
15580                    + before.mVersionCode);
15581        } else if (after.versionCode == before.mVersionCode) {
15582            if (after.baseRevisionCode < before.baseRevisionCode) {
15583                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15584                        "Update base revision code " + after.baseRevisionCode
15585                        + " is older than current " + before.baseRevisionCode);
15586            }
15587
15588            if (!ArrayUtils.isEmpty(after.splitNames)) {
15589                for (int i = 0; i < after.splitNames.length; i++) {
15590                    final String splitName = after.splitNames[i];
15591                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15592                    if (j != -1) {
15593                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15594                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15595                                    "Update split " + splitName + " revision code "
15596                                    + after.splitRevisionCodes[i] + " is older than current "
15597                                    + before.splitRevisionCodes[j]);
15598                        }
15599                    }
15600                }
15601            }
15602        }
15603    }
15604
15605    private static class MoveCallbacks extends Handler {
15606        private static final int MSG_CREATED = 1;
15607        private static final int MSG_STATUS_CHANGED = 2;
15608
15609        private final RemoteCallbackList<IPackageMoveObserver>
15610                mCallbacks = new RemoteCallbackList<>();
15611
15612        private final SparseIntArray mLastStatus = new SparseIntArray();
15613
15614        public MoveCallbacks(Looper looper) {
15615            super(looper);
15616        }
15617
15618        public void register(IPackageMoveObserver callback) {
15619            mCallbacks.register(callback);
15620        }
15621
15622        public void unregister(IPackageMoveObserver callback) {
15623            mCallbacks.unregister(callback);
15624        }
15625
15626        @Override
15627        public void handleMessage(Message msg) {
15628            final SomeArgs args = (SomeArgs) msg.obj;
15629            final int n = mCallbacks.beginBroadcast();
15630            for (int i = 0; i < n; i++) {
15631                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15632                try {
15633                    invokeCallback(callback, msg.what, args);
15634                } catch (RemoteException ignored) {
15635                }
15636            }
15637            mCallbacks.finishBroadcast();
15638            args.recycle();
15639        }
15640
15641        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15642                throws RemoteException {
15643            switch (what) {
15644                case MSG_CREATED: {
15645                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15646                    break;
15647                }
15648                case MSG_STATUS_CHANGED: {
15649                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15650                    break;
15651                }
15652            }
15653        }
15654
15655        private void notifyCreated(int moveId, Bundle extras) {
15656            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15657
15658            final SomeArgs args = SomeArgs.obtain();
15659            args.argi1 = moveId;
15660            args.arg2 = extras;
15661            obtainMessage(MSG_CREATED, args).sendToTarget();
15662        }
15663
15664        private void notifyStatusChanged(int moveId, int status) {
15665            notifyStatusChanged(moveId, status, -1);
15666        }
15667
15668        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15669            Slog.v(TAG, "Move " + moveId + " status " + status);
15670
15671            final SomeArgs args = SomeArgs.obtain();
15672            args.argi1 = moveId;
15673            args.argi2 = status;
15674            args.arg3 = estMillis;
15675            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15676
15677            synchronized (mLastStatus) {
15678                mLastStatus.put(moveId, status);
15679            }
15680        }
15681    }
15682
15683    private final class OnPermissionChangeListeners extends Handler {
15684        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
15685
15686        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
15687                new RemoteCallbackList<>();
15688
15689        public OnPermissionChangeListeners(Looper looper) {
15690            super(looper);
15691        }
15692
15693        @Override
15694        public void handleMessage(Message msg) {
15695            switch (msg.what) {
15696                case MSG_ON_PERMISSIONS_CHANGED: {
15697                    final int uid = msg.arg1;
15698                    handleOnPermissionsChanged(uid);
15699                } break;
15700            }
15701        }
15702
15703        public void addListenerLocked(IOnPermissionsChangeListener listener) {
15704            mPermissionListeners.register(listener);
15705
15706        }
15707
15708        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
15709            mPermissionListeners.unregister(listener);
15710        }
15711
15712        public void onPermissionsChanged(int uid) {
15713            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
15714                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
15715            }
15716        }
15717
15718        private void handleOnPermissionsChanged(int uid) {
15719            final int count = mPermissionListeners.beginBroadcast();
15720            try {
15721                for (int i = 0; i < count; i++) {
15722                    IOnPermissionsChangeListener callback = mPermissionListeners
15723                            .getBroadcastItem(i);
15724                    try {
15725                        callback.onPermissionsChanged(uid);
15726                    } catch (RemoteException e) {
15727                        Log.e(TAG, "Permission listener is dead", e);
15728                    }
15729                }
15730            } finally {
15731                mPermissionListeners.finishBroadcast();
15732            }
15733        }
15734    }
15735
15736    private class PackageManagerInternalImpl extends PackageManagerInternal {
15737        @Override
15738        public void setLocationPackagesProvider(PackagesProvider provider) {
15739            synchronized (mPackages) {
15740                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
15741            }
15742        }
15743
15744        @Override
15745        public void setImePackagesProvider(PackagesProvider provider) {
15746            synchronized (mPackages) {
15747                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
15748            }
15749        }
15750
15751        @Override
15752        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
15753            synchronized (mPackages) {
15754                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
15755            }
15756        }
15757    }
15758}
15759