PackageManagerService.java revision 143e118fa90bbeb8cf558ec0d303639d15ee7db7
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
28import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
29import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
32import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
36import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
37import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
38import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
39import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
43import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
44import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
45import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
46import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
47import static android.content.pm.PackageManager.INSTALL_INTERNAL;
48import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
52import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
53import static android.content.pm.PackageManager.MATCH_ALL;
54import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
55import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
56import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
57import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
58import static android.content.pm.PackageManager.PERMISSION_GRANTED;
59import static android.content.pm.PackageParser.isApkFile;
60import static android.os.Process.PACKAGE_INFO_GID;
61import static android.os.Process.SYSTEM_UID;
62import static android.system.OsConstants.O_CREAT;
63import static android.system.OsConstants.O_RDWR;
64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
65import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
66import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
67import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
68import static com.android.internal.util.ArrayUtils.appendInt;
69import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
71import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
72import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
73import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
74
75import android.Manifest;
76import android.app.ActivityManager;
77import android.app.ActivityManagerNative;
78import android.app.AppGlobals;
79import android.app.IActivityManager;
80import android.app.admin.IDevicePolicyManager;
81import android.app.backup.IBackupManager;
82import android.app.usage.UsageStats;
83import android.app.usage.UsageStatsManager;
84import android.content.BroadcastReceiver;
85import android.content.ComponentName;
86import android.content.Context;
87import android.content.IIntentReceiver;
88import android.content.Intent;
89import android.content.IntentFilter;
90import android.content.IntentSender;
91import android.content.IntentSender.SendIntentException;
92import android.content.ServiceConnection;
93import android.content.pm.ActivityInfo;
94import android.content.pm.ApplicationInfo;
95import android.content.pm.FeatureInfo;
96import android.content.pm.IOnPermissionsChangeListener;
97import android.content.pm.IPackageDataObserver;
98import android.content.pm.IPackageDeleteObserver;
99import android.content.pm.IPackageDeleteObserver2;
100import android.content.pm.IPackageInstallObserver2;
101import android.content.pm.IPackageInstaller;
102import android.content.pm.IPackageManager;
103import android.content.pm.IPackageMoveObserver;
104import android.content.pm.IPackageStatsObserver;
105import android.content.pm.IPackagesProvider;
106import android.content.pm.InstrumentationInfo;
107import android.content.pm.IntentFilterVerificationInfo;
108import android.content.pm.KeySet;
109import android.content.pm.ManifestDigest;
110import android.content.pm.PackageCleanItem;
111import android.content.pm.PackageInfo;
112import android.content.pm.PackageInfoLite;
113import android.content.pm.PackageInstaller;
114import android.content.pm.PackageManager;
115import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
116import android.content.pm.PackageManagerInternal;
117import android.content.pm.PackageParser;
118import android.content.pm.PackageParser.ActivityIntentInfo;
119import android.content.pm.PackageParser.PackageLite;
120import android.content.pm.PackageParser.PackageParserException;
121import android.content.pm.PackageStats;
122import android.content.pm.PackageUserState;
123import android.content.pm.ParceledListSlice;
124import android.content.pm.PermissionGroupInfo;
125import android.content.pm.PermissionInfo;
126import android.content.pm.ProviderInfo;
127import android.content.pm.ResolveInfo;
128import android.content.pm.ServiceInfo;
129import android.content.pm.Signature;
130import android.content.pm.UserInfo;
131import android.content.pm.VerificationParams;
132import android.content.pm.VerifierDeviceIdentity;
133import android.content.pm.VerifierInfo;
134import android.content.res.Resources;
135import android.hardware.display.DisplayManager;
136import android.net.Uri;
137import android.os.Binder;
138import android.os.Build;
139import android.os.Bundle;
140import android.os.Debug;
141import android.os.Environment;
142import android.os.Environment.UserEnvironment;
143import android.os.FileUtils;
144import android.os.Handler;
145import android.os.IBinder;
146import android.os.Looper;
147import android.os.Message;
148import android.os.Parcel;
149import android.os.ParcelFileDescriptor;
150import android.os.Process;
151import android.os.RemoteCallbackList;
152import android.os.RemoteException;
153import android.os.SELinux;
154import android.os.ServiceManager;
155import android.os.SystemClock;
156import android.os.SystemProperties;
157import android.os.UserHandle;
158import android.os.UserManager;
159import android.os.storage.IMountService;
160import android.os.storage.StorageEventListener;
161import android.os.storage.StorageManager;
162import android.os.storage.VolumeInfo;
163import android.os.storage.VolumeRecord;
164import android.security.KeyStore;
165import android.security.SystemKeyStore;
166import android.system.ErrnoException;
167import android.system.Os;
168import android.system.StructStat;
169import android.text.TextUtils;
170import android.text.format.DateUtils;
171import android.util.ArrayMap;
172import android.util.ArraySet;
173import android.util.AtomicFile;
174import android.util.DisplayMetrics;
175import android.util.EventLog;
176import android.util.ExceptionUtils;
177import android.util.Log;
178import android.util.LogPrinter;
179import android.util.MathUtils;
180import android.util.PrintStreamPrinter;
181import android.util.Slog;
182import android.util.SparseArray;
183import android.util.SparseBooleanArray;
184import android.util.SparseIntArray;
185import android.util.Xml;
186import android.view.Display;
187
188import dalvik.system.DexFile;
189import dalvik.system.VMRuntime;
190
191import libcore.io.IoUtils;
192import libcore.util.EmptyArray;
193
194import com.android.internal.R;
195import com.android.internal.app.IMediaContainerService;
196import com.android.internal.app.ResolverActivity;
197import com.android.internal.content.NativeLibraryHelper;
198import com.android.internal.content.PackageHelper;
199import com.android.internal.os.IParcelFileDescriptorFactory;
200import com.android.internal.os.SomeArgs;
201import com.android.internal.os.Zygote;
202import com.android.internal.util.ArrayUtils;
203import com.android.internal.util.FastPrintWriter;
204import com.android.internal.util.FastXmlSerializer;
205import com.android.internal.util.IndentingPrintWriter;
206import com.android.internal.util.Preconditions;
207import com.android.server.EventLogTags;
208import com.android.server.FgThread;
209import com.android.server.IntentResolver;
210import com.android.server.LocalServices;
211import com.android.server.ServiceThread;
212import com.android.server.SystemConfig;
213import com.android.server.Watchdog;
214import com.android.server.pm.PermissionsState.PermissionState;
215import com.android.server.pm.Settings.DatabaseVersion;
216import com.android.server.storage.DeviceStorageMonitorInternal;
217
218import org.xmlpull.v1.XmlPullParser;
219import org.xmlpull.v1.XmlPullParserException;
220import org.xmlpull.v1.XmlSerializer;
221
222import java.io.BufferedInputStream;
223import java.io.BufferedOutputStream;
224import java.io.BufferedReader;
225import java.io.ByteArrayInputStream;
226import java.io.ByteArrayOutputStream;
227import java.io.File;
228import java.io.FileDescriptor;
229import java.io.FileNotFoundException;
230import java.io.FileOutputStream;
231import java.io.FileReader;
232import java.io.FilenameFilter;
233import java.io.IOException;
234import java.io.InputStream;
235import java.io.PrintWriter;
236import java.nio.charset.StandardCharsets;
237import java.security.NoSuchAlgorithmException;
238import java.security.PublicKey;
239import java.security.cert.CertificateEncodingException;
240import java.security.cert.CertificateException;
241import java.text.SimpleDateFormat;
242import java.util.ArrayList;
243import java.util.Arrays;
244import java.util.Collection;
245import java.util.Collections;
246import java.util.Comparator;
247import java.util.Date;
248import java.util.Iterator;
249import java.util.List;
250import java.util.Map;
251import java.util.Objects;
252import java.util.Set;
253import java.util.concurrent.CountDownLatch;
254import java.util.concurrent.TimeUnit;
255import java.util.concurrent.atomic.AtomicBoolean;
256import java.util.concurrent.atomic.AtomicInteger;
257import java.util.concurrent.atomic.AtomicLong;
258
259/**
260 * Keep track of all those .apks everywhere.
261 *
262 * This is very central to the platform's security; please run the unit
263 * tests whenever making modifications here:
264 *
265mmm frameworks/base/tests/AndroidTests
266adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
267adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
268 *
269 * {@hide}
270 */
271public class PackageManagerService extends IPackageManager.Stub {
272    static final String TAG = "PackageManager";
273    static final boolean DEBUG_SETTINGS = false;
274    static final boolean DEBUG_PREFERRED = false;
275    static final boolean DEBUG_UPGRADE = false;
276    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
277    private static final boolean DEBUG_BACKUP = true;
278    private static final boolean DEBUG_INSTALL = false;
279    private static final boolean DEBUG_REMOVE = false;
280    private static final boolean DEBUG_BROADCASTS = false;
281    private static final boolean DEBUG_SHOW_INFO = false;
282    private static final boolean DEBUG_PACKAGE_INFO = false;
283    private static final boolean DEBUG_INTENT_MATCHING = false;
284    private static final boolean DEBUG_PACKAGE_SCANNING = false;
285    private static final boolean DEBUG_VERIFY = false;
286    private static final boolean DEBUG_DEXOPT = false;
287    private static final boolean DEBUG_ABI_SELECTION = false;
288
289    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
290
291    private static final int RADIO_UID = Process.PHONE_UID;
292    private static final int LOG_UID = Process.LOG_UID;
293    private static final int NFC_UID = Process.NFC_UID;
294    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
295    private static final int SHELL_UID = Process.SHELL_UID;
296
297    // Cap the size of permission trees that 3rd party apps can define
298    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
299
300    // Suffix used during package installation when copying/moving
301    // package apks to install directory.
302    private static final String INSTALL_PACKAGE_SUFFIX = "-";
303
304    static final int SCAN_NO_DEX = 1<<1;
305    static final int SCAN_FORCE_DEX = 1<<2;
306    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
307    static final int SCAN_NEW_INSTALL = 1<<4;
308    static final int SCAN_NO_PATHS = 1<<5;
309    static final int SCAN_UPDATE_TIME = 1<<6;
310    static final int SCAN_DEFER_DEX = 1<<7;
311    static final int SCAN_BOOTING = 1<<8;
312    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
313    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
314    static final int SCAN_REQUIRE_KNOWN = 1<<12;
315    static final int SCAN_MOVE = 1<<13;
316    static final int SCAN_INITIAL = 1<<14;
317
318    static final int REMOVE_CHATTY = 1<<16;
319
320    private static final int[] EMPTY_INT_ARRAY = new int[0];
321
322    /**
323     * Timeout (in milliseconds) after which the watchdog should declare that
324     * our handler thread is wedged.  The usual default for such things is one
325     * minute but we sometimes do very lengthy I/O operations on this thread,
326     * such as installing multi-gigabyte applications, so ours needs to be longer.
327     */
328    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
329
330    /**
331     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
332     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
333     * settings entry if available, otherwise we use the hardcoded default.  If it's been
334     * more than this long since the last fstrim, we force one during the boot sequence.
335     *
336     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
337     * one gets run at the next available charging+idle time.  This final mandatory
338     * no-fstrim check kicks in only of the other scheduling criteria is never met.
339     */
340    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
341
342    /**
343     * Whether verification is enabled by default.
344     */
345    private static final boolean DEFAULT_VERIFY_ENABLE = true;
346
347    /**
348     * The default maximum time to wait for the verification agent to return in
349     * milliseconds.
350     */
351    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
352
353    /**
354     * The default response for package verification timeout.
355     *
356     * This can be either PackageManager.VERIFICATION_ALLOW or
357     * PackageManager.VERIFICATION_REJECT.
358     */
359    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
360
361    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
362
363    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
364            DEFAULT_CONTAINER_PACKAGE,
365            "com.android.defcontainer.DefaultContainerService");
366
367    private static final String KILL_APP_REASON_GIDS_CHANGED =
368            "permission grant or revoke changed gids";
369
370    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
371            "permissions revoked";
372
373    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
374
375    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
376
377    /** Permission grant: not grant the permission. */
378    private static final int GRANT_DENIED = 1;
379
380    /** Permission grant: grant the permission as an install permission. */
381    private static final int GRANT_INSTALL = 2;
382
383    /** Permission grant: grant the permission as an install permission for a legacy app. */
384    private static final int GRANT_INSTALL_LEGACY = 3;
385
386    /** Permission grant: grant the permission as a runtime one. */
387    private static final int GRANT_RUNTIME = 4;
388
389    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
390    private static final int GRANT_UPGRADE = 5;
391
392    final ServiceThread mHandlerThread;
393
394    final PackageHandler mHandler;
395
396    /**
397     * Messages for {@link #mHandler} that need to wait for system ready before
398     * being dispatched.
399     */
400    private ArrayList<Message> mPostSystemReadyMessages;
401
402    final int mSdkVersion = Build.VERSION.SDK_INT;
403
404    final Context mContext;
405    final boolean mFactoryTest;
406    final boolean mOnlyCore;
407    final boolean mLazyDexOpt;
408    final long mDexOptLRUThresholdInMills;
409    final DisplayMetrics mMetrics;
410    final int mDefParseFlags;
411    final String[] mSeparateProcesses;
412    final boolean mIsUpgrade;
413
414    // This is where all application persistent data goes.
415    final File mAppDataDir;
416
417    // This is where all application persistent data goes for secondary users.
418    final File mUserAppDataDir;
419
420    /** The location for ASEC container files on internal storage. */
421    final String mAsecInternalPath;
422
423    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
424    // LOCK HELD.  Can be called with mInstallLock held.
425    final Installer mInstaller;
426
427    /** Directory where installed third-party apps stored */
428    final File mAppInstallDir;
429
430    /**
431     * Directory to which applications installed internally have their
432     * 32 bit native libraries copied.
433     */
434    private File mAppLib32InstallDir;
435
436    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
437    // apps.
438    final File mDrmAppPrivateInstallDir;
439
440    // ----------------------------------------------------------------
441
442    // Lock for state used when installing and doing other long running
443    // operations.  Methods that must be called with this lock held have
444    // the suffix "LI".
445    final Object mInstallLock = new Object();
446
447    // ----------------------------------------------------------------
448
449    // Keys are String (package name), values are Package.  This also serves
450    // as the lock for the global state.  Methods that must be called with
451    // this lock held have the prefix "LP".
452    final ArrayMap<String, PackageParser.Package> mPackages =
453            new ArrayMap<String, PackageParser.Package>();
454
455    // Tracks available target package names -> overlay package paths.
456    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
457        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
458
459    final Settings mSettings;
460    boolean mRestoredSettings;
461
462    // System configuration read by SystemConfig.
463    final int[] mGlobalGids;
464    final SparseArray<ArraySet<String>> mSystemPermissions;
465    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
466
467    // If mac_permissions.xml was found for seinfo labeling.
468    boolean mFoundPolicyFile;
469
470    // If a recursive restorecon of /data/data/<pkg> is needed.
471    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
472
473    public static final class SharedLibraryEntry {
474        public final String path;
475        public final String apk;
476
477        SharedLibraryEntry(String _path, String _apk) {
478            path = _path;
479            apk = _apk;
480        }
481    }
482
483    // Currently known shared libraries.
484    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
485            new ArrayMap<String, SharedLibraryEntry>();
486
487    // All available activities, for your resolving pleasure.
488    final ActivityIntentResolver mActivities =
489            new ActivityIntentResolver();
490
491    // All available receivers, for your resolving pleasure.
492    final ActivityIntentResolver mReceivers =
493            new ActivityIntentResolver();
494
495    // All available services, for your resolving pleasure.
496    final ServiceIntentResolver mServices = new ServiceIntentResolver();
497
498    // All available providers, for your resolving pleasure.
499    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
500
501    // Mapping from provider base names (first directory in content URI codePath)
502    // to the provider information.
503    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
504            new ArrayMap<String, PackageParser.Provider>();
505
506    // Mapping from instrumentation class names to info about them.
507    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
508            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
509
510    // Mapping from permission names to info about them.
511    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
512            new ArrayMap<String, PackageParser.PermissionGroup>();
513
514    // Packages whose data we have transfered into another package, thus
515    // should no longer exist.
516    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
517
518    // Broadcast actions that are only available to the system.
519    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
520
521    /** List of packages waiting for verification. */
522    final SparseArray<PackageVerificationState> mPendingVerification
523            = new SparseArray<PackageVerificationState>();
524
525    /** Set of packages associated with each app op permission. */
526    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
527
528    final PackageInstallerService mInstallerService;
529
530    private final PackageDexOptimizer mPackageDexOptimizer;
531
532    private AtomicInteger mNextMoveId = new AtomicInteger();
533    private final MoveCallbacks mMoveCallbacks;
534
535    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
536
537    // Cache of users who need badging.
538    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
539
540    /** Token for keys in mPendingVerification. */
541    private int mPendingVerificationToken = 0;
542
543    volatile boolean mSystemReady;
544    volatile boolean mSafeMode;
545    volatile boolean mHasSystemUidErrors;
546
547    ApplicationInfo mAndroidApplication;
548    final ActivityInfo mResolveActivity = new ActivityInfo();
549    final ResolveInfo mResolveInfo = new ResolveInfo();
550    ComponentName mResolveComponentName;
551    PackageParser.Package mPlatformPackage;
552    ComponentName mCustomResolverComponentName;
553
554    boolean mResolverReplaced = false;
555
556    private final ComponentName mIntentFilterVerifierComponent;
557    private int mIntentFilterVerificationToken = 0;
558
559    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
560            = new SparseArray<IntentFilterVerificationState>();
561
562    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
563            new DefaultPermissionGrantPolicy(this);
564
565    private static class IFVerificationParams {
566        PackageParser.Package pkg;
567        boolean replacing;
568        int userId;
569        int verifierUid;
570
571        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
572                int _userId, int _verifierUid) {
573            pkg = _pkg;
574            replacing = _replacing;
575            userId = _userId;
576            replacing = _replacing;
577            verifierUid = _verifierUid;
578        }
579    }
580
581    private interface IntentFilterVerifier<T extends IntentFilter> {
582        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
583                                               T filter, String packageName);
584        void startVerifications(int userId);
585        void receiveVerificationResponse(int verificationId);
586    }
587
588    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
589        private Context mContext;
590        private ComponentName mIntentFilterVerifierComponent;
591        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
592
593        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
594            mContext = context;
595            mIntentFilterVerifierComponent = verifierComponent;
596        }
597
598        private String getDefaultScheme() {
599            return IntentFilter.SCHEME_HTTPS;
600        }
601
602        @Override
603        public void startVerifications(int userId) {
604            // Launch verifications requests
605            int count = mCurrentIntentFilterVerifications.size();
606            for (int n=0; n<count; n++) {
607                int verificationId = mCurrentIntentFilterVerifications.get(n);
608                final IntentFilterVerificationState ivs =
609                        mIntentFilterVerificationStates.get(verificationId);
610
611                String packageName = ivs.getPackageName();
612
613                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
614                final int filterCount = filters.size();
615                ArraySet<String> domainsSet = new ArraySet<>();
616                for (int m=0; m<filterCount; m++) {
617                    PackageParser.ActivityIntentInfo filter = filters.get(m);
618                    domainsSet.addAll(filter.getHostsList());
619                }
620                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
621                synchronized (mPackages) {
622                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
623                            packageName, domainsList) != null) {
624                        scheduleWriteSettingsLocked();
625                    }
626                }
627                sendVerificationRequest(userId, verificationId, ivs);
628            }
629            mCurrentIntentFilterVerifications.clear();
630        }
631
632        private void sendVerificationRequest(int userId, int verificationId,
633                IntentFilterVerificationState ivs) {
634
635            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
636            verificationIntent.putExtra(
637                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
638                    verificationId);
639            verificationIntent.putExtra(
640                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
641                    getDefaultScheme());
642            verificationIntent.putExtra(
643                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
644                    ivs.getHostsString());
645            verificationIntent.putExtra(
646                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
647                    ivs.getPackageName());
648            verificationIntent.setComponent(mIntentFilterVerifierComponent);
649            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
650
651            UserHandle user = new UserHandle(userId);
652            mContext.sendBroadcastAsUser(verificationIntent, user);
653            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
654                    "Sending IntentFilter verification broadcast");
655        }
656
657        public void receiveVerificationResponse(int verificationId) {
658            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
659
660            final boolean verified = ivs.isVerified();
661
662            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
663            final int count = filters.size();
664            if (DEBUG_DOMAIN_VERIFICATION) {
665                Slog.i(TAG, "Received verification response " + verificationId
666                        + " for " + count + " filters, verified=" + verified);
667            }
668            for (int n=0; n<count; n++) {
669                PackageParser.ActivityIntentInfo filter = filters.get(n);
670                filter.setVerified(verified);
671
672                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
673                        + " verified with result:" + verified + " and hosts:"
674                        + ivs.getHostsString());
675            }
676
677            mIntentFilterVerificationStates.remove(verificationId);
678
679            final String packageName = ivs.getPackageName();
680            IntentFilterVerificationInfo ivi = null;
681
682            synchronized (mPackages) {
683                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
684            }
685            if (ivi == null) {
686                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
687                        + verificationId + " packageName:" + packageName);
688                return;
689            }
690            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
691                    "Updating IntentFilterVerificationInfo for verificationId:" + verificationId);
692
693            synchronized (mPackages) {
694                if (verified) {
695                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
696                } else {
697                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
698                }
699                scheduleWriteSettingsLocked();
700
701                final int userId = ivs.getUserId();
702                if (userId != UserHandle.USER_ALL) {
703                    final int userStatus =
704                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
705
706                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
707                    boolean needUpdate = false;
708
709                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
710                    // already been set by the User thru the Disambiguation dialog
711                    switch (userStatus) {
712                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
713                            if (verified) {
714                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
715                            } else {
716                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
717                            }
718                            needUpdate = true;
719                            break;
720
721                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
722                            if (verified) {
723                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
724                                needUpdate = true;
725                            }
726                            break;
727
728                        default:
729                            // Nothing to do
730                    }
731
732                    if (needUpdate) {
733                        mSettings.updateIntentFilterVerificationStatusLPw(
734                                packageName, updatedStatus, userId);
735                        scheduleWritePackageRestrictionsLocked(userId);
736                    }
737                }
738            }
739        }
740
741        @Override
742        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
743                    ActivityIntentInfo filter, String packageName) {
744            if (!hasValidDomains(filter)) {
745                return false;
746            }
747            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
748            if (ivs == null) {
749                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
750                        packageName);
751            }
752            if (DEBUG_DOMAIN_VERIFICATION) {
753                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
754            }
755            ivs.addFilter(filter);
756            return true;
757        }
758
759        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
760                int userId, int verificationId, String packageName) {
761            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
762                    verifierUid, userId, packageName);
763            ivs.setPendingState();
764            synchronized (mPackages) {
765                mIntentFilterVerificationStates.append(verificationId, ivs);
766                mCurrentIntentFilterVerifications.add(verificationId);
767            }
768            return ivs;
769        }
770    }
771
772    private static boolean hasValidDomains(ActivityIntentInfo filter) {
773        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
774                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
775        if (!hasHTTPorHTTPS) {
776            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
777                    "IntentFilter does not contain any HTTP or HTTPS data scheme");
778            return false;
779        }
780        return true;
781    }
782
783    private IntentFilterVerifier mIntentFilterVerifier;
784
785    // Set of pending broadcasts for aggregating enable/disable of components.
786    static class PendingPackageBroadcasts {
787        // for each user id, a map of <package name -> components within that package>
788        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
789
790        public PendingPackageBroadcasts() {
791            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
792        }
793
794        public ArrayList<String> get(int userId, String packageName) {
795            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
796            return packages.get(packageName);
797        }
798
799        public void put(int userId, String packageName, ArrayList<String> components) {
800            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
801            packages.put(packageName, components);
802        }
803
804        public void remove(int userId, String packageName) {
805            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
806            if (packages != null) {
807                packages.remove(packageName);
808            }
809        }
810
811        public void remove(int userId) {
812            mUidMap.remove(userId);
813        }
814
815        public int userIdCount() {
816            return mUidMap.size();
817        }
818
819        public int userIdAt(int n) {
820            return mUidMap.keyAt(n);
821        }
822
823        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
824            return mUidMap.get(userId);
825        }
826
827        public int size() {
828            // total number of pending broadcast entries across all userIds
829            int num = 0;
830            for (int i = 0; i< mUidMap.size(); i++) {
831                num += mUidMap.valueAt(i).size();
832            }
833            return num;
834        }
835
836        public void clear() {
837            mUidMap.clear();
838        }
839
840        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
841            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
842            if (map == null) {
843                map = new ArrayMap<String, ArrayList<String>>();
844                mUidMap.put(userId, map);
845            }
846            return map;
847        }
848    }
849    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
850
851    // Service Connection to remote media container service to copy
852    // package uri's from external media onto secure containers
853    // or internal storage.
854    private IMediaContainerService mContainerService = null;
855
856    static final int SEND_PENDING_BROADCAST = 1;
857    static final int MCS_BOUND = 3;
858    static final int END_COPY = 4;
859    static final int INIT_COPY = 5;
860    static final int MCS_UNBIND = 6;
861    static final int START_CLEANING_PACKAGE = 7;
862    static final int FIND_INSTALL_LOC = 8;
863    static final int POST_INSTALL = 9;
864    static final int MCS_RECONNECT = 10;
865    static final int MCS_GIVE_UP = 11;
866    static final int UPDATED_MEDIA_STATUS = 12;
867    static final int WRITE_SETTINGS = 13;
868    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
869    static final int PACKAGE_VERIFIED = 15;
870    static final int CHECK_PENDING_VERIFICATION = 16;
871    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
872    static final int INTENT_FILTER_VERIFIED = 18;
873
874    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
875
876    // Delay time in millisecs
877    static final int BROADCAST_DELAY = 10 * 1000;
878
879    static UserManagerService sUserManager;
880
881    // Stores a list of users whose package restrictions file needs to be updated
882    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
883
884    final private DefaultContainerConnection mDefContainerConn =
885            new DefaultContainerConnection();
886    class DefaultContainerConnection implements ServiceConnection {
887        public void onServiceConnected(ComponentName name, IBinder service) {
888            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
889            IMediaContainerService imcs =
890                IMediaContainerService.Stub.asInterface(service);
891            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
892        }
893
894        public void onServiceDisconnected(ComponentName name) {
895            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
896        }
897    }
898
899    // Recordkeeping of restore-after-install operations that are currently in flight
900    // between the Package Manager and the Backup Manager
901    class PostInstallData {
902        public InstallArgs args;
903        public PackageInstalledInfo res;
904
905        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
906            args = _a;
907            res = _r;
908        }
909    }
910
911    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
912    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
913
914    // XML tags for backup/restore of various bits of state
915    private static final String TAG_PREFERRED_BACKUP = "pa";
916    private static final String TAG_DEFAULT_APPS = "da";
917    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
918
919    private final String mRequiredVerifierPackage;
920
921    private final PackageUsage mPackageUsage = new PackageUsage();
922
923    private class PackageUsage {
924        private static final int WRITE_INTERVAL
925            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
926
927        private final Object mFileLock = new Object();
928        private final AtomicLong mLastWritten = new AtomicLong(0);
929        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
930
931        private boolean mIsHistoricalPackageUsageAvailable = true;
932
933        boolean isHistoricalPackageUsageAvailable() {
934            return mIsHistoricalPackageUsageAvailable;
935        }
936
937        void write(boolean force) {
938            if (force) {
939                writeInternal();
940                return;
941            }
942            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
943                && !DEBUG_DEXOPT) {
944                return;
945            }
946            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
947                new Thread("PackageUsage_DiskWriter") {
948                    @Override
949                    public void run() {
950                        try {
951                            writeInternal();
952                        } finally {
953                            mBackgroundWriteRunning.set(false);
954                        }
955                    }
956                }.start();
957            }
958        }
959
960        private void writeInternal() {
961            synchronized (mPackages) {
962                synchronized (mFileLock) {
963                    AtomicFile file = getFile();
964                    FileOutputStream f = null;
965                    try {
966                        f = file.startWrite();
967                        BufferedOutputStream out = new BufferedOutputStream(f);
968                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
969                        StringBuilder sb = new StringBuilder();
970                        for (PackageParser.Package pkg : mPackages.values()) {
971                            if (pkg.mLastPackageUsageTimeInMills == 0) {
972                                continue;
973                            }
974                            sb.setLength(0);
975                            sb.append(pkg.packageName);
976                            sb.append(' ');
977                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
978                            sb.append('\n');
979                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
980                        }
981                        out.flush();
982                        file.finishWrite(f);
983                    } catch (IOException e) {
984                        if (f != null) {
985                            file.failWrite(f);
986                        }
987                        Log.e(TAG, "Failed to write package usage times", e);
988                    }
989                }
990            }
991            mLastWritten.set(SystemClock.elapsedRealtime());
992        }
993
994        void readLP() {
995            synchronized (mFileLock) {
996                AtomicFile file = getFile();
997                BufferedInputStream in = null;
998                try {
999                    in = new BufferedInputStream(file.openRead());
1000                    StringBuffer sb = new StringBuffer();
1001                    while (true) {
1002                        String packageName = readToken(in, sb, ' ');
1003                        if (packageName == null) {
1004                            break;
1005                        }
1006                        String timeInMillisString = readToken(in, sb, '\n');
1007                        if (timeInMillisString == null) {
1008                            throw new IOException("Failed to find last usage time for package "
1009                                                  + packageName);
1010                        }
1011                        PackageParser.Package pkg = mPackages.get(packageName);
1012                        if (pkg == null) {
1013                            continue;
1014                        }
1015                        long timeInMillis;
1016                        try {
1017                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1018                        } catch (NumberFormatException e) {
1019                            throw new IOException("Failed to parse " + timeInMillisString
1020                                                  + " as a long.", e);
1021                        }
1022                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1023                    }
1024                } catch (FileNotFoundException expected) {
1025                    mIsHistoricalPackageUsageAvailable = false;
1026                } catch (IOException e) {
1027                    Log.w(TAG, "Failed to read package usage times", e);
1028                } finally {
1029                    IoUtils.closeQuietly(in);
1030                }
1031            }
1032            mLastWritten.set(SystemClock.elapsedRealtime());
1033        }
1034
1035        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1036                throws IOException {
1037            sb.setLength(0);
1038            while (true) {
1039                int ch = in.read();
1040                if (ch == -1) {
1041                    if (sb.length() == 0) {
1042                        return null;
1043                    }
1044                    throw new IOException("Unexpected EOF");
1045                }
1046                if (ch == endOfToken) {
1047                    return sb.toString();
1048                }
1049                sb.append((char)ch);
1050            }
1051        }
1052
1053        private AtomicFile getFile() {
1054            File dataDir = Environment.getDataDirectory();
1055            File systemDir = new File(dataDir, "system");
1056            File fname = new File(systemDir, "package-usage.list");
1057            return new AtomicFile(fname);
1058        }
1059    }
1060
1061    class PackageHandler extends Handler {
1062        private boolean mBound = false;
1063        final ArrayList<HandlerParams> mPendingInstalls =
1064            new ArrayList<HandlerParams>();
1065
1066        private boolean connectToService() {
1067            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1068                    " DefaultContainerService");
1069            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1070            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1071            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1072                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1073                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1074                mBound = true;
1075                return true;
1076            }
1077            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1078            return false;
1079        }
1080
1081        private void disconnectService() {
1082            mContainerService = null;
1083            mBound = false;
1084            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1085            mContext.unbindService(mDefContainerConn);
1086            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1087        }
1088
1089        PackageHandler(Looper looper) {
1090            super(looper);
1091        }
1092
1093        public void handleMessage(Message msg) {
1094            try {
1095                doHandleMessage(msg);
1096            } finally {
1097                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1098            }
1099        }
1100
1101        void doHandleMessage(Message msg) {
1102            switch (msg.what) {
1103                case INIT_COPY: {
1104                    HandlerParams params = (HandlerParams) msg.obj;
1105                    int idx = mPendingInstalls.size();
1106                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1107                    // If a bind was already initiated we dont really
1108                    // need to do anything. The pending install
1109                    // will be processed later on.
1110                    if (!mBound) {
1111                        // If this is the only one pending we might
1112                        // have to bind to the service again.
1113                        if (!connectToService()) {
1114                            Slog.e(TAG, "Failed to bind to media container service");
1115                            params.serviceError();
1116                            return;
1117                        } else {
1118                            // Once we bind to the service, the first
1119                            // pending request will be processed.
1120                            mPendingInstalls.add(idx, params);
1121                        }
1122                    } else {
1123                        mPendingInstalls.add(idx, params);
1124                        // Already bound to the service. Just make
1125                        // sure we trigger off processing the first request.
1126                        if (idx == 0) {
1127                            mHandler.sendEmptyMessage(MCS_BOUND);
1128                        }
1129                    }
1130                    break;
1131                }
1132                case MCS_BOUND: {
1133                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1134                    if (msg.obj != null) {
1135                        mContainerService = (IMediaContainerService) msg.obj;
1136                    }
1137                    if (mContainerService == null) {
1138                        if (!mBound) {
1139                            // Something seriously wrong since we are not bound and we are not
1140                            // waiting for connection. Bail out.
1141                            Slog.e(TAG, "Cannot bind to media container service");
1142                            for (HandlerParams params : mPendingInstalls) {
1143                                // Indicate service bind error
1144                                params.serviceError();
1145                            }
1146                            mPendingInstalls.clear();
1147                        } else {
1148                            Slog.w(TAG, "Waiting to connect to media container service");
1149                        }
1150                    } else if (mPendingInstalls.size() > 0) {
1151                        HandlerParams params = mPendingInstalls.get(0);
1152                        if (params != null) {
1153                            if (params.startCopy()) {
1154                                // We are done...  look for more work or to
1155                                // go idle.
1156                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1157                                        "Checking for more work or unbind...");
1158                                // Delete pending install
1159                                if (mPendingInstalls.size() > 0) {
1160                                    mPendingInstalls.remove(0);
1161                                }
1162                                if (mPendingInstalls.size() == 0) {
1163                                    if (mBound) {
1164                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1165                                                "Posting delayed MCS_UNBIND");
1166                                        removeMessages(MCS_UNBIND);
1167                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1168                                        // Unbind after a little delay, to avoid
1169                                        // continual thrashing.
1170                                        sendMessageDelayed(ubmsg, 10000);
1171                                    }
1172                                } else {
1173                                    // There are more pending requests in queue.
1174                                    // Just post MCS_BOUND message to trigger processing
1175                                    // of next pending install.
1176                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1177                                            "Posting MCS_BOUND for next work");
1178                                    mHandler.sendEmptyMessage(MCS_BOUND);
1179                                }
1180                            }
1181                        }
1182                    } else {
1183                        // Should never happen ideally.
1184                        Slog.w(TAG, "Empty queue");
1185                    }
1186                    break;
1187                }
1188                case MCS_RECONNECT: {
1189                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1190                    if (mPendingInstalls.size() > 0) {
1191                        if (mBound) {
1192                            disconnectService();
1193                        }
1194                        if (!connectToService()) {
1195                            Slog.e(TAG, "Failed to bind to media container service");
1196                            for (HandlerParams params : mPendingInstalls) {
1197                                // Indicate service bind error
1198                                params.serviceError();
1199                            }
1200                            mPendingInstalls.clear();
1201                        }
1202                    }
1203                    break;
1204                }
1205                case MCS_UNBIND: {
1206                    // If there is no actual work left, then time to unbind.
1207                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1208
1209                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1210                        if (mBound) {
1211                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1212
1213                            disconnectService();
1214                        }
1215                    } else if (mPendingInstalls.size() > 0) {
1216                        // There are more pending requests in queue.
1217                        // Just post MCS_BOUND message to trigger processing
1218                        // of next pending install.
1219                        mHandler.sendEmptyMessage(MCS_BOUND);
1220                    }
1221
1222                    break;
1223                }
1224                case MCS_GIVE_UP: {
1225                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1226                    mPendingInstalls.remove(0);
1227                    break;
1228                }
1229                case SEND_PENDING_BROADCAST: {
1230                    String packages[];
1231                    ArrayList<String> components[];
1232                    int size = 0;
1233                    int uids[];
1234                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1235                    synchronized (mPackages) {
1236                        if (mPendingBroadcasts == null) {
1237                            return;
1238                        }
1239                        size = mPendingBroadcasts.size();
1240                        if (size <= 0) {
1241                            // Nothing to be done. Just return
1242                            return;
1243                        }
1244                        packages = new String[size];
1245                        components = new ArrayList[size];
1246                        uids = new int[size];
1247                        int i = 0;  // filling out the above arrays
1248
1249                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1250                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1251                            Iterator<Map.Entry<String, ArrayList<String>>> it
1252                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1253                                            .entrySet().iterator();
1254                            while (it.hasNext() && i < size) {
1255                                Map.Entry<String, ArrayList<String>> ent = it.next();
1256                                packages[i] = ent.getKey();
1257                                components[i] = ent.getValue();
1258                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1259                                uids[i] = (ps != null)
1260                                        ? UserHandle.getUid(packageUserId, ps.appId)
1261                                        : -1;
1262                                i++;
1263                            }
1264                        }
1265                        size = i;
1266                        mPendingBroadcasts.clear();
1267                    }
1268                    // Send broadcasts
1269                    for (int i = 0; i < size; i++) {
1270                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1271                    }
1272                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1273                    break;
1274                }
1275                case START_CLEANING_PACKAGE: {
1276                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1277                    final String packageName = (String)msg.obj;
1278                    final int userId = msg.arg1;
1279                    final boolean andCode = msg.arg2 != 0;
1280                    synchronized (mPackages) {
1281                        if (userId == UserHandle.USER_ALL) {
1282                            int[] users = sUserManager.getUserIds();
1283                            for (int user : users) {
1284                                mSettings.addPackageToCleanLPw(
1285                                        new PackageCleanItem(user, packageName, andCode));
1286                            }
1287                        } else {
1288                            mSettings.addPackageToCleanLPw(
1289                                    new PackageCleanItem(userId, packageName, andCode));
1290                        }
1291                    }
1292                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1293                    startCleaningPackages();
1294                } break;
1295                case POST_INSTALL: {
1296                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1297                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1298                    mRunningInstalls.delete(msg.arg1);
1299                    boolean deleteOld = false;
1300
1301                    if (data != null) {
1302                        InstallArgs args = data.args;
1303                        PackageInstalledInfo res = data.res;
1304
1305                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1306                            res.removedInfo.sendBroadcast(false, true, false);
1307                            Bundle extras = new Bundle(1);
1308                            extras.putInt(Intent.EXTRA_UID, res.uid);
1309
1310                            // Now that we successfully installed the package, grant runtime
1311                            // permissions if requested before broadcasting the install.
1312                            if ((args.installFlags
1313                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1314                                grantRequestedRuntimePermissions(res.pkg,
1315                                        args.user.getIdentifier());
1316                            }
1317
1318                            // Determine the set of users who are adding this
1319                            // package for the first time vs. those who are seeing
1320                            // an update.
1321                            int[] firstUsers;
1322                            int[] updateUsers = new int[0];
1323                            if (res.origUsers == null || res.origUsers.length == 0) {
1324                                firstUsers = res.newUsers;
1325                            } else {
1326                                firstUsers = new int[0];
1327                                for (int i=0; i<res.newUsers.length; i++) {
1328                                    int user = res.newUsers[i];
1329                                    boolean isNew = true;
1330                                    for (int j=0; j<res.origUsers.length; j++) {
1331                                        if (res.origUsers[j] == user) {
1332                                            isNew = false;
1333                                            break;
1334                                        }
1335                                    }
1336                                    if (isNew) {
1337                                        int[] newFirst = new int[firstUsers.length+1];
1338                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1339                                                firstUsers.length);
1340                                        newFirst[firstUsers.length] = user;
1341                                        firstUsers = newFirst;
1342                                    } else {
1343                                        int[] newUpdate = new int[updateUsers.length+1];
1344                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1345                                                updateUsers.length);
1346                                        newUpdate[updateUsers.length] = user;
1347                                        updateUsers = newUpdate;
1348                                    }
1349                                }
1350                            }
1351                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1352                                    res.pkg.applicationInfo.packageName,
1353                                    extras, null, null, firstUsers);
1354                            final boolean update = res.removedInfo.removedPackage != null;
1355                            if (update) {
1356                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1357                            }
1358                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1359                                    res.pkg.applicationInfo.packageName,
1360                                    extras, null, null, updateUsers);
1361                            if (update) {
1362                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1363                                        res.pkg.applicationInfo.packageName,
1364                                        extras, null, null, updateUsers);
1365                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1366                                        null, null,
1367                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1368
1369                                // treat asec-hosted packages like removable media on upgrade
1370                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1371                                    if (DEBUG_INSTALL) {
1372                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1373                                                + " is ASEC-hosted -> AVAILABLE");
1374                                    }
1375                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1376                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1377                                    pkgList.add(res.pkg.applicationInfo.packageName);
1378                                    sendResourcesChangedBroadcast(true, true,
1379                                            pkgList,uidArray, null);
1380                                }
1381                            }
1382                            if (res.removedInfo.args != null) {
1383                                // Remove the replaced package's older resources safely now
1384                                deleteOld = true;
1385                            }
1386
1387                            // Log current value of "unknown sources" setting
1388                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1389                                getUnknownSourcesSettings());
1390                        }
1391                        // Force a gc to clear up things
1392                        Runtime.getRuntime().gc();
1393                        // We delete after a gc for applications  on sdcard.
1394                        if (deleteOld) {
1395                            synchronized (mInstallLock) {
1396                                res.removedInfo.args.doPostDeleteLI(true);
1397                            }
1398                        }
1399                        if (args.observer != null) {
1400                            try {
1401                                Bundle extras = extrasForInstallResult(res);
1402                                args.observer.onPackageInstalled(res.name, res.returnCode,
1403                                        res.returnMsg, extras);
1404                            } catch (RemoteException e) {
1405                                Slog.i(TAG, "Observer no longer exists.");
1406                            }
1407                        }
1408                    } else {
1409                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1410                    }
1411                } break;
1412                case UPDATED_MEDIA_STATUS: {
1413                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1414                    boolean reportStatus = msg.arg1 == 1;
1415                    boolean doGc = msg.arg2 == 1;
1416                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1417                    if (doGc) {
1418                        // Force a gc to clear up stale containers.
1419                        Runtime.getRuntime().gc();
1420                    }
1421                    if (msg.obj != null) {
1422                        @SuppressWarnings("unchecked")
1423                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1424                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1425                        // Unload containers
1426                        unloadAllContainers(args);
1427                    }
1428                    if (reportStatus) {
1429                        try {
1430                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1431                            PackageHelper.getMountService().finishMediaUpdate();
1432                        } catch (RemoteException e) {
1433                            Log.e(TAG, "MountService not running?");
1434                        }
1435                    }
1436                } break;
1437                case WRITE_SETTINGS: {
1438                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1439                    synchronized (mPackages) {
1440                        removeMessages(WRITE_SETTINGS);
1441                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1442                        mSettings.writeLPr();
1443                        mDirtyUsers.clear();
1444                    }
1445                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1446                } break;
1447                case WRITE_PACKAGE_RESTRICTIONS: {
1448                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1449                    synchronized (mPackages) {
1450                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1451                        for (int userId : mDirtyUsers) {
1452                            mSettings.writePackageRestrictionsLPr(userId);
1453                        }
1454                        mDirtyUsers.clear();
1455                    }
1456                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1457                } break;
1458                case CHECK_PENDING_VERIFICATION: {
1459                    final int verificationId = msg.arg1;
1460                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1461
1462                    if ((state != null) && !state.timeoutExtended()) {
1463                        final InstallArgs args = state.getInstallArgs();
1464                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1465
1466                        Slog.i(TAG, "Verification timed out for " + originUri);
1467                        mPendingVerification.remove(verificationId);
1468
1469                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1470
1471                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1472                            Slog.i(TAG, "Continuing with installation of " + originUri);
1473                            state.setVerifierResponse(Binder.getCallingUid(),
1474                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1475                            broadcastPackageVerified(verificationId, originUri,
1476                                    PackageManager.VERIFICATION_ALLOW,
1477                                    state.getInstallArgs().getUser());
1478                            try {
1479                                ret = args.copyApk(mContainerService, true);
1480                            } catch (RemoteException e) {
1481                                Slog.e(TAG, "Could not contact the ContainerService");
1482                            }
1483                        } else {
1484                            broadcastPackageVerified(verificationId, originUri,
1485                                    PackageManager.VERIFICATION_REJECT,
1486                                    state.getInstallArgs().getUser());
1487                        }
1488
1489                        processPendingInstall(args, ret);
1490                        mHandler.sendEmptyMessage(MCS_UNBIND);
1491                    }
1492                    break;
1493                }
1494                case PACKAGE_VERIFIED: {
1495                    final int verificationId = msg.arg1;
1496
1497                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1498                    if (state == null) {
1499                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1500                        break;
1501                    }
1502
1503                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1504
1505                    state.setVerifierResponse(response.callerUid, response.code);
1506
1507                    if (state.isVerificationComplete()) {
1508                        mPendingVerification.remove(verificationId);
1509
1510                        final InstallArgs args = state.getInstallArgs();
1511                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1512
1513                        int ret;
1514                        if (state.isInstallAllowed()) {
1515                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1516                            broadcastPackageVerified(verificationId, originUri,
1517                                    response.code, state.getInstallArgs().getUser());
1518                            try {
1519                                ret = args.copyApk(mContainerService, true);
1520                            } catch (RemoteException e) {
1521                                Slog.e(TAG, "Could not contact the ContainerService");
1522                            }
1523                        } else {
1524                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1525                        }
1526
1527                        processPendingInstall(args, ret);
1528
1529                        mHandler.sendEmptyMessage(MCS_UNBIND);
1530                    }
1531
1532                    break;
1533                }
1534                case START_INTENT_FILTER_VERIFICATIONS: {
1535                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1536                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1537                            params.replacing, params.pkg);
1538                    break;
1539                }
1540                case INTENT_FILTER_VERIFIED: {
1541                    final int verificationId = msg.arg1;
1542
1543                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1544                            verificationId);
1545                    if (state == null) {
1546                        Slog.w(TAG, "Invalid IntentFilter verification token "
1547                                + verificationId + " received");
1548                        break;
1549                    }
1550
1551                    final int userId = state.getUserId();
1552
1553                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1554                            "Processing IntentFilter verification with token:"
1555                            + verificationId + " and userId:" + userId);
1556
1557                    final IntentFilterVerificationResponse response =
1558                            (IntentFilterVerificationResponse) msg.obj;
1559
1560                    state.setVerifierResponse(response.callerUid, response.code);
1561
1562                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1563                            "IntentFilter verification with token:" + verificationId
1564                            + " and userId:" + userId
1565                            + " is settings verifier response with response code:"
1566                            + response.code);
1567
1568                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1569                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1570                                + response.getFailedDomainsString());
1571                    }
1572
1573                    if (state.isVerificationComplete()) {
1574                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1575                    } else {
1576                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1577                                "IntentFilter verification with token:" + verificationId
1578                                + " was not said to be complete");
1579                    }
1580
1581                    break;
1582                }
1583            }
1584        }
1585    }
1586
1587    private StorageEventListener mStorageListener = new StorageEventListener() {
1588        @Override
1589        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1590            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1591                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1592                    // TODO: ensure that private directories exist for all active users
1593                    // TODO: remove user data whose serial number doesn't match
1594                    loadPrivatePackages(vol);
1595                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1596                    unloadPrivatePackages(vol);
1597                }
1598            }
1599
1600            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1601                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1602                    updateExternalMediaStatus(true, false);
1603                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1604                    updateExternalMediaStatus(false, false);
1605                }
1606            }
1607        }
1608
1609        @Override
1610        public void onVolumeForgotten(String fsUuid) {
1611            // TODO: remove all packages hosted on this uuid
1612        }
1613    };
1614
1615    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1616        if (userId >= UserHandle.USER_OWNER) {
1617            grantRequestedRuntimePermissionsForUser(pkg, userId);
1618        } else if (userId == UserHandle.USER_ALL) {
1619            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1620                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1621            }
1622        }
1623
1624        // We could have touched GID membership, so flush out packages.list
1625        synchronized (mPackages) {
1626            mSettings.writePackageListLPr();
1627        }
1628    }
1629
1630    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1631        SettingBase sb = (SettingBase) pkg.mExtras;
1632        if (sb == null) {
1633            return;
1634        }
1635
1636        PermissionsState permissionsState = sb.getPermissionsState();
1637
1638        for (String permission : pkg.requestedPermissions) {
1639            BasePermission bp = mSettings.mPermissions.get(permission);
1640            if (bp != null && bp.isRuntime()) {
1641                permissionsState.grantRuntimePermission(bp, userId);
1642            }
1643        }
1644    }
1645
1646    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1647        Bundle extras = null;
1648        switch (res.returnCode) {
1649            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1650                extras = new Bundle();
1651                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1652                        res.origPermission);
1653                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1654                        res.origPackage);
1655                break;
1656            }
1657            case PackageManager.INSTALL_SUCCEEDED: {
1658                extras = new Bundle();
1659                extras.putBoolean(Intent.EXTRA_REPLACING,
1660                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1661                break;
1662            }
1663        }
1664        return extras;
1665    }
1666
1667    void scheduleWriteSettingsLocked() {
1668        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1669            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1670        }
1671    }
1672
1673    void scheduleWritePackageRestrictionsLocked(int userId) {
1674        if (!sUserManager.exists(userId)) return;
1675        mDirtyUsers.add(userId);
1676        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1677            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1678        }
1679    }
1680
1681    public static PackageManagerService main(Context context, Installer installer,
1682            boolean factoryTest, boolean onlyCore) {
1683        PackageManagerService m = new PackageManagerService(context, installer,
1684                factoryTest, onlyCore);
1685        ServiceManager.addService("package", m);
1686        return m;
1687    }
1688
1689    static String[] splitString(String str, char sep) {
1690        int count = 1;
1691        int i = 0;
1692        while ((i=str.indexOf(sep, i)) >= 0) {
1693            count++;
1694            i++;
1695        }
1696
1697        String[] res = new String[count];
1698        i=0;
1699        count = 0;
1700        int lastI=0;
1701        while ((i=str.indexOf(sep, i)) >= 0) {
1702            res[count] = str.substring(lastI, i);
1703            count++;
1704            i++;
1705            lastI = i;
1706        }
1707        res[count] = str.substring(lastI, str.length());
1708        return res;
1709    }
1710
1711    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1712        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1713                Context.DISPLAY_SERVICE);
1714        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1715    }
1716
1717    public PackageManagerService(Context context, Installer installer,
1718            boolean factoryTest, boolean onlyCore) {
1719        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1720                SystemClock.uptimeMillis());
1721
1722        if (mSdkVersion <= 0) {
1723            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1724        }
1725
1726        mContext = context;
1727        mFactoryTest = factoryTest;
1728        mOnlyCore = onlyCore;
1729        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1730        mMetrics = new DisplayMetrics();
1731        mSettings = new Settings(mPackages);
1732        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1733                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1734        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1735                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1736        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1737                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1738        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1739                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1740        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1741                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1742        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1743                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1744
1745        // TODO: add a property to control this?
1746        long dexOptLRUThresholdInMinutes;
1747        if (mLazyDexOpt) {
1748            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1749        } else {
1750            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1751        }
1752        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1753
1754        String separateProcesses = SystemProperties.get("debug.separate_processes");
1755        if (separateProcesses != null && separateProcesses.length() > 0) {
1756            if ("*".equals(separateProcesses)) {
1757                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1758                mSeparateProcesses = null;
1759                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1760            } else {
1761                mDefParseFlags = 0;
1762                mSeparateProcesses = separateProcesses.split(",");
1763                Slog.w(TAG, "Running with debug.separate_processes: "
1764                        + separateProcesses);
1765            }
1766        } else {
1767            mDefParseFlags = 0;
1768            mSeparateProcesses = null;
1769        }
1770
1771        mInstaller = installer;
1772        mPackageDexOptimizer = new PackageDexOptimizer(this);
1773        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1774
1775        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1776                FgThread.get().getLooper());
1777
1778        getDefaultDisplayMetrics(context, mMetrics);
1779
1780        SystemConfig systemConfig = SystemConfig.getInstance();
1781        mGlobalGids = systemConfig.getGlobalGids();
1782        mSystemPermissions = systemConfig.getSystemPermissions();
1783        mAvailableFeatures = systemConfig.getAvailableFeatures();
1784
1785        synchronized (mInstallLock) {
1786        // writer
1787        synchronized (mPackages) {
1788            mHandlerThread = new ServiceThread(TAG,
1789                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1790            mHandlerThread.start();
1791            mHandler = new PackageHandler(mHandlerThread.getLooper());
1792            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1793
1794            File dataDir = Environment.getDataDirectory();
1795            mAppDataDir = new File(dataDir, "data");
1796            mAppInstallDir = new File(dataDir, "app");
1797            mAppLib32InstallDir = new File(dataDir, "app-lib");
1798            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1799            mUserAppDataDir = new File(dataDir, "user");
1800            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1801
1802            sUserManager = new UserManagerService(context, this,
1803                    mInstallLock, mPackages);
1804
1805            // Propagate permission configuration in to package manager.
1806            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1807                    = systemConfig.getPermissions();
1808            for (int i=0; i<permConfig.size(); i++) {
1809                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1810                BasePermission bp = mSettings.mPermissions.get(perm.name);
1811                if (bp == null) {
1812                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1813                    mSettings.mPermissions.put(perm.name, bp);
1814                }
1815                if (perm.gids != null) {
1816                    bp.setGids(perm.gids, perm.perUser);
1817                }
1818            }
1819
1820            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1821            for (int i=0; i<libConfig.size(); i++) {
1822                mSharedLibraries.put(libConfig.keyAt(i),
1823                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1824            }
1825
1826            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1827
1828            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1829                    mSdkVersion, mOnlyCore);
1830
1831            String customResolverActivity = Resources.getSystem().getString(
1832                    R.string.config_customResolverActivity);
1833            if (TextUtils.isEmpty(customResolverActivity)) {
1834                customResolverActivity = null;
1835            } else {
1836                mCustomResolverComponentName = ComponentName.unflattenFromString(
1837                        customResolverActivity);
1838            }
1839
1840            long startTime = SystemClock.uptimeMillis();
1841
1842            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1843                    startTime);
1844
1845            // Set flag to monitor and not change apk file paths when
1846            // scanning install directories.
1847            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1848
1849            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1850
1851            /**
1852             * Add everything in the in the boot class path to the
1853             * list of process files because dexopt will have been run
1854             * if necessary during zygote startup.
1855             */
1856            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1857            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1858
1859            if (bootClassPath != null) {
1860                String[] bootClassPathElements = splitString(bootClassPath, ':');
1861                for (String element : bootClassPathElements) {
1862                    alreadyDexOpted.add(element);
1863                }
1864            } else {
1865                Slog.w(TAG, "No BOOTCLASSPATH found!");
1866            }
1867
1868            if (systemServerClassPath != null) {
1869                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1870                for (String element : systemServerClassPathElements) {
1871                    alreadyDexOpted.add(element);
1872                }
1873            } else {
1874                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1875            }
1876
1877            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1878            final String[] dexCodeInstructionSets =
1879                    getDexCodeInstructionSets(
1880                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1881
1882            /**
1883             * Ensure all external libraries have had dexopt run on them.
1884             */
1885            if (mSharedLibraries.size() > 0) {
1886                // NOTE: For now, we're compiling these system "shared libraries"
1887                // (and framework jars) into all available architectures. It's possible
1888                // to compile them only when we come across an app that uses them (there's
1889                // already logic for that in scanPackageLI) but that adds some complexity.
1890                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1891                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1892                        final String lib = libEntry.path;
1893                        if (lib == null) {
1894                            continue;
1895                        }
1896
1897                        try {
1898                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1899                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1900                                alreadyDexOpted.add(lib);
1901                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1902                            }
1903                        } catch (FileNotFoundException e) {
1904                            Slog.w(TAG, "Library not found: " + lib);
1905                        } catch (IOException e) {
1906                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1907                                    + e.getMessage());
1908                        }
1909                    }
1910                }
1911            }
1912
1913            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1914
1915            // Gross hack for now: we know this file doesn't contain any
1916            // code, so don't dexopt it to avoid the resulting log spew.
1917            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1918
1919            // Gross hack for now: we know this file is only part of
1920            // the boot class path for art, so don't dexopt it to
1921            // avoid the resulting log spew.
1922            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1923
1924            /**
1925             * There are a number of commands implemented in Java, which
1926             * we currently need to do the dexopt on so that they can be
1927             * run from a non-root shell.
1928             */
1929            String[] frameworkFiles = frameworkDir.list();
1930            if (frameworkFiles != null) {
1931                // TODO: We could compile these only for the most preferred ABI. We should
1932                // first double check that the dex files for these commands are not referenced
1933                // by other system apps.
1934                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1935                    for (int i=0; i<frameworkFiles.length; i++) {
1936                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1937                        String path = libPath.getPath();
1938                        // Skip the file if we already did it.
1939                        if (alreadyDexOpted.contains(path)) {
1940                            continue;
1941                        }
1942                        // Skip the file if it is not a type we want to dexopt.
1943                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1944                            continue;
1945                        }
1946                        try {
1947                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1948                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1949                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1950                            }
1951                        } catch (FileNotFoundException e) {
1952                            Slog.w(TAG, "Jar not found: " + path);
1953                        } catch (IOException e) {
1954                            Slog.w(TAG, "Exception reading jar: " + path, e);
1955                        }
1956                    }
1957                }
1958            }
1959
1960            // Collect vendor overlay packages.
1961            // (Do this before scanning any apps.)
1962            // For security and version matching reason, only consider
1963            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1964            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1965            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1966                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1967
1968            // Find base frameworks (resource packages without code).
1969            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1970                    | PackageParser.PARSE_IS_SYSTEM_DIR
1971                    | PackageParser.PARSE_IS_PRIVILEGED,
1972                    scanFlags | SCAN_NO_DEX, 0);
1973
1974            // Collected privileged system packages.
1975            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1976            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1977                    | PackageParser.PARSE_IS_SYSTEM_DIR
1978                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1979
1980            // Collect ordinary system packages.
1981            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1982            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1983                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1984
1985            // Collect all vendor packages.
1986            File vendorAppDir = new File("/vendor/app");
1987            try {
1988                vendorAppDir = vendorAppDir.getCanonicalFile();
1989            } catch (IOException e) {
1990                // failed to look up canonical path, continue with original one
1991            }
1992            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1993                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1994
1995            // Collect all OEM packages.
1996            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1997            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1998                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1999
2000            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2001            mInstaller.moveFiles();
2002
2003            // Prune any system packages that no longer exist.
2004            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2005            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
2006            if (!mOnlyCore) {
2007                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2008                while (psit.hasNext()) {
2009                    PackageSetting ps = psit.next();
2010
2011                    /*
2012                     * If this is not a system app, it can't be a
2013                     * disable system app.
2014                     */
2015                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2016                        continue;
2017                    }
2018
2019                    /*
2020                     * If the package is scanned, it's not erased.
2021                     */
2022                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2023                    if (scannedPkg != null) {
2024                        /*
2025                         * If the system app is both scanned and in the
2026                         * disabled packages list, then it must have been
2027                         * added via OTA. Remove it from the currently
2028                         * scanned package so the previously user-installed
2029                         * application can be scanned.
2030                         */
2031                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2032                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2033                                    + ps.name + "; removing system app.  Last known codePath="
2034                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2035                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2036                                    + scannedPkg.mVersionCode);
2037                            removePackageLI(ps, true);
2038                            expectingBetter.put(ps.name, ps.codePath);
2039                        }
2040
2041                        continue;
2042                    }
2043
2044                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2045                        psit.remove();
2046                        logCriticalInfo(Log.WARN, "System package " + ps.name
2047                                + " no longer exists; wiping its data");
2048                        removeDataDirsLI(null, ps.name);
2049                    } else {
2050                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2051                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2052                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2053                        }
2054                    }
2055                }
2056            }
2057
2058            //look for any incomplete package installations
2059            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2060            //clean up list
2061            for(int i = 0; i < deletePkgsList.size(); i++) {
2062                //clean up here
2063                cleanupInstallFailedPackage(deletePkgsList.get(i));
2064            }
2065            //delete tmp files
2066            deleteTempPackageFiles();
2067
2068            // Remove any shared userIDs that have no associated packages
2069            mSettings.pruneSharedUsersLPw();
2070
2071            if (!mOnlyCore) {
2072                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2073                        SystemClock.uptimeMillis());
2074                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2075
2076                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2077                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2078
2079                /**
2080                 * Remove disable package settings for any updated system
2081                 * apps that were removed via an OTA. If they're not a
2082                 * previously-updated app, remove them completely.
2083                 * Otherwise, just revoke their system-level permissions.
2084                 */
2085                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2086                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2087                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2088
2089                    String msg;
2090                    if (deletedPkg == null) {
2091                        msg = "Updated system package " + deletedAppName
2092                                + " no longer exists; wiping its data";
2093                        removeDataDirsLI(null, deletedAppName);
2094                    } else {
2095                        msg = "Updated system app + " + deletedAppName
2096                                + " no longer present; removing system privileges for "
2097                                + deletedAppName;
2098
2099                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2100
2101                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2102                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2103                    }
2104                    logCriticalInfo(Log.WARN, msg);
2105                }
2106
2107                /**
2108                 * Make sure all system apps that we expected to appear on
2109                 * the userdata partition actually showed up. If they never
2110                 * appeared, crawl back and revive the system version.
2111                 */
2112                for (int i = 0; i < expectingBetter.size(); i++) {
2113                    final String packageName = expectingBetter.keyAt(i);
2114                    if (!mPackages.containsKey(packageName)) {
2115                        final File scanFile = expectingBetter.valueAt(i);
2116
2117                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2118                                + " but never showed up; reverting to system");
2119
2120                        final int reparseFlags;
2121                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2122                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2123                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2124                                    | PackageParser.PARSE_IS_PRIVILEGED;
2125                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2126                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2127                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2128                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2129                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2130                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2131                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2132                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2133                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2134                        } else {
2135                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2136                            continue;
2137                        }
2138
2139                        mSettings.enableSystemPackageLPw(packageName);
2140
2141                        try {
2142                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2143                        } catch (PackageManagerException e) {
2144                            Slog.e(TAG, "Failed to parse original system package: "
2145                                    + e.getMessage());
2146                        }
2147                    }
2148                }
2149            }
2150
2151            // Now that we know all of the shared libraries, update all clients to have
2152            // the correct library paths.
2153            updateAllSharedLibrariesLPw();
2154
2155            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2156                // NOTE: We ignore potential failures here during a system scan (like
2157                // the rest of the commands above) because there's precious little we
2158                // can do about it. A settings error is reported, though.
2159                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2160                        false /* force dexopt */, false /* defer dexopt */);
2161            }
2162
2163            // Now that we know all the packages we are keeping,
2164            // read and update their last usage times.
2165            mPackageUsage.readLP();
2166
2167            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2168                    SystemClock.uptimeMillis());
2169            Slog.i(TAG, "Time to scan packages: "
2170                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2171                    + " seconds");
2172
2173            // If the platform SDK has changed since the last time we booted,
2174            // we need to re-grant app permission to catch any new ones that
2175            // appear.  This is really a hack, and means that apps can in some
2176            // cases get permissions that the user didn't initially explicitly
2177            // allow...  it would be nice to have some better way to handle
2178            // this situation.
2179            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2180                    != mSdkVersion;
2181            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2182                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2183                    + "; regranting permissions for internal storage");
2184            mSettings.mInternalSdkPlatform = mSdkVersion;
2185
2186            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2187                    | (regrantPermissions
2188                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2189                            : 0));
2190
2191            // If this is the first boot, and it is a normal boot, then
2192            // we need to initialize the default preferred apps.
2193            if (!mRestoredSettings && !onlyCore) {
2194                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2195                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2196            }
2197
2198            // If this is first boot after an OTA, and a normal boot, then
2199            // we need to clear code cache directories.
2200            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2201            if (mIsUpgrade && !onlyCore) {
2202                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2203                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2204                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2205                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2206                }
2207                mSettings.mFingerprint = Build.FINGERPRINT;
2208            }
2209
2210            primeDomainVerificationsLPw();
2211            checkDefaultBrowser();
2212
2213            // All the changes are done during package scanning.
2214            mSettings.updateInternalDatabaseVersion();
2215
2216            // can downgrade to reader
2217            mSettings.writeLPr();
2218
2219            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2220                    SystemClock.uptimeMillis());
2221
2222            mRequiredVerifierPackage = getRequiredVerifierLPr();
2223
2224            mInstallerService = new PackageInstallerService(context, this);
2225
2226            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2227            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2228                    mIntentFilterVerifierComponent);
2229
2230        } // synchronized (mPackages)
2231        } // synchronized (mInstallLock)
2232
2233        // Now after opening every single application zip, make sure they
2234        // are all flushed.  Not really needed, but keeps things nice and
2235        // tidy.
2236        Runtime.getRuntime().gc();
2237
2238        // Expose private service for system components to use.
2239        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2240    }
2241
2242    @Override
2243    public boolean isFirstBoot() {
2244        return !mRestoredSettings;
2245    }
2246
2247    @Override
2248    public boolean isOnlyCoreApps() {
2249        return mOnlyCore;
2250    }
2251
2252    @Override
2253    public boolean isUpgrade() {
2254        return mIsUpgrade;
2255    }
2256
2257    private String getRequiredVerifierLPr() {
2258        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2259        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2260                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2261
2262        String requiredVerifier = null;
2263
2264        final int N = receivers.size();
2265        for (int i = 0; i < N; i++) {
2266            final ResolveInfo info = receivers.get(i);
2267
2268            if (info.activityInfo == null) {
2269                continue;
2270            }
2271
2272            final String packageName = info.activityInfo.packageName;
2273
2274            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2275                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2276                continue;
2277            }
2278
2279            if (requiredVerifier != null) {
2280                throw new RuntimeException("There can be only one required verifier");
2281            }
2282
2283            requiredVerifier = packageName;
2284        }
2285
2286        return requiredVerifier;
2287    }
2288
2289    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2290        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2291        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2292                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2293
2294        ComponentName verifierComponentName = null;
2295
2296        int priority = -1000;
2297        final int N = receivers.size();
2298        for (int i = 0; i < N; i++) {
2299            final ResolveInfo info = receivers.get(i);
2300
2301            if (info.activityInfo == null) {
2302                continue;
2303            }
2304
2305            final String packageName = info.activityInfo.packageName;
2306
2307            final PackageSetting ps = mSettings.mPackages.get(packageName);
2308            if (ps == null) {
2309                continue;
2310            }
2311
2312            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2313                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2314                continue;
2315            }
2316
2317            // Select the IntentFilterVerifier with the highest priority
2318            if (priority < info.priority) {
2319                priority = info.priority;
2320                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2321                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2322                        + verifierComponentName + " with priority: " + info.priority);
2323            }
2324        }
2325
2326        return verifierComponentName;
2327    }
2328
2329    private void primeDomainVerificationsLPw() {
2330        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2331        boolean updated = false;
2332        ArraySet<String> allHostsSet = new ArraySet<>();
2333        for (PackageParser.Package pkg : mPackages.values()) {
2334            final String packageName = pkg.packageName;
2335            if (!hasDomainURLs(pkg)) {
2336                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2337                            "package with no domain URLs: " + packageName);
2338                continue;
2339            }
2340            if (!pkg.isSystemApp()) {
2341                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2342                        "No priming domain verifications for a non system package : " +
2343                                packageName);
2344                continue;
2345            }
2346            for (PackageParser.Activity a : pkg.activities) {
2347                for (ActivityIntentInfo filter : a.intents) {
2348                    if (hasValidDomains(filter)) {
2349                        allHostsSet.addAll(filter.getHostsList());
2350                    }
2351                }
2352            }
2353            if (allHostsSet.size() == 0) {
2354                allHostsSet.add("*");
2355            }
2356            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2357            IntentFilterVerificationInfo ivi =
2358                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2359            if (ivi != null) {
2360                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2361                        "Priming domain verifications for package: " + packageName +
2362                        " with hosts:" + ivi.getDomainsString());
2363                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2364                updated = true;
2365            }
2366            else {
2367                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2368                        "No priming domain verifications for package: " + packageName);
2369            }
2370            allHostsSet.clear();
2371        }
2372        if (updated) {
2373            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2374                    "Will need to write primed domain verifications");
2375        }
2376        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2377    }
2378
2379    private void applyFactoryDefaultBrowserLPw(int userId) {
2380        // The default browser app's package name is stored in a string resource,
2381        // with a product-specific overlay used for vendor customization.
2382        String browserPkg = mContext.getResources().getString(
2383                com.android.internal.R.string.default_browser);
2384        if (browserPkg != null) {
2385            // non-empty string => required to be a known package
2386            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2387            if (ps == null) {
2388                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2389                browserPkg = null;
2390            } else {
2391                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2392            }
2393        }
2394
2395        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2396        // default.  If there's more than one, just leave everything alone.
2397        if (browserPkg == null) {
2398            calculateDefaultBrowserLPw(userId);
2399        }
2400    }
2401
2402    private void calculateDefaultBrowserLPw(int userId) {
2403        List<String> allBrowsers = resolveAllBrowserApps(userId);
2404        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2405        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2406    }
2407
2408    private List<String> resolveAllBrowserApps(int userId) {
2409        // Match all generic http: browser apps
2410        Intent intent = new Intent();
2411        intent.setAction(Intent.ACTION_VIEW);
2412        intent.addCategory(Intent.CATEGORY_BROWSABLE);
2413        intent.setData(Uri.parse("http:"));
2414
2415        // Resolve that intent and check that the handleAllWebDataURI boolean is set
2416        List<ResolveInfo> list = queryIntentActivities(intent, null, 0, userId);
2417
2418        final int count = list.size();
2419        List<String> result = new ArrayList<String>(count);
2420        for (int i=0; i<count; i++) {
2421            ResolveInfo info = list.get(i);
2422            if (info.activityInfo == null
2423                    || !info.handleAllWebDataURI
2424                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2425                    || result.contains(info.activityInfo.packageName)) {
2426                continue;
2427            }
2428            result.add(info.activityInfo.packageName);
2429        }
2430
2431        return result;
2432    }
2433
2434    private void checkDefaultBrowser() {
2435        final int myUserId = UserHandle.myUserId();
2436        final String packageName = getDefaultBrowserPackageName(myUserId);
2437        if (packageName != null) {
2438            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2439            if (info == null) {
2440                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2441                synchronized (mPackages) {
2442                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2443                }
2444            }
2445        }
2446    }
2447
2448    @Override
2449    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2450            throws RemoteException {
2451        try {
2452            return super.onTransact(code, data, reply, flags);
2453        } catch (RuntimeException e) {
2454            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2455                Slog.wtf(TAG, "Package Manager Crash", e);
2456            }
2457            throw e;
2458        }
2459    }
2460
2461    void cleanupInstallFailedPackage(PackageSetting ps) {
2462        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2463
2464        removeDataDirsLI(ps.volumeUuid, ps.name);
2465        if (ps.codePath != null) {
2466            if (ps.codePath.isDirectory()) {
2467                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2468            } else {
2469                ps.codePath.delete();
2470            }
2471        }
2472        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2473            if (ps.resourcePath.isDirectory()) {
2474                FileUtils.deleteContents(ps.resourcePath);
2475            }
2476            ps.resourcePath.delete();
2477        }
2478        mSettings.removePackageLPw(ps.name);
2479    }
2480
2481    static int[] appendInts(int[] cur, int[] add) {
2482        if (add == null) return cur;
2483        if (cur == null) return add;
2484        final int N = add.length;
2485        for (int i=0; i<N; i++) {
2486            cur = appendInt(cur, add[i]);
2487        }
2488        return cur;
2489    }
2490
2491    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2492        if (!sUserManager.exists(userId)) return null;
2493        final PackageSetting ps = (PackageSetting) p.mExtras;
2494        if (ps == null) {
2495            return null;
2496        }
2497
2498        final PermissionsState permissionsState = ps.getPermissionsState();
2499
2500        final int[] gids = permissionsState.computeGids(userId);
2501        final Set<String> permissions = permissionsState.getPermissions(userId);
2502        final PackageUserState state = ps.readUserState(userId);
2503
2504        return PackageParser.generatePackageInfo(p, gids, flags,
2505                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2506    }
2507
2508    @Override
2509    public boolean isPackageFrozen(String packageName) {
2510        synchronized (mPackages) {
2511            final PackageSetting ps = mSettings.mPackages.get(packageName);
2512            if (ps != null) {
2513                return ps.frozen;
2514            }
2515        }
2516        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2517        return true;
2518    }
2519
2520    @Override
2521    public boolean isPackageAvailable(String packageName, int userId) {
2522        if (!sUserManager.exists(userId)) return false;
2523        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2524        synchronized (mPackages) {
2525            PackageParser.Package p = mPackages.get(packageName);
2526            if (p != null) {
2527                final PackageSetting ps = (PackageSetting) p.mExtras;
2528                if (ps != null) {
2529                    final PackageUserState state = ps.readUserState(userId);
2530                    if (state != null) {
2531                        return PackageParser.isAvailable(state);
2532                    }
2533                }
2534            }
2535        }
2536        return false;
2537    }
2538
2539    @Override
2540    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2541        if (!sUserManager.exists(userId)) return null;
2542        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2543        // reader
2544        synchronized (mPackages) {
2545            PackageParser.Package p = mPackages.get(packageName);
2546            if (DEBUG_PACKAGE_INFO)
2547                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2548            if (p != null) {
2549                return generatePackageInfo(p, flags, userId);
2550            }
2551            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2552                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2553            }
2554        }
2555        return null;
2556    }
2557
2558    @Override
2559    public String[] currentToCanonicalPackageNames(String[] names) {
2560        String[] out = new String[names.length];
2561        // reader
2562        synchronized (mPackages) {
2563            for (int i=names.length-1; i>=0; i--) {
2564                PackageSetting ps = mSettings.mPackages.get(names[i]);
2565                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2566            }
2567        }
2568        return out;
2569    }
2570
2571    @Override
2572    public String[] canonicalToCurrentPackageNames(String[] names) {
2573        String[] out = new String[names.length];
2574        // reader
2575        synchronized (mPackages) {
2576            for (int i=names.length-1; i>=0; i--) {
2577                String cur = mSettings.mRenamedPackages.get(names[i]);
2578                out[i] = cur != null ? cur : names[i];
2579            }
2580        }
2581        return out;
2582    }
2583
2584    @Override
2585    public int getPackageUid(String packageName, int userId) {
2586        if (!sUserManager.exists(userId)) return -1;
2587        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2588
2589        // reader
2590        synchronized (mPackages) {
2591            PackageParser.Package p = mPackages.get(packageName);
2592            if(p != null) {
2593                return UserHandle.getUid(userId, p.applicationInfo.uid);
2594            }
2595            PackageSetting ps = mSettings.mPackages.get(packageName);
2596            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2597                return -1;
2598            }
2599            p = ps.pkg;
2600            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2601        }
2602    }
2603
2604    @Override
2605    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2606        if (!sUserManager.exists(userId)) {
2607            return null;
2608        }
2609
2610        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2611                "getPackageGids");
2612
2613        // reader
2614        synchronized (mPackages) {
2615            PackageParser.Package p = mPackages.get(packageName);
2616            if (DEBUG_PACKAGE_INFO) {
2617                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2618            }
2619            if (p != null) {
2620                PackageSetting ps = (PackageSetting) p.mExtras;
2621                return ps.getPermissionsState().computeGids(userId);
2622            }
2623        }
2624
2625        return null;
2626    }
2627
2628    @Override
2629    public int getMountExternalMode(int uid) {
2630        if (Process.isIsolated(uid)) {
2631            return Zygote.MOUNT_EXTERNAL_NONE;
2632        } else {
2633            if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2634                return Zygote.MOUNT_EXTERNAL_WRITE;
2635            } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2636                return Zygote.MOUNT_EXTERNAL_READ;
2637            } else {
2638                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2639            }
2640        }
2641    }
2642
2643    static PermissionInfo generatePermissionInfo(
2644            BasePermission bp, int flags) {
2645        if (bp.perm != null) {
2646            return PackageParser.generatePermissionInfo(bp.perm, flags);
2647        }
2648        PermissionInfo pi = new PermissionInfo();
2649        pi.name = bp.name;
2650        pi.packageName = bp.sourcePackage;
2651        pi.nonLocalizedLabel = bp.name;
2652        pi.protectionLevel = bp.protectionLevel;
2653        return pi;
2654    }
2655
2656    @Override
2657    public PermissionInfo getPermissionInfo(String name, int flags) {
2658        // reader
2659        synchronized (mPackages) {
2660            final BasePermission p = mSettings.mPermissions.get(name);
2661            if (p != null) {
2662                return generatePermissionInfo(p, flags);
2663            }
2664            return null;
2665        }
2666    }
2667
2668    @Override
2669    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2670        // reader
2671        synchronized (mPackages) {
2672            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2673            for (BasePermission p : mSettings.mPermissions.values()) {
2674                if (group == null) {
2675                    if (p.perm == null || p.perm.info.group == null) {
2676                        out.add(generatePermissionInfo(p, flags));
2677                    }
2678                } else {
2679                    if (p.perm != null && group.equals(p.perm.info.group)) {
2680                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2681                    }
2682                }
2683            }
2684
2685            if (out.size() > 0) {
2686                return out;
2687            }
2688            return mPermissionGroups.containsKey(group) ? out : null;
2689        }
2690    }
2691
2692    @Override
2693    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2694        // reader
2695        synchronized (mPackages) {
2696            return PackageParser.generatePermissionGroupInfo(
2697                    mPermissionGroups.get(name), flags);
2698        }
2699    }
2700
2701    @Override
2702    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2703        // reader
2704        synchronized (mPackages) {
2705            final int N = mPermissionGroups.size();
2706            ArrayList<PermissionGroupInfo> out
2707                    = new ArrayList<PermissionGroupInfo>(N);
2708            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2709                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2710            }
2711            return out;
2712        }
2713    }
2714
2715    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2716            int userId) {
2717        if (!sUserManager.exists(userId)) return null;
2718        PackageSetting ps = mSettings.mPackages.get(packageName);
2719        if (ps != null) {
2720            if (ps.pkg == null) {
2721                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2722                        flags, userId);
2723                if (pInfo != null) {
2724                    return pInfo.applicationInfo;
2725                }
2726                return null;
2727            }
2728            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2729                    ps.readUserState(userId), userId);
2730        }
2731        return null;
2732    }
2733
2734    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2735            int userId) {
2736        if (!sUserManager.exists(userId)) return null;
2737        PackageSetting ps = mSettings.mPackages.get(packageName);
2738        if (ps != null) {
2739            PackageParser.Package pkg = ps.pkg;
2740            if (pkg == null) {
2741                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2742                    return null;
2743                }
2744                // Only data remains, so we aren't worried about code paths
2745                pkg = new PackageParser.Package(packageName);
2746                pkg.applicationInfo.packageName = packageName;
2747                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2748                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2749                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2750                        packageName, userId).getAbsolutePath();
2751                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2752                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2753            }
2754            return generatePackageInfo(pkg, flags, userId);
2755        }
2756        return null;
2757    }
2758
2759    @Override
2760    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2761        if (!sUserManager.exists(userId)) return null;
2762        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2763        // writer
2764        synchronized (mPackages) {
2765            PackageParser.Package p = mPackages.get(packageName);
2766            if (DEBUG_PACKAGE_INFO) Log.v(
2767                    TAG, "getApplicationInfo " + packageName
2768                    + ": " + p);
2769            if (p != null) {
2770                PackageSetting ps = mSettings.mPackages.get(packageName);
2771                if (ps == null) return null;
2772                // Note: isEnabledLP() does not apply here - always return info
2773                return PackageParser.generateApplicationInfo(
2774                        p, flags, ps.readUserState(userId), userId);
2775            }
2776            if ("android".equals(packageName)||"system".equals(packageName)) {
2777                return mAndroidApplication;
2778            }
2779            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2780                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2781            }
2782        }
2783        return null;
2784    }
2785
2786    @Override
2787    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2788            final IPackageDataObserver observer) {
2789        mContext.enforceCallingOrSelfPermission(
2790                android.Manifest.permission.CLEAR_APP_CACHE, null);
2791        // Queue up an async operation since clearing cache may take a little while.
2792        mHandler.post(new Runnable() {
2793            public void run() {
2794                mHandler.removeCallbacks(this);
2795                int retCode = -1;
2796                synchronized (mInstallLock) {
2797                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2798                    if (retCode < 0) {
2799                        Slog.w(TAG, "Couldn't clear application caches");
2800                    }
2801                }
2802                if (observer != null) {
2803                    try {
2804                        observer.onRemoveCompleted(null, (retCode >= 0));
2805                    } catch (RemoteException e) {
2806                        Slog.w(TAG, "RemoveException when invoking call back");
2807                    }
2808                }
2809            }
2810        });
2811    }
2812
2813    @Override
2814    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2815            final IntentSender pi) {
2816        mContext.enforceCallingOrSelfPermission(
2817                android.Manifest.permission.CLEAR_APP_CACHE, null);
2818        // Queue up an async operation since clearing cache may take a little while.
2819        mHandler.post(new Runnable() {
2820            public void run() {
2821                mHandler.removeCallbacks(this);
2822                int retCode = -1;
2823                synchronized (mInstallLock) {
2824                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2825                    if (retCode < 0) {
2826                        Slog.w(TAG, "Couldn't clear application caches");
2827                    }
2828                }
2829                if(pi != null) {
2830                    try {
2831                        // Callback via pending intent
2832                        int code = (retCode >= 0) ? 1 : 0;
2833                        pi.sendIntent(null, code, null,
2834                                null, null);
2835                    } catch (SendIntentException e1) {
2836                        Slog.i(TAG, "Failed to send pending intent");
2837                    }
2838                }
2839            }
2840        });
2841    }
2842
2843    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2844        synchronized (mInstallLock) {
2845            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2846                throw new IOException("Failed to free enough space");
2847            }
2848        }
2849    }
2850
2851    @Override
2852    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2853        if (!sUserManager.exists(userId)) return null;
2854        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2855        synchronized (mPackages) {
2856            PackageParser.Activity a = mActivities.mActivities.get(component);
2857
2858            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2859            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2860                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2861                if (ps == null) return null;
2862                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2863                        userId);
2864            }
2865            if (mResolveComponentName.equals(component)) {
2866                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2867                        new PackageUserState(), userId);
2868            }
2869        }
2870        return null;
2871    }
2872
2873    @Override
2874    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2875            String resolvedType) {
2876        synchronized (mPackages) {
2877            PackageParser.Activity a = mActivities.mActivities.get(component);
2878            if (a == null) {
2879                return false;
2880            }
2881            for (int i=0; i<a.intents.size(); i++) {
2882                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2883                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2884                    return true;
2885                }
2886            }
2887            return false;
2888        }
2889    }
2890
2891    @Override
2892    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2893        if (!sUserManager.exists(userId)) return null;
2894        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2895        synchronized (mPackages) {
2896            PackageParser.Activity a = mReceivers.mActivities.get(component);
2897            if (DEBUG_PACKAGE_INFO) Log.v(
2898                TAG, "getReceiverInfo " + component + ": " + a);
2899            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2900                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2901                if (ps == null) return null;
2902                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2903                        userId);
2904            }
2905        }
2906        return null;
2907    }
2908
2909    @Override
2910    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2911        if (!sUserManager.exists(userId)) return null;
2912        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2913        synchronized (mPackages) {
2914            PackageParser.Service s = mServices.mServices.get(component);
2915            if (DEBUG_PACKAGE_INFO) Log.v(
2916                TAG, "getServiceInfo " + component + ": " + s);
2917            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2918                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2919                if (ps == null) return null;
2920                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2921                        userId);
2922            }
2923        }
2924        return null;
2925    }
2926
2927    @Override
2928    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2929        if (!sUserManager.exists(userId)) return null;
2930        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2931        synchronized (mPackages) {
2932            PackageParser.Provider p = mProviders.mProviders.get(component);
2933            if (DEBUG_PACKAGE_INFO) Log.v(
2934                TAG, "getProviderInfo " + component + ": " + p);
2935            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2936                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2937                if (ps == null) return null;
2938                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2939                        userId);
2940            }
2941        }
2942        return null;
2943    }
2944
2945    @Override
2946    public String[] getSystemSharedLibraryNames() {
2947        Set<String> libSet;
2948        synchronized (mPackages) {
2949            libSet = mSharedLibraries.keySet();
2950            int size = libSet.size();
2951            if (size > 0) {
2952                String[] libs = new String[size];
2953                libSet.toArray(libs);
2954                return libs;
2955            }
2956        }
2957        return null;
2958    }
2959
2960    /**
2961     * @hide
2962     */
2963    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2964        synchronized (mPackages) {
2965            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2966            if (lib != null && lib.apk != null) {
2967                return mPackages.get(lib.apk);
2968            }
2969        }
2970        return null;
2971    }
2972
2973    @Override
2974    public FeatureInfo[] getSystemAvailableFeatures() {
2975        Collection<FeatureInfo> featSet;
2976        synchronized (mPackages) {
2977            featSet = mAvailableFeatures.values();
2978            int size = featSet.size();
2979            if (size > 0) {
2980                FeatureInfo[] features = new FeatureInfo[size+1];
2981                featSet.toArray(features);
2982                FeatureInfo fi = new FeatureInfo();
2983                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2984                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2985                features[size] = fi;
2986                return features;
2987            }
2988        }
2989        return null;
2990    }
2991
2992    @Override
2993    public boolean hasSystemFeature(String name) {
2994        synchronized (mPackages) {
2995            return mAvailableFeatures.containsKey(name);
2996        }
2997    }
2998
2999    private void checkValidCaller(int uid, int userId) {
3000        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3001            return;
3002
3003        throw new SecurityException("Caller uid=" + uid
3004                + " is not privileged to communicate with user=" + userId);
3005    }
3006
3007    @Override
3008    public int checkPermission(String permName, String pkgName, int userId) {
3009        if (!sUserManager.exists(userId)) {
3010            return PackageManager.PERMISSION_DENIED;
3011        }
3012
3013        synchronized (mPackages) {
3014            final PackageParser.Package p = mPackages.get(pkgName);
3015            if (p != null && p.mExtras != null) {
3016                final PackageSetting ps = (PackageSetting) p.mExtras;
3017                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3018                    return PackageManager.PERMISSION_GRANTED;
3019                }
3020            }
3021        }
3022
3023        return PackageManager.PERMISSION_DENIED;
3024    }
3025
3026    @Override
3027    public int checkUidPermission(String permName, int uid) {
3028        final int userId = UserHandle.getUserId(uid);
3029
3030        if (!sUserManager.exists(userId)) {
3031            return PackageManager.PERMISSION_DENIED;
3032        }
3033
3034        synchronized (mPackages) {
3035            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3036            if (obj != null) {
3037                final SettingBase ps = (SettingBase) obj;
3038                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3039                    return PackageManager.PERMISSION_GRANTED;
3040                }
3041            } else {
3042                ArraySet<String> perms = mSystemPermissions.get(uid);
3043                if (perms != null && perms.contains(permName)) {
3044                    return PackageManager.PERMISSION_GRANTED;
3045                }
3046            }
3047        }
3048
3049        return PackageManager.PERMISSION_DENIED;
3050    }
3051
3052    /**
3053     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3054     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3055     * @param checkShell TODO(yamasani):
3056     * @param message the message to log on security exception
3057     */
3058    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3059            boolean checkShell, String message) {
3060        if (userId < 0) {
3061            throw new IllegalArgumentException("Invalid userId " + userId);
3062        }
3063        if (checkShell) {
3064            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3065        }
3066        if (userId == UserHandle.getUserId(callingUid)) return;
3067        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3068            if (requireFullPermission) {
3069                mContext.enforceCallingOrSelfPermission(
3070                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3071            } else {
3072                try {
3073                    mContext.enforceCallingOrSelfPermission(
3074                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3075                } catch (SecurityException se) {
3076                    mContext.enforceCallingOrSelfPermission(
3077                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3078                }
3079            }
3080        }
3081    }
3082
3083    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3084        if (callingUid == Process.SHELL_UID) {
3085            if (userHandle >= 0
3086                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3087                throw new SecurityException("Shell does not have permission to access user "
3088                        + userHandle);
3089            } else if (userHandle < 0) {
3090                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3091                        + Debug.getCallers(3));
3092            }
3093        }
3094    }
3095
3096    private BasePermission findPermissionTreeLP(String permName) {
3097        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3098            if (permName.startsWith(bp.name) &&
3099                    permName.length() > bp.name.length() &&
3100                    permName.charAt(bp.name.length()) == '.') {
3101                return bp;
3102            }
3103        }
3104        return null;
3105    }
3106
3107    private BasePermission checkPermissionTreeLP(String permName) {
3108        if (permName != null) {
3109            BasePermission bp = findPermissionTreeLP(permName);
3110            if (bp != null) {
3111                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3112                    return bp;
3113                }
3114                throw new SecurityException("Calling uid "
3115                        + Binder.getCallingUid()
3116                        + " is not allowed to add to permission tree "
3117                        + bp.name + " owned by uid " + bp.uid);
3118            }
3119        }
3120        throw new SecurityException("No permission tree found for " + permName);
3121    }
3122
3123    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3124        if (s1 == null) {
3125            return s2 == null;
3126        }
3127        if (s2 == null) {
3128            return false;
3129        }
3130        if (s1.getClass() != s2.getClass()) {
3131            return false;
3132        }
3133        return s1.equals(s2);
3134    }
3135
3136    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3137        if (pi1.icon != pi2.icon) return false;
3138        if (pi1.logo != pi2.logo) return false;
3139        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3140        if (!compareStrings(pi1.name, pi2.name)) return false;
3141        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3142        // We'll take care of setting this one.
3143        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3144        // These are not currently stored in settings.
3145        //if (!compareStrings(pi1.group, pi2.group)) return false;
3146        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3147        //if (pi1.labelRes != pi2.labelRes) return false;
3148        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3149        return true;
3150    }
3151
3152    int permissionInfoFootprint(PermissionInfo info) {
3153        int size = info.name.length();
3154        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3155        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3156        return size;
3157    }
3158
3159    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3160        int size = 0;
3161        for (BasePermission perm : mSettings.mPermissions.values()) {
3162            if (perm.uid == tree.uid) {
3163                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3164            }
3165        }
3166        return size;
3167    }
3168
3169    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3170        // We calculate the max size of permissions defined by this uid and throw
3171        // if that plus the size of 'info' would exceed our stated maximum.
3172        if (tree.uid != Process.SYSTEM_UID) {
3173            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3174            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3175                throw new SecurityException("Permission tree size cap exceeded");
3176            }
3177        }
3178    }
3179
3180    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3181        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3182            throw new SecurityException("Label must be specified in permission");
3183        }
3184        BasePermission tree = checkPermissionTreeLP(info.name);
3185        BasePermission bp = mSettings.mPermissions.get(info.name);
3186        boolean added = bp == null;
3187        boolean changed = true;
3188        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3189        if (added) {
3190            enforcePermissionCapLocked(info, tree);
3191            bp = new BasePermission(info.name, tree.sourcePackage,
3192                    BasePermission.TYPE_DYNAMIC);
3193        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3194            throw new SecurityException(
3195                    "Not allowed to modify non-dynamic permission "
3196                    + info.name);
3197        } else {
3198            if (bp.protectionLevel == fixedLevel
3199                    && bp.perm.owner.equals(tree.perm.owner)
3200                    && bp.uid == tree.uid
3201                    && comparePermissionInfos(bp.perm.info, info)) {
3202                changed = false;
3203            }
3204        }
3205        bp.protectionLevel = fixedLevel;
3206        info = new PermissionInfo(info);
3207        info.protectionLevel = fixedLevel;
3208        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3209        bp.perm.info.packageName = tree.perm.info.packageName;
3210        bp.uid = tree.uid;
3211        if (added) {
3212            mSettings.mPermissions.put(info.name, bp);
3213        }
3214        if (changed) {
3215            if (!async) {
3216                mSettings.writeLPr();
3217            } else {
3218                scheduleWriteSettingsLocked();
3219            }
3220        }
3221        return added;
3222    }
3223
3224    @Override
3225    public boolean addPermission(PermissionInfo info) {
3226        synchronized (mPackages) {
3227            return addPermissionLocked(info, false);
3228        }
3229    }
3230
3231    @Override
3232    public boolean addPermissionAsync(PermissionInfo info) {
3233        synchronized (mPackages) {
3234            return addPermissionLocked(info, true);
3235        }
3236    }
3237
3238    @Override
3239    public void removePermission(String name) {
3240        synchronized (mPackages) {
3241            checkPermissionTreeLP(name);
3242            BasePermission bp = mSettings.mPermissions.get(name);
3243            if (bp != null) {
3244                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3245                    throw new SecurityException(
3246                            "Not allowed to modify non-dynamic permission "
3247                            + name);
3248                }
3249                mSettings.mPermissions.remove(name);
3250                mSettings.writeLPr();
3251            }
3252        }
3253    }
3254
3255    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3256            BasePermission bp) {
3257        int index = pkg.requestedPermissions.indexOf(bp.name);
3258        if (index == -1) {
3259            throw new SecurityException("Package " + pkg.packageName
3260                    + " has not requested permission " + bp.name);
3261        }
3262        if (!bp.isRuntime()) {
3263            throw new SecurityException("Permission " + bp.name
3264                    + " is not a changeable permission type");
3265        }
3266    }
3267
3268    @Override
3269    public void grantRuntimePermission(String packageName, String name, final int userId) {
3270        if (!sUserManager.exists(userId)) {
3271            Log.e(TAG, "No such user:" + userId);
3272            return;
3273        }
3274
3275        mContext.enforceCallingOrSelfPermission(
3276                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3277                "grantRuntimePermission");
3278
3279        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3280                "grantRuntimePermission");
3281
3282        final int uid;
3283        final SettingBase sb;
3284
3285        synchronized (mPackages) {
3286            final PackageParser.Package pkg = mPackages.get(packageName);
3287            if (pkg == null) {
3288                throw new IllegalArgumentException("Unknown package: " + packageName);
3289            }
3290
3291            final BasePermission bp = mSettings.mPermissions.get(name);
3292            if (bp == null) {
3293                throw new IllegalArgumentException("Unknown permission: " + name);
3294            }
3295
3296            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3297
3298            uid = pkg.applicationInfo.uid;
3299            sb = (SettingBase) pkg.mExtras;
3300            if (sb == null) {
3301                throw new IllegalArgumentException("Unknown package: " + packageName);
3302            }
3303
3304            final PermissionsState permissionsState = sb.getPermissionsState();
3305
3306            final int flags = permissionsState.getPermissionFlags(name, userId);
3307            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3308                throw new SecurityException("Cannot grant system fixed permission: "
3309                        + name + " for package: " + packageName);
3310            }
3311
3312            final int result = permissionsState.grantRuntimePermission(bp, userId);
3313            switch (result) {
3314                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3315                    return;
3316                }
3317
3318                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3319                    mHandler.post(new Runnable() {
3320                        @Override
3321                        public void run() {
3322                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3323                        }
3324                    });
3325                } break;
3326            }
3327
3328            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3329
3330            // Not critical if that is lost - app has to request again.
3331            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3332        }
3333
3334        if (READ_EXTERNAL_STORAGE.equals(name)
3335                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3336            final long token = Binder.clearCallingIdentity();
3337            try {
3338                final StorageManager storage = mContext.getSystemService(StorageManager.class);
3339                storage.remountUid(uid);
3340            } finally {
3341                Binder.restoreCallingIdentity(token);
3342            }
3343        }
3344    }
3345
3346    @Override
3347    public void revokeRuntimePermission(String packageName, String name, int userId) {
3348        if (!sUserManager.exists(userId)) {
3349            Log.e(TAG, "No such user:" + userId);
3350            return;
3351        }
3352
3353        mContext.enforceCallingOrSelfPermission(
3354                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3355                "revokeRuntimePermission");
3356
3357        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3358                "revokeRuntimePermission");
3359
3360        final SettingBase sb;
3361
3362        synchronized (mPackages) {
3363            final PackageParser.Package pkg = mPackages.get(packageName);
3364            if (pkg == null) {
3365                throw new IllegalArgumentException("Unknown package: " + packageName);
3366            }
3367
3368            final BasePermission bp = mSettings.mPermissions.get(name);
3369            if (bp == null) {
3370                throw new IllegalArgumentException("Unknown permission: " + name);
3371            }
3372
3373            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3374
3375            sb = (SettingBase) pkg.mExtras;
3376            if (sb == null) {
3377                throw new IllegalArgumentException("Unknown package: " + packageName);
3378            }
3379
3380            final PermissionsState permissionsState = sb.getPermissionsState();
3381
3382            final int flags = permissionsState.getPermissionFlags(name, userId);
3383            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3384                throw new SecurityException("Cannot revoke system fixed permission: "
3385                        + name + " for package: " + packageName);
3386            }
3387
3388            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3389                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3390                return;
3391            }
3392
3393            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3394
3395            // Critical, after this call app should never have the permission.
3396            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3397        }
3398
3399        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3400    }
3401
3402    @Override
3403    public void resetRuntimePermissions() {
3404        mContext.enforceCallingOrSelfPermission(
3405                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3406                "revokeRuntimePermission");
3407
3408        int callingUid = Binder.getCallingUid();
3409        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3410            mContext.enforceCallingOrSelfPermission(
3411                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3412                    "resetRuntimePermissions");
3413        }
3414
3415        synchronized (mPackages) {
3416            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3417            for (int userId : UserManagerService.getInstance().getUserIds()) {
3418                mDefaultPermissionPolicy.grantDefaultPermissions(userId);
3419            }
3420        }
3421    }
3422
3423    @Override
3424    public int getPermissionFlags(String name, String packageName, int userId) {
3425        if (!sUserManager.exists(userId)) {
3426            return 0;
3427        }
3428
3429        mContext.enforceCallingOrSelfPermission(
3430                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3431                "getPermissionFlags");
3432
3433        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3434                "getPermissionFlags");
3435
3436        synchronized (mPackages) {
3437            final PackageParser.Package pkg = mPackages.get(packageName);
3438            if (pkg == null) {
3439                throw new IllegalArgumentException("Unknown package: " + packageName);
3440            }
3441
3442            final BasePermission bp = mSettings.mPermissions.get(name);
3443            if (bp == null) {
3444                throw new IllegalArgumentException("Unknown permission: " + name);
3445            }
3446
3447            SettingBase sb = (SettingBase) pkg.mExtras;
3448            if (sb == null) {
3449                throw new IllegalArgumentException("Unknown package: " + packageName);
3450            }
3451
3452            PermissionsState permissionsState = sb.getPermissionsState();
3453            return permissionsState.getPermissionFlags(name, userId);
3454        }
3455    }
3456
3457    @Override
3458    public void updatePermissionFlags(String name, String packageName, int flagMask,
3459            int flagValues, int userId) {
3460        if (!sUserManager.exists(userId)) {
3461            return;
3462        }
3463
3464        mContext.enforceCallingOrSelfPermission(
3465                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3466                "updatePermissionFlags");
3467
3468        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3469                "updatePermissionFlags");
3470
3471        // Only the system can change system fixed flags.
3472        if (getCallingUid() != Process.SYSTEM_UID) {
3473            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3474            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3475        }
3476
3477        synchronized (mPackages) {
3478            final PackageParser.Package pkg = mPackages.get(packageName);
3479            if (pkg == null) {
3480                throw new IllegalArgumentException("Unknown package: " + packageName);
3481            }
3482
3483            final BasePermission bp = mSettings.mPermissions.get(name);
3484            if (bp == null) {
3485                throw new IllegalArgumentException("Unknown permission: " + name);
3486            }
3487
3488            SettingBase sb = (SettingBase) pkg.mExtras;
3489            if (sb == null) {
3490                throw new IllegalArgumentException("Unknown package: " + packageName);
3491            }
3492
3493            PermissionsState permissionsState = sb.getPermissionsState();
3494
3495            // Only the package manager can change flags for system component permissions.
3496            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3497            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3498                return;
3499            }
3500
3501            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3502
3503            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3504                // Install and runtime permissions are stored in different places,
3505                // so figure out what permission changed and persist the change.
3506                if (permissionsState.getInstallPermissionState(name) != null) {
3507                    scheduleWriteSettingsLocked();
3508                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3509                        || hadState) {
3510                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3511                }
3512            }
3513        }
3514    }
3515
3516    /**
3517     * Update the permission flags for all packages and runtime permissions of a user in order
3518     * to allow device or profile owner to remove POLICY_FIXED.
3519     */
3520    @Override
3521    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3522        if (!sUserManager.exists(userId)) {
3523            return;
3524        }
3525
3526        mContext.enforceCallingOrSelfPermission(
3527                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3528                "updatePermissionFlagsForAllApps");
3529
3530        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3531                "updatePermissionFlagsForAllApps");
3532
3533        // Only the system can change system fixed flags.
3534        if (getCallingUid() != Process.SYSTEM_UID) {
3535            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3536            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3537        }
3538
3539        synchronized (mPackages) {
3540            boolean changed = false;
3541            final int packageCount = mPackages.size();
3542            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3543                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3544                SettingBase sb = (SettingBase) pkg.mExtras;
3545                if (sb == null) {
3546                    continue;
3547                }
3548                PermissionsState permissionsState = sb.getPermissionsState();
3549                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3550                        userId, flagMask, flagValues);
3551            }
3552            if (changed) {
3553                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3554            }
3555        }
3556    }
3557
3558    @Override
3559    public boolean shouldShowRequestPermissionRationale(String permissionName,
3560            String packageName, int userId) {
3561        if (UserHandle.getCallingUserId() != userId) {
3562            mContext.enforceCallingPermission(
3563                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3564                    "canShowRequestPermissionRationale for user " + userId);
3565        }
3566
3567        final int uid = getPackageUid(packageName, userId);
3568        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3569            return false;
3570        }
3571
3572        if (checkPermission(permissionName, packageName, userId)
3573                == PackageManager.PERMISSION_GRANTED) {
3574            return false;
3575        }
3576
3577        final int flags;
3578
3579        final long identity = Binder.clearCallingIdentity();
3580        try {
3581            flags = getPermissionFlags(permissionName,
3582                    packageName, userId);
3583        } finally {
3584            Binder.restoreCallingIdentity(identity);
3585        }
3586
3587        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3588                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3589                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3590
3591        if ((flags & fixedFlags) != 0) {
3592            return false;
3593        }
3594
3595        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3596    }
3597
3598    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3599        BasePermission bp = mSettings.mPermissions.get(permission);
3600        if (bp == null) {
3601            throw new SecurityException("Missing " + permission + " permission");
3602        }
3603
3604        SettingBase sb = (SettingBase) pkg.mExtras;
3605        PermissionsState permissionsState = sb.getPermissionsState();
3606
3607        if (permissionsState.grantInstallPermission(bp) !=
3608                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3609            scheduleWriteSettingsLocked();
3610        }
3611    }
3612
3613    @Override
3614    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3615        mContext.enforceCallingOrSelfPermission(
3616                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3617                "addOnPermissionsChangeListener");
3618
3619        synchronized (mPackages) {
3620            mOnPermissionChangeListeners.addListenerLocked(listener);
3621        }
3622    }
3623
3624    @Override
3625    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3626        synchronized (mPackages) {
3627            mOnPermissionChangeListeners.removeListenerLocked(listener);
3628        }
3629    }
3630
3631    @Override
3632    public boolean isProtectedBroadcast(String actionName) {
3633        synchronized (mPackages) {
3634            return mProtectedBroadcasts.contains(actionName);
3635        }
3636    }
3637
3638    @Override
3639    public int checkSignatures(String pkg1, String pkg2) {
3640        synchronized (mPackages) {
3641            final PackageParser.Package p1 = mPackages.get(pkg1);
3642            final PackageParser.Package p2 = mPackages.get(pkg2);
3643            if (p1 == null || p1.mExtras == null
3644                    || p2 == null || p2.mExtras == null) {
3645                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3646            }
3647            return compareSignatures(p1.mSignatures, p2.mSignatures);
3648        }
3649    }
3650
3651    @Override
3652    public int checkUidSignatures(int uid1, int uid2) {
3653        // Map to base uids.
3654        uid1 = UserHandle.getAppId(uid1);
3655        uid2 = UserHandle.getAppId(uid2);
3656        // reader
3657        synchronized (mPackages) {
3658            Signature[] s1;
3659            Signature[] s2;
3660            Object obj = mSettings.getUserIdLPr(uid1);
3661            if (obj != null) {
3662                if (obj instanceof SharedUserSetting) {
3663                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3664                } else if (obj instanceof PackageSetting) {
3665                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3666                } else {
3667                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3668                }
3669            } else {
3670                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3671            }
3672            obj = mSettings.getUserIdLPr(uid2);
3673            if (obj != null) {
3674                if (obj instanceof SharedUserSetting) {
3675                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3676                } else if (obj instanceof PackageSetting) {
3677                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3678                } else {
3679                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3680                }
3681            } else {
3682                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3683            }
3684            return compareSignatures(s1, s2);
3685        }
3686    }
3687
3688    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3689        final long identity = Binder.clearCallingIdentity();
3690        try {
3691            if (sb instanceof SharedUserSetting) {
3692                SharedUserSetting sus = (SharedUserSetting) sb;
3693                final int packageCount = sus.packages.size();
3694                for (int i = 0; i < packageCount; i++) {
3695                    PackageSetting susPs = sus.packages.valueAt(i);
3696                    if (userId == UserHandle.USER_ALL) {
3697                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3698                    } else {
3699                        final int uid = UserHandle.getUid(userId, susPs.appId);
3700                        killUid(uid, reason);
3701                    }
3702                }
3703            } else if (sb instanceof PackageSetting) {
3704                PackageSetting ps = (PackageSetting) sb;
3705                if (userId == UserHandle.USER_ALL) {
3706                    killApplication(ps.pkg.packageName, ps.appId, reason);
3707                } else {
3708                    final int uid = UserHandle.getUid(userId, ps.appId);
3709                    killUid(uid, reason);
3710                }
3711            }
3712        } finally {
3713            Binder.restoreCallingIdentity(identity);
3714        }
3715    }
3716
3717    private static void killUid(int uid, String reason) {
3718        IActivityManager am = ActivityManagerNative.getDefault();
3719        if (am != null) {
3720            try {
3721                am.killUid(uid, reason);
3722            } catch (RemoteException e) {
3723                /* ignore - same process */
3724            }
3725        }
3726    }
3727
3728    /**
3729     * Compares two sets of signatures. Returns:
3730     * <br />
3731     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3732     * <br />
3733     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3734     * <br />
3735     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3736     * <br />
3737     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3738     * <br />
3739     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3740     */
3741    static int compareSignatures(Signature[] s1, Signature[] s2) {
3742        if (s1 == null) {
3743            return s2 == null
3744                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3745                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3746        }
3747
3748        if (s2 == null) {
3749            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3750        }
3751
3752        if (s1.length != s2.length) {
3753            return PackageManager.SIGNATURE_NO_MATCH;
3754        }
3755
3756        // Since both signature sets are of size 1, we can compare without HashSets.
3757        if (s1.length == 1) {
3758            return s1[0].equals(s2[0]) ?
3759                    PackageManager.SIGNATURE_MATCH :
3760                    PackageManager.SIGNATURE_NO_MATCH;
3761        }
3762
3763        ArraySet<Signature> set1 = new ArraySet<Signature>();
3764        for (Signature sig : s1) {
3765            set1.add(sig);
3766        }
3767        ArraySet<Signature> set2 = new ArraySet<Signature>();
3768        for (Signature sig : s2) {
3769            set2.add(sig);
3770        }
3771        // Make sure s2 contains all signatures in s1.
3772        if (set1.equals(set2)) {
3773            return PackageManager.SIGNATURE_MATCH;
3774        }
3775        return PackageManager.SIGNATURE_NO_MATCH;
3776    }
3777
3778    /**
3779     * If the database version for this type of package (internal storage or
3780     * external storage) is less than the version where package signatures
3781     * were updated, return true.
3782     */
3783    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3784        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3785                DatabaseVersion.SIGNATURE_END_ENTITY))
3786                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3787                        DatabaseVersion.SIGNATURE_END_ENTITY));
3788    }
3789
3790    /**
3791     * Used for backward compatibility to make sure any packages with
3792     * certificate chains get upgraded to the new style. {@code existingSigs}
3793     * will be in the old format (since they were stored on disk from before the
3794     * system upgrade) and {@code scannedSigs} will be in the newer format.
3795     */
3796    private int compareSignaturesCompat(PackageSignatures existingSigs,
3797            PackageParser.Package scannedPkg) {
3798        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3799            return PackageManager.SIGNATURE_NO_MATCH;
3800        }
3801
3802        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3803        for (Signature sig : existingSigs.mSignatures) {
3804            existingSet.add(sig);
3805        }
3806        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3807        for (Signature sig : scannedPkg.mSignatures) {
3808            try {
3809                Signature[] chainSignatures = sig.getChainSignatures();
3810                for (Signature chainSig : chainSignatures) {
3811                    scannedCompatSet.add(chainSig);
3812                }
3813            } catch (CertificateEncodingException e) {
3814                scannedCompatSet.add(sig);
3815            }
3816        }
3817        /*
3818         * Make sure the expanded scanned set contains all signatures in the
3819         * existing one.
3820         */
3821        if (scannedCompatSet.equals(existingSet)) {
3822            // Migrate the old signatures to the new scheme.
3823            existingSigs.assignSignatures(scannedPkg.mSignatures);
3824            // The new KeySets will be re-added later in the scanning process.
3825            synchronized (mPackages) {
3826                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3827            }
3828            return PackageManager.SIGNATURE_MATCH;
3829        }
3830        return PackageManager.SIGNATURE_NO_MATCH;
3831    }
3832
3833    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3834        if (isExternal(scannedPkg)) {
3835            return mSettings.isExternalDatabaseVersionOlderThan(
3836                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3837        } else {
3838            return mSettings.isInternalDatabaseVersionOlderThan(
3839                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3840        }
3841    }
3842
3843    private int compareSignaturesRecover(PackageSignatures existingSigs,
3844            PackageParser.Package scannedPkg) {
3845        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3846            return PackageManager.SIGNATURE_NO_MATCH;
3847        }
3848
3849        String msg = null;
3850        try {
3851            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3852                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3853                        + scannedPkg.packageName);
3854                return PackageManager.SIGNATURE_MATCH;
3855            }
3856        } catch (CertificateException e) {
3857            msg = e.getMessage();
3858        }
3859
3860        logCriticalInfo(Log.INFO,
3861                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3862        return PackageManager.SIGNATURE_NO_MATCH;
3863    }
3864
3865    @Override
3866    public String[] getPackagesForUid(int uid) {
3867        uid = UserHandle.getAppId(uid);
3868        // reader
3869        synchronized (mPackages) {
3870            Object obj = mSettings.getUserIdLPr(uid);
3871            if (obj instanceof SharedUserSetting) {
3872                final SharedUserSetting sus = (SharedUserSetting) obj;
3873                final int N = sus.packages.size();
3874                final String[] res = new String[N];
3875                final Iterator<PackageSetting> it = sus.packages.iterator();
3876                int i = 0;
3877                while (it.hasNext()) {
3878                    res[i++] = it.next().name;
3879                }
3880                return res;
3881            } else if (obj instanceof PackageSetting) {
3882                final PackageSetting ps = (PackageSetting) obj;
3883                return new String[] { ps.name };
3884            }
3885        }
3886        return null;
3887    }
3888
3889    @Override
3890    public String getNameForUid(int uid) {
3891        // reader
3892        synchronized (mPackages) {
3893            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3894            if (obj instanceof SharedUserSetting) {
3895                final SharedUserSetting sus = (SharedUserSetting) obj;
3896                return sus.name + ":" + sus.userId;
3897            } else if (obj instanceof PackageSetting) {
3898                final PackageSetting ps = (PackageSetting) obj;
3899                return ps.name;
3900            }
3901        }
3902        return null;
3903    }
3904
3905    @Override
3906    public int getUidForSharedUser(String sharedUserName) {
3907        if(sharedUserName == null) {
3908            return -1;
3909        }
3910        // reader
3911        synchronized (mPackages) {
3912            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3913            if (suid == null) {
3914                return -1;
3915            }
3916            return suid.userId;
3917        }
3918    }
3919
3920    @Override
3921    public int getFlagsForUid(int uid) {
3922        synchronized (mPackages) {
3923            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3924            if (obj instanceof SharedUserSetting) {
3925                final SharedUserSetting sus = (SharedUserSetting) obj;
3926                return sus.pkgFlags;
3927            } else if (obj instanceof PackageSetting) {
3928                final PackageSetting ps = (PackageSetting) obj;
3929                return ps.pkgFlags;
3930            }
3931        }
3932        return 0;
3933    }
3934
3935    @Override
3936    public int getPrivateFlagsForUid(int uid) {
3937        synchronized (mPackages) {
3938            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3939            if (obj instanceof SharedUserSetting) {
3940                final SharedUserSetting sus = (SharedUserSetting) obj;
3941                return sus.pkgPrivateFlags;
3942            } else if (obj instanceof PackageSetting) {
3943                final PackageSetting ps = (PackageSetting) obj;
3944                return ps.pkgPrivateFlags;
3945            }
3946        }
3947        return 0;
3948    }
3949
3950    @Override
3951    public boolean isUidPrivileged(int uid) {
3952        uid = UserHandle.getAppId(uid);
3953        // reader
3954        synchronized (mPackages) {
3955            Object obj = mSettings.getUserIdLPr(uid);
3956            if (obj instanceof SharedUserSetting) {
3957                final SharedUserSetting sus = (SharedUserSetting) obj;
3958                final Iterator<PackageSetting> it = sus.packages.iterator();
3959                while (it.hasNext()) {
3960                    if (it.next().isPrivileged()) {
3961                        return true;
3962                    }
3963                }
3964            } else if (obj instanceof PackageSetting) {
3965                final PackageSetting ps = (PackageSetting) obj;
3966                return ps.isPrivileged();
3967            }
3968        }
3969        return false;
3970    }
3971
3972    @Override
3973    public String[] getAppOpPermissionPackages(String permissionName) {
3974        synchronized (mPackages) {
3975            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3976            if (pkgs == null) {
3977                return null;
3978            }
3979            return pkgs.toArray(new String[pkgs.size()]);
3980        }
3981    }
3982
3983    @Override
3984    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3985            int flags, int userId) {
3986        if (!sUserManager.exists(userId)) return null;
3987        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3988        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3989        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3990    }
3991
3992    @Override
3993    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3994            IntentFilter filter, int match, ComponentName activity) {
3995        final int userId = UserHandle.getCallingUserId();
3996        if (DEBUG_PREFERRED) {
3997            Log.v(TAG, "setLastChosenActivity intent=" + intent
3998                + " resolvedType=" + resolvedType
3999                + " flags=" + flags
4000                + " filter=" + filter
4001                + " match=" + match
4002                + " activity=" + activity);
4003            filter.dump(new PrintStreamPrinter(System.out), "    ");
4004        }
4005        intent.setComponent(null);
4006        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4007        // Find any earlier preferred or last chosen entries and nuke them
4008        findPreferredActivity(intent, resolvedType,
4009                flags, query, 0, false, true, false, userId);
4010        // Add the new activity as the last chosen for this filter
4011        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4012                "Setting last chosen");
4013    }
4014
4015    @Override
4016    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4017        final int userId = UserHandle.getCallingUserId();
4018        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4019        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4020        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4021                false, false, false, userId);
4022    }
4023
4024    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4025            int flags, List<ResolveInfo> query, int userId) {
4026        if (query != null) {
4027            final int N = query.size();
4028            if (N == 1) {
4029                return query.get(0);
4030            } else if (N > 1) {
4031                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4032                // If there is more than one activity with the same priority,
4033                // then let the user decide between them.
4034                ResolveInfo r0 = query.get(0);
4035                ResolveInfo r1 = query.get(1);
4036                if (DEBUG_INTENT_MATCHING || debug) {
4037                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4038                            + r1.activityInfo.name + "=" + r1.priority);
4039                }
4040                // If the first activity has a higher priority, or a different
4041                // default, then it is always desireable to pick it.
4042                if (r0.priority != r1.priority
4043                        || r0.preferredOrder != r1.preferredOrder
4044                        || r0.isDefault != r1.isDefault) {
4045                    return query.get(0);
4046                }
4047                // If we have saved a preference for a preferred activity for
4048                // this Intent, use that.
4049                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4050                        flags, query, r0.priority, true, false, debug, userId);
4051                if (ri != null) {
4052                    return ri;
4053                }
4054                if (userId != 0) {
4055                    ri = new ResolveInfo(mResolveInfo);
4056                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4057                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4058                            ri.activityInfo.applicationInfo);
4059                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4060                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4061                    return ri;
4062                }
4063                return mResolveInfo;
4064            }
4065        }
4066        return null;
4067    }
4068
4069    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4070            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4071        final int N = query.size();
4072        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4073                .get(userId);
4074        // Get the list of persistent preferred activities that handle the intent
4075        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4076        List<PersistentPreferredActivity> pprefs = ppir != null
4077                ? ppir.queryIntent(intent, resolvedType,
4078                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4079                : null;
4080        if (pprefs != null && pprefs.size() > 0) {
4081            final int M = pprefs.size();
4082            for (int i=0; i<M; i++) {
4083                final PersistentPreferredActivity ppa = pprefs.get(i);
4084                if (DEBUG_PREFERRED || debug) {
4085                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4086                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4087                            + "\n  component=" + ppa.mComponent);
4088                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4089                }
4090                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4091                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4092                if (DEBUG_PREFERRED || debug) {
4093                    Slog.v(TAG, "Found persistent preferred activity:");
4094                    if (ai != null) {
4095                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4096                    } else {
4097                        Slog.v(TAG, "  null");
4098                    }
4099                }
4100                if (ai == null) {
4101                    // This previously registered persistent preferred activity
4102                    // component is no longer known. Ignore it and do NOT remove it.
4103                    continue;
4104                }
4105                for (int j=0; j<N; j++) {
4106                    final ResolveInfo ri = query.get(j);
4107                    if (!ri.activityInfo.applicationInfo.packageName
4108                            .equals(ai.applicationInfo.packageName)) {
4109                        continue;
4110                    }
4111                    if (!ri.activityInfo.name.equals(ai.name)) {
4112                        continue;
4113                    }
4114                    //  Found a persistent preference that can handle the intent.
4115                    if (DEBUG_PREFERRED || debug) {
4116                        Slog.v(TAG, "Returning persistent preferred activity: " +
4117                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4118                    }
4119                    return ri;
4120                }
4121            }
4122        }
4123        return null;
4124    }
4125
4126    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4127            List<ResolveInfo> query, int priority, boolean always,
4128            boolean removeMatches, boolean debug, int userId) {
4129        if (!sUserManager.exists(userId)) return null;
4130        // writer
4131        synchronized (mPackages) {
4132            if (intent.getSelector() != null) {
4133                intent = intent.getSelector();
4134            }
4135            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4136
4137            // Try to find a matching persistent preferred activity.
4138            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4139                    debug, userId);
4140
4141            // If a persistent preferred activity matched, use it.
4142            if (pri != null) {
4143                return pri;
4144            }
4145
4146            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4147            // Get the list of preferred activities that handle the intent
4148            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4149            List<PreferredActivity> prefs = pir != null
4150                    ? pir.queryIntent(intent, resolvedType,
4151                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4152                    : null;
4153            if (prefs != null && prefs.size() > 0) {
4154                boolean changed = false;
4155                try {
4156                    // First figure out how good the original match set is.
4157                    // We will only allow preferred activities that came
4158                    // from the same match quality.
4159                    int match = 0;
4160
4161                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4162
4163                    final int N = query.size();
4164                    for (int j=0; j<N; j++) {
4165                        final ResolveInfo ri = query.get(j);
4166                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4167                                + ": 0x" + Integer.toHexString(match));
4168                        if (ri.match > match) {
4169                            match = ri.match;
4170                        }
4171                    }
4172
4173                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4174                            + Integer.toHexString(match));
4175
4176                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4177                    final int M = prefs.size();
4178                    for (int i=0; i<M; i++) {
4179                        final PreferredActivity pa = prefs.get(i);
4180                        if (DEBUG_PREFERRED || debug) {
4181                            Slog.v(TAG, "Checking PreferredActivity ds="
4182                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4183                                    + "\n  component=" + pa.mPref.mComponent);
4184                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4185                        }
4186                        if (pa.mPref.mMatch != match) {
4187                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4188                                    + Integer.toHexString(pa.mPref.mMatch));
4189                            continue;
4190                        }
4191                        // If it's not an "always" type preferred activity and that's what we're
4192                        // looking for, skip it.
4193                        if (always && !pa.mPref.mAlways) {
4194                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4195                            continue;
4196                        }
4197                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4198                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4199                        if (DEBUG_PREFERRED || debug) {
4200                            Slog.v(TAG, "Found preferred activity:");
4201                            if (ai != null) {
4202                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4203                            } else {
4204                                Slog.v(TAG, "  null");
4205                            }
4206                        }
4207                        if (ai == null) {
4208                            // This previously registered preferred activity
4209                            // component is no longer known.  Most likely an update
4210                            // to the app was installed and in the new version this
4211                            // component no longer exists.  Clean it up by removing
4212                            // it from the preferred activities list, and skip it.
4213                            Slog.w(TAG, "Removing dangling preferred activity: "
4214                                    + pa.mPref.mComponent);
4215                            pir.removeFilter(pa);
4216                            changed = true;
4217                            continue;
4218                        }
4219                        for (int j=0; j<N; j++) {
4220                            final ResolveInfo ri = query.get(j);
4221                            if (!ri.activityInfo.applicationInfo.packageName
4222                                    .equals(ai.applicationInfo.packageName)) {
4223                                continue;
4224                            }
4225                            if (!ri.activityInfo.name.equals(ai.name)) {
4226                                continue;
4227                            }
4228
4229                            if (removeMatches) {
4230                                pir.removeFilter(pa);
4231                                changed = true;
4232                                if (DEBUG_PREFERRED) {
4233                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4234                                }
4235                                break;
4236                            }
4237
4238                            // Okay we found a previously set preferred or last chosen app.
4239                            // If the result set is different from when this
4240                            // was created, we need to clear it and re-ask the
4241                            // user their preference, if we're looking for an "always" type entry.
4242                            if (always && !pa.mPref.sameSet(query)) {
4243                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4244                                        + intent + " type " + resolvedType);
4245                                if (DEBUG_PREFERRED) {
4246                                    Slog.v(TAG, "Removing preferred activity since set changed "
4247                                            + pa.mPref.mComponent);
4248                                }
4249                                pir.removeFilter(pa);
4250                                // Re-add the filter as a "last chosen" entry (!always)
4251                                PreferredActivity lastChosen = new PreferredActivity(
4252                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4253                                pir.addFilter(lastChosen);
4254                                changed = true;
4255                                return null;
4256                            }
4257
4258                            // Yay! Either the set matched or we're looking for the last chosen
4259                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4260                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4261                            return ri;
4262                        }
4263                    }
4264                } finally {
4265                    if (changed) {
4266                        if (DEBUG_PREFERRED) {
4267                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4268                        }
4269                        scheduleWritePackageRestrictionsLocked(userId);
4270                    }
4271                }
4272            }
4273        }
4274        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4275        return null;
4276    }
4277
4278    /*
4279     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4280     */
4281    @Override
4282    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4283            int targetUserId) {
4284        mContext.enforceCallingOrSelfPermission(
4285                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4286        List<CrossProfileIntentFilter> matches =
4287                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4288        if (matches != null) {
4289            int size = matches.size();
4290            for (int i = 0; i < size; i++) {
4291                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4292            }
4293        }
4294        if (hasWebURI(intent)) {
4295            // cross-profile app linking works only towards the parent.
4296            final UserInfo parent = getProfileParent(sourceUserId);
4297            synchronized(mPackages) {
4298                return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId,
4299                        parent.id) != null;
4300            }
4301        }
4302        return false;
4303    }
4304
4305    private UserInfo getProfileParent(int userId) {
4306        final long identity = Binder.clearCallingIdentity();
4307        try {
4308            return sUserManager.getProfileParent(userId);
4309        } finally {
4310            Binder.restoreCallingIdentity(identity);
4311        }
4312    }
4313
4314    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4315            String resolvedType, int userId) {
4316        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4317        if (resolver != null) {
4318            return resolver.queryIntent(intent, resolvedType, false, userId);
4319        }
4320        return null;
4321    }
4322
4323    @Override
4324    public List<ResolveInfo> queryIntentActivities(Intent intent,
4325            String resolvedType, int flags, int userId) {
4326        if (!sUserManager.exists(userId)) return Collections.emptyList();
4327        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4328        ComponentName comp = intent.getComponent();
4329        if (comp == null) {
4330            if (intent.getSelector() != null) {
4331                intent = intent.getSelector();
4332                comp = intent.getComponent();
4333            }
4334        }
4335
4336        if (comp != null) {
4337            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4338            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4339            if (ai != null) {
4340                final ResolveInfo ri = new ResolveInfo();
4341                ri.activityInfo = ai;
4342                list.add(ri);
4343            }
4344            return list;
4345        }
4346
4347        // reader
4348        synchronized (mPackages) {
4349            final String pkgName = intent.getPackage();
4350            if (pkgName == null) {
4351                List<CrossProfileIntentFilter> matchingFilters =
4352                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4353                // Check for results that need to skip the current profile.
4354                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4355                        resolvedType, flags, userId);
4356                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4357                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4358                    result.add(xpResolveInfo);
4359                    return filterIfNotPrimaryUser(result, userId);
4360                }
4361
4362                // Check for results in the current profile.
4363                List<ResolveInfo> result = mActivities.queryIntent(
4364                        intent, resolvedType, flags, userId);
4365
4366                // Check for cross profile results.
4367                xpResolveInfo = queryCrossProfileIntents(
4368                        matchingFilters, intent, resolvedType, flags, userId);
4369                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4370                    result.add(xpResolveInfo);
4371                    Collections.sort(result, mResolvePrioritySorter);
4372                }
4373                result = filterIfNotPrimaryUser(result, userId);
4374                if (hasWebURI(intent)) {
4375                    CrossProfileDomainInfo xpDomainInfo = null;
4376                    final UserInfo parent = getProfileParent(userId);
4377                    if (parent != null) {
4378                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4379                                flags, userId, parent.id);
4380                    }
4381                    if (xpDomainInfo != null) {
4382                        if (xpResolveInfo != null) {
4383                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4384                            // in the result.
4385                            result.remove(xpResolveInfo);
4386                        }
4387                        if (result.size() == 0) {
4388                            result.add(xpDomainInfo.resolveInfo);
4389                            return result;
4390                        }
4391                    } else if (result.size() <= 1) {
4392                        return result;
4393                    }
4394                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4395                            xpDomainInfo);
4396                    Collections.sort(result, mResolvePrioritySorter);
4397                }
4398                return result;
4399            }
4400            final PackageParser.Package pkg = mPackages.get(pkgName);
4401            if (pkg != null) {
4402                return filterIfNotPrimaryUser(
4403                        mActivities.queryIntentForPackage(
4404                                intent, resolvedType, flags, pkg.activities, userId),
4405                        userId);
4406            }
4407            return new ArrayList<ResolveInfo>();
4408        }
4409    }
4410
4411    private static class CrossProfileDomainInfo {
4412        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4413        ResolveInfo resolveInfo;
4414        /* Best domain verification status of the activities found in the other profile */
4415        int bestDomainVerificationStatus;
4416    }
4417
4418    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4419            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4420        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_APP_LINKING,
4421                sourceUserId)) {
4422            return null;
4423        }
4424        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4425                resolvedType, flags, parentUserId);
4426
4427        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4428            return null;
4429        }
4430        CrossProfileDomainInfo result = null;
4431        int size = resultTargetUser.size();
4432        for (int i = 0; i < size; i++) {
4433            ResolveInfo riTargetUser = resultTargetUser.get(i);
4434            // Intent filter verification is only for filters that specify a host. So don't return
4435            // those that handle all web uris.
4436            if (riTargetUser.handleAllWebDataURI) {
4437                continue;
4438            }
4439            String packageName = riTargetUser.activityInfo.packageName;
4440            PackageSetting ps = mSettings.mPackages.get(packageName);
4441            if (ps == null) {
4442                continue;
4443            }
4444            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4445            if (result == null) {
4446                result = new CrossProfileDomainInfo();
4447                result.resolveInfo =
4448                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4449                result.bestDomainVerificationStatus = status;
4450            } else {
4451                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4452                        result.bestDomainVerificationStatus);
4453            }
4454        }
4455        return result;
4456    }
4457
4458    /**
4459     * Verification statuses are ordered from the worse to the best, except for
4460     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4461     */
4462    private int bestDomainVerificationStatus(int status1, int status2) {
4463        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4464            return status2;
4465        }
4466        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4467            return status1;
4468        }
4469        return (int) MathUtils.max(status1, status2);
4470    }
4471
4472    private boolean isUserEnabled(int userId) {
4473        long callingId = Binder.clearCallingIdentity();
4474        try {
4475            UserInfo userInfo = sUserManager.getUserInfo(userId);
4476            return userInfo != null && userInfo.isEnabled();
4477        } finally {
4478            Binder.restoreCallingIdentity(callingId);
4479        }
4480    }
4481
4482    /**
4483     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4484     *
4485     * @return filtered list
4486     */
4487    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4488        if (userId == UserHandle.USER_OWNER) {
4489            return resolveInfos;
4490        }
4491        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4492            ResolveInfo info = resolveInfos.get(i);
4493            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4494                resolveInfos.remove(i);
4495            }
4496        }
4497        return resolveInfos;
4498    }
4499
4500    private static boolean hasWebURI(Intent intent) {
4501        if (intent.getData() == null) {
4502            return false;
4503        }
4504        final String scheme = intent.getScheme();
4505        if (TextUtils.isEmpty(scheme)) {
4506            return false;
4507        }
4508        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4509    }
4510
4511    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4512            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4513        if (DEBUG_PREFERRED) {
4514            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4515                    candidates.size());
4516        }
4517
4518        final int userId = UserHandle.getCallingUserId();
4519        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4520        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4521        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4522        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4523        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4524
4525        synchronized (mPackages) {
4526            final int count = candidates.size();
4527            // First, try to use the domain preferred app. Partition the candidates into four lists:
4528            // one for the final results, one for the "do not use ever", one for "undefined status"
4529            // and finally one for "Browser App type".
4530            for (int n=0; n<count; n++) {
4531                ResolveInfo info = candidates.get(n);
4532                String packageName = info.activityInfo.packageName;
4533                PackageSetting ps = mSettings.mPackages.get(packageName);
4534                if (ps != null) {
4535                    // Add to the special match all list (Browser use case)
4536                    if (info.handleAllWebDataURI) {
4537                        matchAllList.add(info);
4538                        continue;
4539                    }
4540                    // Try to get the status from User settings first
4541                    int status = getDomainVerificationStatusLPr(ps, userId);
4542                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4543                        alwaysList.add(info);
4544                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4545                        neverList.add(info);
4546                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4547                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4548                        undefinedList.add(info);
4549                    }
4550                }
4551            }
4552            // First try to add the "always" resolution for the current user if there is any
4553            if (alwaysList.size() > 0) {
4554                result.addAll(alwaysList);
4555            // if there is an "always" for the parent user, add it.
4556            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4557                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4558                result.add(xpDomainInfo.resolveInfo);
4559            } else {
4560                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4561                result.addAll(undefinedList);
4562                if (xpDomainInfo != null && (
4563                        xpDomainInfo.bestDomainVerificationStatus
4564                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4565                        || xpDomainInfo.bestDomainVerificationStatus
4566                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4567                    result.add(xpDomainInfo.resolveInfo);
4568                }
4569                // Also add Browsers (all of them or only the default one)
4570                if ((flags & MATCH_ALL) != 0) {
4571                    result.addAll(matchAllList);
4572                } else {
4573                    // Try to add the Default Browser if we can
4574                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4575                            UserHandle.myUserId());
4576                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4577                        boolean defaultBrowserFound = false;
4578                        final int browserCount = matchAllList.size();
4579                        for (int n=0; n<browserCount; n++) {
4580                            ResolveInfo browser = matchAllList.get(n);
4581                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4582                                result.add(browser);
4583                                defaultBrowserFound = true;
4584                                break;
4585                            }
4586                        }
4587                        if (!defaultBrowserFound) {
4588                            result.addAll(matchAllList);
4589                        }
4590                    } else {
4591                        result.addAll(matchAllList);
4592                    }
4593                }
4594
4595                // If there is nothing selected, add all candidates and remove the ones that the User
4596                // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4597                if (result.size() == 0) {
4598                    result.addAll(candidates);
4599                    result.removeAll(neverList);
4600                }
4601            }
4602        }
4603        if (DEBUG_PREFERRED) {
4604            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4605                    result.size());
4606        }
4607        return result;
4608    }
4609
4610    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4611        int status = ps.getDomainVerificationStatusForUser(userId);
4612        // if none available, get the master status
4613        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4614            if (ps.getIntentFilterVerificationInfo() != null) {
4615                status = ps.getIntentFilterVerificationInfo().getStatus();
4616            }
4617        }
4618        return status;
4619    }
4620
4621    private ResolveInfo querySkipCurrentProfileIntents(
4622            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4623            int flags, int sourceUserId) {
4624        if (matchingFilters != null) {
4625            int size = matchingFilters.size();
4626            for (int i = 0; i < size; i ++) {
4627                CrossProfileIntentFilter filter = matchingFilters.get(i);
4628                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4629                    // Checking if there are activities in the target user that can handle the
4630                    // intent.
4631                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4632                            flags, sourceUserId);
4633                    if (resolveInfo != null) {
4634                        return resolveInfo;
4635                    }
4636                }
4637            }
4638        }
4639        return null;
4640    }
4641
4642    // Return matching ResolveInfo if any for skip current profile intent filters.
4643    private ResolveInfo queryCrossProfileIntents(
4644            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4645            int flags, int sourceUserId) {
4646        if (matchingFilters != null) {
4647            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4648            // match the same intent. For performance reasons, it is better not to
4649            // run queryIntent twice for the same userId
4650            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4651            int size = matchingFilters.size();
4652            for (int i = 0; i < size; i++) {
4653                CrossProfileIntentFilter filter = matchingFilters.get(i);
4654                int targetUserId = filter.getTargetUserId();
4655                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4656                        && !alreadyTriedUserIds.get(targetUserId)) {
4657                    // Checking if there are activities in the target user that can handle the
4658                    // intent.
4659                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4660                            flags, sourceUserId);
4661                    if (resolveInfo != null) return resolveInfo;
4662                    alreadyTriedUserIds.put(targetUserId, true);
4663                }
4664            }
4665        }
4666        return null;
4667    }
4668
4669    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4670            String resolvedType, int flags, int sourceUserId) {
4671        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4672                resolvedType, flags, filter.getTargetUserId());
4673        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4674            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4675        }
4676        return null;
4677    }
4678
4679    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4680            int sourceUserId, int targetUserId) {
4681        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4682        String className;
4683        if (targetUserId == UserHandle.USER_OWNER) {
4684            className = FORWARD_INTENT_TO_USER_OWNER;
4685        } else {
4686            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4687        }
4688        ComponentName forwardingActivityComponentName = new ComponentName(
4689                mAndroidApplication.packageName, className);
4690        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4691                sourceUserId);
4692        if (targetUserId == UserHandle.USER_OWNER) {
4693            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4694            forwardingResolveInfo.noResourceId = true;
4695        }
4696        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4697        forwardingResolveInfo.priority = 0;
4698        forwardingResolveInfo.preferredOrder = 0;
4699        forwardingResolveInfo.match = 0;
4700        forwardingResolveInfo.isDefault = true;
4701        forwardingResolveInfo.filter = filter;
4702        forwardingResolveInfo.targetUserId = targetUserId;
4703        return forwardingResolveInfo;
4704    }
4705
4706    @Override
4707    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4708            Intent[] specifics, String[] specificTypes, Intent intent,
4709            String resolvedType, int flags, int userId) {
4710        if (!sUserManager.exists(userId)) return Collections.emptyList();
4711        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4712                false, "query intent activity options");
4713        final String resultsAction = intent.getAction();
4714
4715        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4716                | PackageManager.GET_RESOLVED_FILTER, userId);
4717
4718        if (DEBUG_INTENT_MATCHING) {
4719            Log.v(TAG, "Query " + intent + ": " + results);
4720        }
4721
4722        int specificsPos = 0;
4723        int N;
4724
4725        // todo: note that the algorithm used here is O(N^2).  This
4726        // isn't a problem in our current environment, but if we start running
4727        // into situations where we have more than 5 or 10 matches then this
4728        // should probably be changed to something smarter...
4729
4730        // First we go through and resolve each of the specific items
4731        // that were supplied, taking care of removing any corresponding
4732        // duplicate items in the generic resolve list.
4733        if (specifics != null) {
4734            for (int i=0; i<specifics.length; i++) {
4735                final Intent sintent = specifics[i];
4736                if (sintent == null) {
4737                    continue;
4738                }
4739
4740                if (DEBUG_INTENT_MATCHING) {
4741                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4742                }
4743
4744                String action = sintent.getAction();
4745                if (resultsAction != null && resultsAction.equals(action)) {
4746                    // If this action was explicitly requested, then don't
4747                    // remove things that have it.
4748                    action = null;
4749                }
4750
4751                ResolveInfo ri = null;
4752                ActivityInfo ai = null;
4753
4754                ComponentName comp = sintent.getComponent();
4755                if (comp == null) {
4756                    ri = resolveIntent(
4757                        sintent,
4758                        specificTypes != null ? specificTypes[i] : null,
4759                            flags, userId);
4760                    if (ri == null) {
4761                        continue;
4762                    }
4763                    if (ri == mResolveInfo) {
4764                        // ACK!  Must do something better with this.
4765                    }
4766                    ai = ri.activityInfo;
4767                    comp = new ComponentName(ai.applicationInfo.packageName,
4768                            ai.name);
4769                } else {
4770                    ai = getActivityInfo(comp, flags, userId);
4771                    if (ai == null) {
4772                        continue;
4773                    }
4774                }
4775
4776                // Look for any generic query activities that are duplicates
4777                // of this specific one, and remove them from the results.
4778                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4779                N = results.size();
4780                int j;
4781                for (j=specificsPos; j<N; j++) {
4782                    ResolveInfo sri = results.get(j);
4783                    if ((sri.activityInfo.name.equals(comp.getClassName())
4784                            && sri.activityInfo.applicationInfo.packageName.equals(
4785                                    comp.getPackageName()))
4786                        || (action != null && sri.filter.matchAction(action))) {
4787                        results.remove(j);
4788                        if (DEBUG_INTENT_MATCHING) Log.v(
4789                            TAG, "Removing duplicate item from " + j
4790                            + " due to specific " + specificsPos);
4791                        if (ri == null) {
4792                            ri = sri;
4793                        }
4794                        j--;
4795                        N--;
4796                    }
4797                }
4798
4799                // Add this specific item to its proper place.
4800                if (ri == null) {
4801                    ri = new ResolveInfo();
4802                    ri.activityInfo = ai;
4803                }
4804                results.add(specificsPos, ri);
4805                ri.specificIndex = i;
4806                specificsPos++;
4807            }
4808        }
4809
4810        // Now we go through the remaining generic results and remove any
4811        // duplicate actions that are found here.
4812        N = results.size();
4813        for (int i=specificsPos; i<N-1; i++) {
4814            final ResolveInfo rii = results.get(i);
4815            if (rii.filter == null) {
4816                continue;
4817            }
4818
4819            // Iterate over all of the actions of this result's intent
4820            // filter...  typically this should be just one.
4821            final Iterator<String> it = rii.filter.actionsIterator();
4822            if (it == null) {
4823                continue;
4824            }
4825            while (it.hasNext()) {
4826                final String action = it.next();
4827                if (resultsAction != null && resultsAction.equals(action)) {
4828                    // If this action was explicitly requested, then don't
4829                    // remove things that have it.
4830                    continue;
4831                }
4832                for (int j=i+1; j<N; j++) {
4833                    final ResolveInfo rij = results.get(j);
4834                    if (rij.filter != null && rij.filter.hasAction(action)) {
4835                        results.remove(j);
4836                        if (DEBUG_INTENT_MATCHING) Log.v(
4837                            TAG, "Removing duplicate item from " + j
4838                            + " due to action " + action + " at " + i);
4839                        j--;
4840                        N--;
4841                    }
4842                }
4843            }
4844
4845            // If the caller didn't request filter information, drop it now
4846            // so we don't have to marshall/unmarshall it.
4847            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4848                rii.filter = null;
4849            }
4850        }
4851
4852        // Filter out the caller activity if so requested.
4853        if (caller != null) {
4854            N = results.size();
4855            for (int i=0; i<N; i++) {
4856                ActivityInfo ainfo = results.get(i).activityInfo;
4857                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4858                        && caller.getClassName().equals(ainfo.name)) {
4859                    results.remove(i);
4860                    break;
4861                }
4862            }
4863        }
4864
4865        // If the caller didn't request filter information,
4866        // drop them now so we don't have to
4867        // marshall/unmarshall it.
4868        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4869            N = results.size();
4870            for (int i=0; i<N; i++) {
4871                results.get(i).filter = null;
4872            }
4873        }
4874
4875        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4876        return results;
4877    }
4878
4879    @Override
4880    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4881            int userId) {
4882        if (!sUserManager.exists(userId)) return Collections.emptyList();
4883        ComponentName comp = intent.getComponent();
4884        if (comp == null) {
4885            if (intent.getSelector() != null) {
4886                intent = intent.getSelector();
4887                comp = intent.getComponent();
4888            }
4889        }
4890        if (comp != null) {
4891            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4892            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4893            if (ai != null) {
4894                ResolveInfo ri = new ResolveInfo();
4895                ri.activityInfo = ai;
4896                list.add(ri);
4897            }
4898            return list;
4899        }
4900
4901        // reader
4902        synchronized (mPackages) {
4903            String pkgName = intent.getPackage();
4904            if (pkgName == null) {
4905                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4906            }
4907            final PackageParser.Package pkg = mPackages.get(pkgName);
4908            if (pkg != null) {
4909                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4910                        userId);
4911            }
4912            return null;
4913        }
4914    }
4915
4916    @Override
4917    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4918        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4919        if (!sUserManager.exists(userId)) return null;
4920        if (query != null) {
4921            if (query.size() >= 1) {
4922                // If there is more than one service with the same priority,
4923                // just arbitrarily pick the first one.
4924                return query.get(0);
4925            }
4926        }
4927        return null;
4928    }
4929
4930    @Override
4931    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4932            int userId) {
4933        if (!sUserManager.exists(userId)) return Collections.emptyList();
4934        ComponentName comp = intent.getComponent();
4935        if (comp == null) {
4936            if (intent.getSelector() != null) {
4937                intent = intent.getSelector();
4938                comp = intent.getComponent();
4939            }
4940        }
4941        if (comp != null) {
4942            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4943            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4944            if (si != null) {
4945                final ResolveInfo ri = new ResolveInfo();
4946                ri.serviceInfo = si;
4947                list.add(ri);
4948            }
4949            return list;
4950        }
4951
4952        // reader
4953        synchronized (mPackages) {
4954            String pkgName = intent.getPackage();
4955            if (pkgName == null) {
4956                return mServices.queryIntent(intent, resolvedType, flags, userId);
4957            }
4958            final PackageParser.Package pkg = mPackages.get(pkgName);
4959            if (pkg != null) {
4960                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4961                        userId);
4962            }
4963            return null;
4964        }
4965    }
4966
4967    @Override
4968    public List<ResolveInfo> queryIntentContentProviders(
4969            Intent intent, String resolvedType, int flags, int userId) {
4970        if (!sUserManager.exists(userId)) return Collections.emptyList();
4971        ComponentName comp = intent.getComponent();
4972        if (comp == null) {
4973            if (intent.getSelector() != null) {
4974                intent = intent.getSelector();
4975                comp = intent.getComponent();
4976            }
4977        }
4978        if (comp != null) {
4979            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4980            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4981            if (pi != null) {
4982                final ResolveInfo ri = new ResolveInfo();
4983                ri.providerInfo = pi;
4984                list.add(ri);
4985            }
4986            return list;
4987        }
4988
4989        // reader
4990        synchronized (mPackages) {
4991            String pkgName = intent.getPackage();
4992            if (pkgName == null) {
4993                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4994            }
4995            final PackageParser.Package pkg = mPackages.get(pkgName);
4996            if (pkg != null) {
4997                return mProviders.queryIntentForPackage(
4998                        intent, resolvedType, flags, pkg.providers, userId);
4999            }
5000            return null;
5001        }
5002    }
5003
5004    @Override
5005    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5006        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5007
5008        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5009
5010        // writer
5011        synchronized (mPackages) {
5012            ArrayList<PackageInfo> list;
5013            if (listUninstalled) {
5014                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5015                for (PackageSetting ps : mSettings.mPackages.values()) {
5016                    PackageInfo pi;
5017                    if (ps.pkg != null) {
5018                        pi = generatePackageInfo(ps.pkg, flags, userId);
5019                    } else {
5020                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5021                    }
5022                    if (pi != null) {
5023                        list.add(pi);
5024                    }
5025                }
5026            } else {
5027                list = new ArrayList<PackageInfo>(mPackages.size());
5028                for (PackageParser.Package p : mPackages.values()) {
5029                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5030                    if (pi != null) {
5031                        list.add(pi);
5032                    }
5033                }
5034            }
5035
5036            return new ParceledListSlice<PackageInfo>(list);
5037        }
5038    }
5039
5040    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5041            String[] permissions, boolean[] tmp, int flags, int userId) {
5042        int numMatch = 0;
5043        final PermissionsState permissionsState = ps.getPermissionsState();
5044        for (int i=0; i<permissions.length; i++) {
5045            final String permission = permissions[i];
5046            if (permissionsState.hasPermission(permission, userId)) {
5047                tmp[i] = true;
5048                numMatch++;
5049            } else {
5050                tmp[i] = false;
5051            }
5052        }
5053        if (numMatch == 0) {
5054            return;
5055        }
5056        PackageInfo pi;
5057        if (ps.pkg != null) {
5058            pi = generatePackageInfo(ps.pkg, flags, userId);
5059        } else {
5060            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5061        }
5062        // The above might return null in cases of uninstalled apps or install-state
5063        // skew across users/profiles.
5064        if (pi != null) {
5065            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5066                if (numMatch == permissions.length) {
5067                    pi.requestedPermissions = permissions;
5068                } else {
5069                    pi.requestedPermissions = new String[numMatch];
5070                    numMatch = 0;
5071                    for (int i=0; i<permissions.length; i++) {
5072                        if (tmp[i]) {
5073                            pi.requestedPermissions[numMatch] = permissions[i];
5074                            numMatch++;
5075                        }
5076                    }
5077                }
5078            }
5079            list.add(pi);
5080        }
5081    }
5082
5083    @Override
5084    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5085            String[] permissions, int flags, int userId) {
5086        if (!sUserManager.exists(userId)) return null;
5087        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5088
5089        // writer
5090        synchronized (mPackages) {
5091            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5092            boolean[] tmpBools = new boolean[permissions.length];
5093            if (listUninstalled) {
5094                for (PackageSetting ps : mSettings.mPackages.values()) {
5095                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5096                }
5097            } else {
5098                for (PackageParser.Package pkg : mPackages.values()) {
5099                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5100                    if (ps != null) {
5101                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5102                                userId);
5103                    }
5104                }
5105            }
5106
5107            return new ParceledListSlice<PackageInfo>(list);
5108        }
5109    }
5110
5111    @Override
5112    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5113        if (!sUserManager.exists(userId)) return null;
5114        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5115
5116        // writer
5117        synchronized (mPackages) {
5118            ArrayList<ApplicationInfo> list;
5119            if (listUninstalled) {
5120                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5121                for (PackageSetting ps : mSettings.mPackages.values()) {
5122                    ApplicationInfo ai;
5123                    if (ps.pkg != null) {
5124                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5125                                ps.readUserState(userId), userId);
5126                    } else {
5127                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5128                    }
5129                    if (ai != null) {
5130                        list.add(ai);
5131                    }
5132                }
5133            } else {
5134                list = new ArrayList<ApplicationInfo>(mPackages.size());
5135                for (PackageParser.Package p : mPackages.values()) {
5136                    if (p.mExtras != null) {
5137                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5138                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5139                        if (ai != null) {
5140                            list.add(ai);
5141                        }
5142                    }
5143                }
5144            }
5145
5146            return new ParceledListSlice<ApplicationInfo>(list);
5147        }
5148    }
5149
5150    public List<ApplicationInfo> getPersistentApplications(int flags) {
5151        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5152
5153        // reader
5154        synchronized (mPackages) {
5155            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5156            final int userId = UserHandle.getCallingUserId();
5157            while (i.hasNext()) {
5158                final PackageParser.Package p = i.next();
5159                if (p.applicationInfo != null
5160                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5161                        && (!mSafeMode || isSystemApp(p))) {
5162                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5163                    if (ps != null) {
5164                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5165                                ps.readUserState(userId), userId);
5166                        if (ai != null) {
5167                            finalList.add(ai);
5168                        }
5169                    }
5170                }
5171            }
5172        }
5173
5174        return finalList;
5175    }
5176
5177    @Override
5178    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5179        if (!sUserManager.exists(userId)) return null;
5180        // reader
5181        synchronized (mPackages) {
5182            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5183            PackageSetting ps = provider != null
5184                    ? mSettings.mPackages.get(provider.owner.packageName)
5185                    : null;
5186            return ps != null
5187                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5188                    && (!mSafeMode || (provider.info.applicationInfo.flags
5189                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5190                    ? PackageParser.generateProviderInfo(provider, flags,
5191                            ps.readUserState(userId), userId)
5192                    : null;
5193        }
5194    }
5195
5196    /**
5197     * @deprecated
5198     */
5199    @Deprecated
5200    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5201        // reader
5202        synchronized (mPackages) {
5203            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5204                    .entrySet().iterator();
5205            final int userId = UserHandle.getCallingUserId();
5206            while (i.hasNext()) {
5207                Map.Entry<String, PackageParser.Provider> entry = i.next();
5208                PackageParser.Provider p = entry.getValue();
5209                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5210
5211                if (ps != null && p.syncable
5212                        && (!mSafeMode || (p.info.applicationInfo.flags
5213                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5214                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5215                            ps.readUserState(userId), userId);
5216                    if (info != null) {
5217                        outNames.add(entry.getKey());
5218                        outInfo.add(info);
5219                    }
5220                }
5221            }
5222        }
5223    }
5224
5225    @Override
5226    public List<ProviderInfo> queryContentProviders(String processName,
5227            int uid, int flags) {
5228        ArrayList<ProviderInfo> finalList = null;
5229        // reader
5230        synchronized (mPackages) {
5231            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5232            final int userId = processName != null ?
5233                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5234            while (i.hasNext()) {
5235                final PackageParser.Provider p = i.next();
5236                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5237                if (ps != null && p.info.authority != null
5238                        && (processName == null
5239                                || (p.info.processName.equals(processName)
5240                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5241                        && mSettings.isEnabledLPr(p.info, flags, userId)
5242                        && (!mSafeMode
5243                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5244                    if (finalList == null) {
5245                        finalList = new ArrayList<ProviderInfo>(3);
5246                    }
5247                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5248                            ps.readUserState(userId), userId);
5249                    if (info != null) {
5250                        finalList.add(info);
5251                    }
5252                }
5253            }
5254        }
5255
5256        if (finalList != null) {
5257            Collections.sort(finalList, mProviderInitOrderSorter);
5258        }
5259
5260        return finalList;
5261    }
5262
5263    @Override
5264    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5265            int flags) {
5266        // reader
5267        synchronized (mPackages) {
5268            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5269            return PackageParser.generateInstrumentationInfo(i, flags);
5270        }
5271    }
5272
5273    @Override
5274    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5275            int flags) {
5276        ArrayList<InstrumentationInfo> finalList =
5277            new ArrayList<InstrumentationInfo>();
5278
5279        // reader
5280        synchronized (mPackages) {
5281            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5282            while (i.hasNext()) {
5283                final PackageParser.Instrumentation p = i.next();
5284                if (targetPackage == null
5285                        || targetPackage.equals(p.info.targetPackage)) {
5286                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5287                            flags);
5288                    if (ii != null) {
5289                        finalList.add(ii);
5290                    }
5291                }
5292            }
5293        }
5294
5295        return finalList;
5296    }
5297
5298    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5299        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5300        if (overlays == null) {
5301            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5302            return;
5303        }
5304        for (PackageParser.Package opkg : overlays.values()) {
5305            // Not much to do if idmap fails: we already logged the error
5306            // and we certainly don't want to abort installation of pkg simply
5307            // because an overlay didn't fit properly. For these reasons,
5308            // ignore the return value of createIdmapForPackagePairLI.
5309            createIdmapForPackagePairLI(pkg, opkg);
5310        }
5311    }
5312
5313    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5314            PackageParser.Package opkg) {
5315        if (!opkg.mTrustedOverlay) {
5316            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5317                    opkg.baseCodePath + ": overlay not trusted");
5318            return false;
5319        }
5320        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5321        if (overlaySet == null) {
5322            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5323                    opkg.baseCodePath + " but target package has no known overlays");
5324            return false;
5325        }
5326        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5327        // TODO: generate idmap for split APKs
5328        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5329            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5330                    + opkg.baseCodePath);
5331            return false;
5332        }
5333        PackageParser.Package[] overlayArray =
5334            overlaySet.values().toArray(new PackageParser.Package[0]);
5335        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5336            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5337                return p1.mOverlayPriority - p2.mOverlayPriority;
5338            }
5339        };
5340        Arrays.sort(overlayArray, cmp);
5341
5342        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5343        int i = 0;
5344        for (PackageParser.Package p : overlayArray) {
5345            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5346        }
5347        return true;
5348    }
5349
5350    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5351        final File[] files = dir.listFiles();
5352        if (ArrayUtils.isEmpty(files)) {
5353            Log.d(TAG, "No files in app dir " + dir);
5354            return;
5355        }
5356
5357        if (DEBUG_PACKAGE_SCANNING) {
5358            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5359                    + " flags=0x" + Integer.toHexString(parseFlags));
5360        }
5361
5362        for (File file : files) {
5363            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5364                    && !PackageInstallerService.isStageName(file.getName());
5365            if (!isPackage) {
5366                // Ignore entries which are not packages
5367                continue;
5368            }
5369            try {
5370                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5371                        scanFlags, currentTime, null);
5372            } catch (PackageManagerException e) {
5373                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5374
5375                // Delete invalid userdata apps
5376                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5377                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5378                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5379                    if (file.isDirectory()) {
5380                        mInstaller.rmPackageDir(file.getAbsolutePath());
5381                    } else {
5382                        file.delete();
5383                    }
5384                }
5385            }
5386        }
5387    }
5388
5389    private static File getSettingsProblemFile() {
5390        File dataDir = Environment.getDataDirectory();
5391        File systemDir = new File(dataDir, "system");
5392        File fname = new File(systemDir, "uiderrors.txt");
5393        return fname;
5394    }
5395
5396    static void reportSettingsProblem(int priority, String msg) {
5397        logCriticalInfo(priority, msg);
5398    }
5399
5400    static void logCriticalInfo(int priority, String msg) {
5401        Slog.println(priority, TAG, msg);
5402        EventLogTags.writePmCriticalInfo(msg);
5403        try {
5404            File fname = getSettingsProblemFile();
5405            FileOutputStream out = new FileOutputStream(fname, true);
5406            PrintWriter pw = new FastPrintWriter(out);
5407            SimpleDateFormat formatter = new SimpleDateFormat();
5408            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5409            pw.println(dateString + ": " + msg);
5410            pw.close();
5411            FileUtils.setPermissions(
5412                    fname.toString(),
5413                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5414                    -1, -1);
5415        } catch (java.io.IOException e) {
5416        }
5417    }
5418
5419    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5420            PackageParser.Package pkg, File srcFile, int parseFlags)
5421            throws PackageManagerException {
5422        if (ps != null
5423                && ps.codePath.equals(srcFile)
5424                && ps.timeStamp == srcFile.lastModified()
5425                && !isCompatSignatureUpdateNeeded(pkg)
5426                && !isRecoverSignatureUpdateNeeded(pkg)) {
5427            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5428            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5429            ArraySet<PublicKey> signingKs;
5430            synchronized (mPackages) {
5431                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5432            }
5433            if (ps.signatures.mSignatures != null
5434                    && ps.signatures.mSignatures.length != 0
5435                    && signingKs != null) {
5436                // Optimization: reuse the existing cached certificates
5437                // if the package appears to be unchanged.
5438                pkg.mSignatures = ps.signatures.mSignatures;
5439                pkg.mSigningKeys = signingKs;
5440                return;
5441            }
5442
5443            Slog.w(TAG, "PackageSetting for " + ps.name
5444                    + " is missing signatures.  Collecting certs again to recover them.");
5445        } else {
5446            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5447        }
5448
5449        try {
5450            pp.collectCertificates(pkg, parseFlags);
5451            pp.collectManifestDigest(pkg);
5452        } catch (PackageParserException e) {
5453            throw PackageManagerException.from(e);
5454        }
5455    }
5456
5457    /*
5458     *  Scan a package and return the newly parsed package.
5459     *  Returns null in case of errors and the error code is stored in mLastScanError
5460     */
5461    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5462            long currentTime, UserHandle user) throws PackageManagerException {
5463        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5464        parseFlags |= mDefParseFlags;
5465        PackageParser pp = new PackageParser();
5466        pp.setSeparateProcesses(mSeparateProcesses);
5467        pp.setOnlyCoreApps(mOnlyCore);
5468        pp.setDisplayMetrics(mMetrics);
5469
5470        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5471            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5472        }
5473
5474        final PackageParser.Package pkg;
5475        try {
5476            pkg = pp.parsePackage(scanFile, parseFlags);
5477        } catch (PackageParserException e) {
5478            throw PackageManagerException.from(e);
5479        }
5480
5481        PackageSetting ps = null;
5482        PackageSetting updatedPkg;
5483        // reader
5484        synchronized (mPackages) {
5485            // Look to see if we already know about this package.
5486            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5487            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5488                // This package has been renamed to its original name.  Let's
5489                // use that.
5490                ps = mSettings.peekPackageLPr(oldName);
5491            }
5492            // If there was no original package, see one for the real package name.
5493            if (ps == null) {
5494                ps = mSettings.peekPackageLPr(pkg.packageName);
5495            }
5496            // Check to see if this package could be hiding/updating a system
5497            // package.  Must look for it either under the original or real
5498            // package name depending on our state.
5499            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5500            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5501        }
5502        boolean updatedPkgBetter = false;
5503        // First check if this is a system package that may involve an update
5504        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5505            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5506            // it needs to drop FLAG_PRIVILEGED.
5507            if (locationIsPrivileged(scanFile)) {
5508                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5509            } else {
5510                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5511            }
5512
5513            if (ps != null && !ps.codePath.equals(scanFile)) {
5514                // The path has changed from what was last scanned...  check the
5515                // version of the new path against what we have stored to determine
5516                // what to do.
5517                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5518                if (pkg.mVersionCode <= ps.versionCode) {
5519                    // The system package has been updated and the code path does not match
5520                    // Ignore entry. Skip it.
5521                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5522                            + " ignored: updated version " + ps.versionCode
5523                            + " better than this " + pkg.mVersionCode);
5524                    if (!updatedPkg.codePath.equals(scanFile)) {
5525                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5526                                + ps.name + " changing from " + updatedPkg.codePathString
5527                                + " to " + scanFile);
5528                        updatedPkg.codePath = scanFile;
5529                        updatedPkg.codePathString = scanFile.toString();
5530                        updatedPkg.resourcePath = scanFile;
5531                        updatedPkg.resourcePathString = scanFile.toString();
5532                    }
5533                    updatedPkg.pkg = pkg;
5534                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5535                } else {
5536                    // The current app on the system partition is better than
5537                    // what we have updated to on the data partition; switch
5538                    // back to the system partition version.
5539                    // At this point, its safely assumed that package installation for
5540                    // apps in system partition will go through. If not there won't be a working
5541                    // version of the app
5542                    // writer
5543                    synchronized (mPackages) {
5544                        // Just remove the loaded entries from package lists.
5545                        mPackages.remove(ps.name);
5546                    }
5547
5548                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5549                            + " reverting from " + ps.codePathString
5550                            + ": new version " + pkg.mVersionCode
5551                            + " better than installed " + ps.versionCode);
5552
5553                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5554                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5555                    synchronized (mInstallLock) {
5556                        args.cleanUpResourcesLI();
5557                    }
5558                    synchronized (mPackages) {
5559                        mSettings.enableSystemPackageLPw(ps.name);
5560                    }
5561                    updatedPkgBetter = true;
5562                }
5563            }
5564        }
5565
5566        if (updatedPkg != null) {
5567            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5568            // initially
5569            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5570
5571            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5572            // flag set initially
5573            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5574                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5575            }
5576        }
5577
5578        // Verify certificates against what was last scanned
5579        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5580
5581        /*
5582         * A new system app appeared, but we already had a non-system one of the
5583         * same name installed earlier.
5584         */
5585        boolean shouldHideSystemApp = false;
5586        if (updatedPkg == null && ps != null
5587                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5588            /*
5589             * Check to make sure the signatures match first. If they don't,
5590             * wipe the installed application and its data.
5591             */
5592            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5593                    != PackageManager.SIGNATURE_MATCH) {
5594                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5595                        + " signatures don't match existing userdata copy; removing");
5596                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5597                ps = null;
5598            } else {
5599                /*
5600                 * If the newly-added system app is an older version than the
5601                 * already installed version, hide it. It will be scanned later
5602                 * and re-added like an update.
5603                 */
5604                if (pkg.mVersionCode <= ps.versionCode) {
5605                    shouldHideSystemApp = true;
5606                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5607                            + " but new version " + pkg.mVersionCode + " better than installed "
5608                            + ps.versionCode + "; hiding system");
5609                } else {
5610                    /*
5611                     * The newly found system app is a newer version that the
5612                     * one previously installed. Simply remove the
5613                     * already-installed application and replace it with our own
5614                     * while keeping the application data.
5615                     */
5616                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5617                            + " reverting from " + ps.codePathString + ": new version "
5618                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5619                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5620                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5621                    synchronized (mInstallLock) {
5622                        args.cleanUpResourcesLI();
5623                    }
5624                }
5625            }
5626        }
5627
5628        // The apk is forward locked (not public) if its code and resources
5629        // are kept in different files. (except for app in either system or
5630        // vendor path).
5631        // TODO grab this value from PackageSettings
5632        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5633            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5634                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5635            }
5636        }
5637
5638        // TODO: extend to support forward-locked splits
5639        String resourcePath = null;
5640        String baseResourcePath = null;
5641        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5642            if (ps != null && ps.resourcePathString != null) {
5643                resourcePath = ps.resourcePathString;
5644                baseResourcePath = ps.resourcePathString;
5645            } else {
5646                // Should not happen at all. Just log an error.
5647                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5648            }
5649        } else {
5650            resourcePath = pkg.codePath;
5651            baseResourcePath = pkg.baseCodePath;
5652        }
5653
5654        // Set application objects path explicitly.
5655        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5656        pkg.applicationInfo.setCodePath(pkg.codePath);
5657        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5658        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5659        pkg.applicationInfo.setResourcePath(resourcePath);
5660        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5661        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5662
5663        // Note that we invoke the following method only if we are about to unpack an application
5664        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5665                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5666
5667        /*
5668         * If the system app should be overridden by a previously installed
5669         * data, hide the system app now and let the /data/app scan pick it up
5670         * again.
5671         */
5672        if (shouldHideSystemApp) {
5673            synchronized (mPackages) {
5674                /*
5675                 * We have to grant systems permissions before we hide, because
5676                 * grantPermissions will assume the package update is trying to
5677                 * expand its permissions.
5678                 */
5679                grantPermissionsLPw(pkg, true, pkg.packageName);
5680                mSettings.disableSystemPackageLPw(pkg.packageName);
5681            }
5682        }
5683
5684        return scannedPkg;
5685    }
5686
5687    private static String fixProcessName(String defProcessName,
5688            String processName, int uid) {
5689        if (processName == null) {
5690            return defProcessName;
5691        }
5692        return processName;
5693    }
5694
5695    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5696            throws PackageManagerException {
5697        if (pkgSetting.signatures.mSignatures != null) {
5698            // Already existing package. Make sure signatures match
5699            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5700                    == PackageManager.SIGNATURE_MATCH;
5701            if (!match) {
5702                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5703                        == PackageManager.SIGNATURE_MATCH;
5704            }
5705            if (!match) {
5706                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5707                        == PackageManager.SIGNATURE_MATCH;
5708            }
5709            if (!match) {
5710                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5711                        + pkg.packageName + " signatures do not match the "
5712                        + "previously installed version; ignoring!");
5713            }
5714        }
5715
5716        // Check for shared user signatures
5717        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5718            // Already existing package. Make sure signatures match
5719            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5720                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5721            if (!match) {
5722                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5723                        == PackageManager.SIGNATURE_MATCH;
5724            }
5725            if (!match) {
5726                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5727                        == PackageManager.SIGNATURE_MATCH;
5728            }
5729            if (!match) {
5730                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5731                        "Package " + pkg.packageName
5732                        + " has no signatures that match those in shared user "
5733                        + pkgSetting.sharedUser.name + "; ignoring!");
5734            }
5735        }
5736    }
5737
5738    /**
5739     * Enforces that only the system UID or root's UID can call a method exposed
5740     * via Binder.
5741     *
5742     * @param message used as message if SecurityException is thrown
5743     * @throws SecurityException if the caller is not system or root
5744     */
5745    private static final void enforceSystemOrRoot(String message) {
5746        final int uid = Binder.getCallingUid();
5747        if (uid != Process.SYSTEM_UID && uid != 0) {
5748            throw new SecurityException(message);
5749        }
5750    }
5751
5752    @Override
5753    public void performBootDexOpt() {
5754        enforceSystemOrRoot("Only the system can request dexopt be performed");
5755
5756        // Before everything else, see whether we need to fstrim.
5757        try {
5758            IMountService ms = PackageHelper.getMountService();
5759            if (ms != null) {
5760                final boolean isUpgrade = isUpgrade();
5761                boolean doTrim = isUpgrade;
5762                if (doTrim) {
5763                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5764                } else {
5765                    final long interval = android.provider.Settings.Global.getLong(
5766                            mContext.getContentResolver(),
5767                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5768                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5769                    if (interval > 0) {
5770                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5771                        if (timeSinceLast > interval) {
5772                            doTrim = true;
5773                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5774                                    + "; running immediately");
5775                        }
5776                    }
5777                }
5778                if (doTrim) {
5779                    if (!isFirstBoot()) {
5780                        try {
5781                            ActivityManagerNative.getDefault().showBootMessage(
5782                                    mContext.getResources().getString(
5783                                            R.string.android_upgrading_fstrim), true);
5784                        } catch (RemoteException e) {
5785                        }
5786                    }
5787                    ms.runMaintenance();
5788                }
5789            } else {
5790                Slog.e(TAG, "Mount service unavailable!");
5791            }
5792        } catch (RemoteException e) {
5793            // Can't happen; MountService is local
5794        }
5795
5796        final ArraySet<PackageParser.Package> pkgs;
5797        synchronized (mPackages) {
5798            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5799        }
5800
5801        if (pkgs != null) {
5802            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5803            // in case the device runs out of space.
5804            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5805            // Give priority to core apps.
5806            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5807                PackageParser.Package pkg = it.next();
5808                if (pkg.coreApp) {
5809                    if (DEBUG_DEXOPT) {
5810                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5811                    }
5812                    sortedPkgs.add(pkg);
5813                    it.remove();
5814                }
5815            }
5816            // Give priority to system apps that listen for pre boot complete.
5817            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5818            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5819            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5820                PackageParser.Package pkg = it.next();
5821                if (pkgNames.contains(pkg.packageName)) {
5822                    if (DEBUG_DEXOPT) {
5823                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5824                    }
5825                    sortedPkgs.add(pkg);
5826                    it.remove();
5827                }
5828            }
5829            // Give priority to system apps.
5830            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5831                PackageParser.Package pkg = it.next();
5832                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5833                    if (DEBUG_DEXOPT) {
5834                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5835                    }
5836                    sortedPkgs.add(pkg);
5837                    it.remove();
5838                }
5839            }
5840            // Give priority to updated system apps.
5841            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5842                PackageParser.Package pkg = it.next();
5843                if (pkg.isUpdatedSystemApp()) {
5844                    if (DEBUG_DEXOPT) {
5845                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5846                    }
5847                    sortedPkgs.add(pkg);
5848                    it.remove();
5849                }
5850            }
5851            // Give priority to apps that listen for boot complete.
5852            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5853            pkgNames = getPackageNamesForIntent(intent);
5854            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5855                PackageParser.Package pkg = it.next();
5856                if (pkgNames.contains(pkg.packageName)) {
5857                    if (DEBUG_DEXOPT) {
5858                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5859                    }
5860                    sortedPkgs.add(pkg);
5861                    it.remove();
5862                }
5863            }
5864            // Filter out packages that aren't recently used.
5865            filterRecentlyUsedApps(pkgs);
5866            // Add all remaining apps.
5867            for (PackageParser.Package pkg : pkgs) {
5868                if (DEBUG_DEXOPT) {
5869                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5870                }
5871                sortedPkgs.add(pkg);
5872            }
5873
5874            // If we want to be lazy, filter everything that wasn't recently used.
5875            if (mLazyDexOpt) {
5876                filterRecentlyUsedApps(sortedPkgs);
5877            }
5878
5879            int i = 0;
5880            int total = sortedPkgs.size();
5881            File dataDir = Environment.getDataDirectory();
5882            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5883            if (lowThreshold == 0) {
5884                throw new IllegalStateException("Invalid low memory threshold");
5885            }
5886            for (PackageParser.Package pkg : sortedPkgs) {
5887                long usableSpace = dataDir.getUsableSpace();
5888                if (usableSpace < lowThreshold) {
5889                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5890                    break;
5891                }
5892                performBootDexOpt(pkg, ++i, total);
5893            }
5894        }
5895    }
5896
5897    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5898        // Filter out packages that aren't recently used.
5899        //
5900        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5901        // should do a full dexopt.
5902        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5903            int total = pkgs.size();
5904            int skipped = 0;
5905            long now = System.currentTimeMillis();
5906            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5907                PackageParser.Package pkg = i.next();
5908                long then = pkg.mLastPackageUsageTimeInMills;
5909                if (then + mDexOptLRUThresholdInMills < now) {
5910                    if (DEBUG_DEXOPT) {
5911                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5912                              ((then == 0) ? "never" : new Date(then)));
5913                    }
5914                    i.remove();
5915                    skipped++;
5916                }
5917            }
5918            if (DEBUG_DEXOPT) {
5919                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5920            }
5921        }
5922    }
5923
5924    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5925        List<ResolveInfo> ris = null;
5926        try {
5927            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5928                    intent, null, 0, UserHandle.USER_OWNER);
5929        } catch (RemoteException e) {
5930        }
5931        ArraySet<String> pkgNames = new ArraySet<String>();
5932        if (ris != null) {
5933            for (ResolveInfo ri : ris) {
5934                pkgNames.add(ri.activityInfo.packageName);
5935            }
5936        }
5937        return pkgNames;
5938    }
5939
5940    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5941        if (DEBUG_DEXOPT) {
5942            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5943        }
5944        if (!isFirstBoot()) {
5945            try {
5946                ActivityManagerNative.getDefault().showBootMessage(
5947                        mContext.getResources().getString(R.string.android_upgrading_apk,
5948                                curr, total), true);
5949            } catch (RemoteException e) {
5950            }
5951        }
5952        PackageParser.Package p = pkg;
5953        synchronized (mInstallLock) {
5954            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5955                    false /* force dex */, false /* defer */, true /* include dependencies */);
5956        }
5957    }
5958
5959    @Override
5960    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5961        return performDexOpt(packageName, instructionSet, false);
5962    }
5963
5964    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5965        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5966        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5967        if (!dexopt && !updateUsage) {
5968            // We aren't going to dexopt or update usage, so bail early.
5969            return false;
5970        }
5971        PackageParser.Package p;
5972        final String targetInstructionSet;
5973        synchronized (mPackages) {
5974            p = mPackages.get(packageName);
5975            if (p == null) {
5976                return false;
5977            }
5978            if (updateUsage) {
5979                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5980            }
5981            mPackageUsage.write(false);
5982            if (!dexopt) {
5983                // We aren't going to dexopt, so bail early.
5984                return false;
5985            }
5986
5987            targetInstructionSet = instructionSet != null ? instructionSet :
5988                    getPrimaryInstructionSet(p.applicationInfo);
5989            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5990                return false;
5991            }
5992        }
5993
5994        synchronized (mInstallLock) {
5995            final String[] instructionSets = new String[] { targetInstructionSet };
5996            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5997                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5998            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5999        }
6000    }
6001
6002    public ArraySet<String> getPackagesThatNeedDexOpt() {
6003        ArraySet<String> pkgs = null;
6004        synchronized (mPackages) {
6005            for (PackageParser.Package p : mPackages.values()) {
6006                if (DEBUG_DEXOPT) {
6007                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6008                }
6009                if (!p.mDexOptPerformed.isEmpty()) {
6010                    continue;
6011                }
6012                if (pkgs == null) {
6013                    pkgs = new ArraySet<String>();
6014                }
6015                pkgs.add(p.packageName);
6016            }
6017        }
6018        return pkgs;
6019    }
6020
6021    public void shutdown() {
6022        mPackageUsage.write(true);
6023    }
6024
6025    @Override
6026    public void forceDexOpt(String packageName) {
6027        enforceSystemOrRoot("forceDexOpt");
6028
6029        PackageParser.Package pkg;
6030        synchronized (mPackages) {
6031            pkg = mPackages.get(packageName);
6032            if (pkg == null) {
6033                throw new IllegalArgumentException("Missing package: " + packageName);
6034            }
6035        }
6036
6037        synchronized (mInstallLock) {
6038            final String[] instructionSets = new String[] {
6039                    getPrimaryInstructionSet(pkg.applicationInfo) };
6040            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6041                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6042            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6043                throw new IllegalStateException("Failed to dexopt: " + res);
6044            }
6045        }
6046    }
6047
6048    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6049        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6050            Slog.w(TAG, "Unable to update from " + oldPkg.name
6051                    + " to " + newPkg.packageName
6052                    + ": old package not in system partition");
6053            return false;
6054        } else if (mPackages.get(oldPkg.name) != null) {
6055            Slog.w(TAG, "Unable to update from " + oldPkg.name
6056                    + " to " + newPkg.packageName
6057                    + ": old package still exists");
6058            return false;
6059        }
6060        return true;
6061    }
6062
6063    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6064        int[] users = sUserManager.getUserIds();
6065        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6066        if (res < 0) {
6067            return res;
6068        }
6069        for (int user : users) {
6070            if (user != 0) {
6071                res = mInstaller.createUserData(volumeUuid, packageName,
6072                        UserHandle.getUid(user, uid), user, seinfo);
6073                if (res < 0) {
6074                    return res;
6075                }
6076            }
6077        }
6078        return res;
6079    }
6080
6081    private int removeDataDirsLI(String volumeUuid, String packageName) {
6082        int[] users = sUserManager.getUserIds();
6083        int res = 0;
6084        for (int user : users) {
6085            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6086            if (resInner < 0) {
6087                res = resInner;
6088            }
6089        }
6090
6091        return res;
6092    }
6093
6094    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6095        int[] users = sUserManager.getUserIds();
6096        int res = 0;
6097        for (int user : users) {
6098            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6099            if (resInner < 0) {
6100                res = resInner;
6101            }
6102        }
6103        return res;
6104    }
6105
6106    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6107            PackageParser.Package changingLib) {
6108        if (file.path != null) {
6109            usesLibraryFiles.add(file.path);
6110            return;
6111        }
6112        PackageParser.Package p = mPackages.get(file.apk);
6113        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6114            // If we are doing this while in the middle of updating a library apk,
6115            // then we need to make sure to use that new apk for determining the
6116            // dependencies here.  (We haven't yet finished committing the new apk
6117            // to the package manager state.)
6118            if (p == null || p.packageName.equals(changingLib.packageName)) {
6119                p = changingLib;
6120            }
6121        }
6122        if (p != null) {
6123            usesLibraryFiles.addAll(p.getAllCodePaths());
6124        }
6125    }
6126
6127    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6128            PackageParser.Package changingLib) throws PackageManagerException {
6129        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6130            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6131            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6132            for (int i=0; i<N; i++) {
6133                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6134                if (file == null) {
6135                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6136                            "Package " + pkg.packageName + " requires unavailable shared library "
6137                            + pkg.usesLibraries.get(i) + "; failing!");
6138                }
6139                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6140            }
6141            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6142            for (int i=0; i<N; i++) {
6143                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6144                if (file == null) {
6145                    Slog.w(TAG, "Package " + pkg.packageName
6146                            + " desires unavailable shared library "
6147                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6148                } else {
6149                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6150                }
6151            }
6152            N = usesLibraryFiles.size();
6153            if (N > 0) {
6154                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6155            } else {
6156                pkg.usesLibraryFiles = null;
6157            }
6158        }
6159    }
6160
6161    private static boolean hasString(List<String> list, List<String> which) {
6162        if (list == null) {
6163            return false;
6164        }
6165        for (int i=list.size()-1; i>=0; i--) {
6166            for (int j=which.size()-1; j>=0; j--) {
6167                if (which.get(j).equals(list.get(i))) {
6168                    return true;
6169                }
6170            }
6171        }
6172        return false;
6173    }
6174
6175    private void updateAllSharedLibrariesLPw() {
6176        for (PackageParser.Package pkg : mPackages.values()) {
6177            try {
6178                updateSharedLibrariesLPw(pkg, null);
6179            } catch (PackageManagerException e) {
6180                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6181            }
6182        }
6183    }
6184
6185    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6186            PackageParser.Package changingPkg) {
6187        ArrayList<PackageParser.Package> res = null;
6188        for (PackageParser.Package pkg : mPackages.values()) {
6189            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6190                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6191                if (res == null) {
6192                    res = new ArrayList<PackageParser.Package>();
6193                }
6194                res.add(pkg);
6195                try {
6196                    updateSharedLibrariesLPw(pkg, changingPkg);
6197                } catch (PackageManagerException e) {
6198                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6199                }
6200            }
6201        }
6202        return res;
6203    }
6204
6205    /**
6206     * Derive the value of the {@code cpuAbiOverride} based on the provided
6207     * value and an optional stored value from the package settings.
6208     */
6209    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6210        String cpuAbiOverride = null;
6211
6212        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6213            cpuAbiOverride = null;
6214        } else if (abiOverride != null) {
6215            cpuAbiOverride = abiOverride;
6216        } else if (settings != null) {
6217            cpuAbiOverride = settings.cpuAbiOverrideString;
6218        }
6219
6220        return cpuAbiOverride;
6221    }
6222
6223    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6224            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6225        boolean success = false;
6226        try {
6227            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6228                    currentTime, user);
6229            success = true;
6230            return res;
6231        } finally {
6232            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6233                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6234            }
6235        }
6236    }
6237
6238    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6239            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6240        final File scanFile = new File(pkg.codePath);
6241        if (pkg.applicationInfo.getCodePath() == null ||
6242                pkg.applicationInfo.getResourcePath() == null) {
6243            // Bail out. The resource and code paths haven't been set.
6244            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6245                    "Code and resource paths haven't been set correctly");
6246        }
6247
6248        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6249            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6250        } else {
6251            // Only allow system apps to be flagged as core apps.
6252            pkg.coreApp = false;
6253        }
6254
6255        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6256            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6257        }
6258
6259        if (mCustomResolverComponentName != null &&
6260                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6261            setUpCustomResolverActivity(pkg);
6262        }
6263
6264        if (pkg.packageName.equals("android")) {
6265            synchronized (mPackages) {
6266                if (mAndroidApplication != null) {
6267                    Slog.w(TAG, "*************************************************");
6268                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6269                    Slog.w(TAG, " file=" + scanFile);
6270                    Slog.w(TAG, "*************************************************");
6271                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6272                            "Core android package being redefined.  Skipping.");
6273                }
6274
6275                // Set up information for our fall-back user intent resolution activity.
6276                mPlatformPackage = pkg;
6277                pkg.mVersionCode = mSdkVersion;
6278                mAndroidApplication = pkg.applicationInfo;
6279
6280                if (!mResolverReplaced) {
6281                    mResolveActivity.applicationInfo = mAndroidApplication;
6282                    mResolveActivity.name = ResolverActivity.class.getName();
6283                    mResolveActivity.packageName = mAndroidApplication.packageName;
6284                    mResolveActivity.processName = "system:ui";
6285                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6286                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6287                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6288                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6289                    mResolveActivity.exported = true;
6290                    mResolveActivity.enabled = true;
6291                    mResolveInfo.activityInfo = mResolveActivity;
6292                    mResolveInfo.priority = 0;
6293                    mResolveInfo.preferredOrder = 0;
6294                    mResolveInfo.match = 0;
6295                    mResolveComponentName = new ComponentName(
6296                            mAndroidApplication.packageName, mResolveActivity.name);
6297                }
6298            }
6299        }
6300
6301        if (DEBUG_PACKAGE_SCANNING) {
6302            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6303                Log.d(TAG, "Scanning package " + pkg.packageName);
6304        }
6305
6306        if (mPackages.containsKey(pkg.packageName)
6307                || mSharedLibraries.containsKey(pkg.packageName)) {
6308            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6309                    "Application package " + pkg.packageName
6310                    + " already installed.  Skipping duplicate.");
6311        }
6312
6313        // If we're only installing presumed-existing packages, require that the
6314        // scanned APK is both already known and at the path previously established
6315        // for it.  Previously unknown packages we pick up normally, but if we have an
6316        // a priori expectation about this package's install presence, enforce it.
6317        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6318            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6319            if (known != null) {
6320                if (DEBUG_PACKAGE_SCANNING) {
6321                    Log.d(TAG, "Examining " + pkg.codePath
6322                            + " and requiring known paths " + known.codePathString
6323                            + " & " + known.resourcePathString);
6324                }
6325                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6326                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6327                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6328                            "Application package " + pkg.packageName
6329                            + " found at " + pkg.applicationInfo.getCodePath()
6330                            + " but expected at " + known.codePathString + "; ignoring.");
6331                }
6332            }
6333        }
6334
6335        // Initialize package source and resource directories
6336        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6337        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6338
6339        SharedUserSetting suid = null;
6340        PackageSetting pkgSetting = null;
6341
6342        if (!isSystemApp(pkg)) {
6343            // Only system apps can use these features.
6344            pkg.mOriginalPackages = null;
6345            pkg.mRealPackage = null;
6346            pkg.mAdoptPermissions = null;
6347        }
6348
6349        // writer
6350        synchronized (mPackages) {
6351            if (pkg.mSharedUserId != null) {
6352                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6353                if (suid == null) {
6354                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6355                            "Creating application package " + pkg.packageName
6356                            + " for shared user failed");
6357                }
6358                if (DEBUG_PACKAGE_SCANNING) {
6359                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6360                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6361                                + "): packages=" + suid.packages);
6362                }
6363            }
6364
6365            // Check if we are renaming from an original package name.
6366            PackageSetting origPackage = null;
6367            String realName = null;
6368            if (pkg.mOriginalPackages != null) {
6369                // This package may need to be renamed to a previously
6370                // installed name.  Let's check on that...
6371                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6372                if (pkg.mOriginalPackages.contains(renamed)) {
6373                    // This package had originally been installed as the
6374                    // original name, and we have already taken care of
6375                    // transitioning to the new one.  Just update the new
6376                    // one to continue using the old name.
6377                    realName = pkg.mRealPackage;
6378                    if (!pkg.packageName.equals(renamed)) {
6379                        // Callers into this function may have already taken
6380                        // care of renaming the package; only do it here if
6381                        // it is not already done.
6382                        pkg.setPackageName(renamed);
6383                    }
6384
6385                } else {
6386                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6387                        if ((origPackage = mSettings.peekPackageLPr(
6388                                pkg.mOriginalPackages.get(i))) != null) {
6389                            // We do have the package already installed under its
6390                            // original name...  should we use it?
6391                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6392                                // New package is not compatible with original.
6393                                origPackage = null;
6394                                continue;
6395                            } else if (origPackage.sharedUser != null) {
6396                                // Make sure uid is compatible between packages.
6397                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6398                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6399                                            + " to " + pkg.packageName + ": old uid "
6400                                            + origPackage.sharedUser.name
6401                                            + " differs from " + pkg.mSharedUserId);
6402                                    origPackage = null;
6403                                    continue;
6404                                }
6405                            } else {
6406                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6407                                        + pkg.packageName + " to old name " + origPackage.name);
6408                            }
6409                            break;
6410                        }
6411                    }
6412                }
6413            }
6414
6415            if (mTransferedPackages.contains(pkg.packageName)) {
6416                Slog.w(TAG, "Package " + pkg.packageName
6417                        + " was transferred to another, but its .apk remains");
6418            }
6419
6420            // Just create the setting, don't add it yet. For already existing packages
6421            // the PkgSetting exists already and doesn't have to be created.
6422            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6423                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6424                    pkg.applicationInfo.primaryCpuAbi,
6425                    pkg.applicationInfo.secondaryCpuAbi,
6426                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6427                    user, false);
6428            if (pkgSetting == null) {
6429                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6430                        "Creating application package " + pkg.packageName + " failed");
6431            }
6432
6433            if (pkgSetting.origPackage != null) {
6434                // If we are first transitioning from an original package,
6435                // fix up the new package's name now.  We need to do this after
6436                // looking up the package under its new name, so getPackageLP
6437                // can take care of fiddling things correctly.
6438                pkg.setPackageName(origPackage.name);
6439
6440                // File a report about this.
6441                String msg = "New package " + pkgSetting.realName
6442                        + " renamed to replace old package " + pkgSetting.name;
6443                reportSettingsProblem(Log.WARN, msg);
6444
6445                // Make a note of it.
6446                mTransferedPackages.add(origPackage.name);
6447
6448                // No longer need to retain this.
6449                pkgSetting.origPackage = null;
6450            }
6451
6452            if (realName != null) {
6453                // Make a note of it.
6454                mTransferedPackages.add(pkg.packageName);
6455            }
6456
6457            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6458                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6459            }
6460
6461            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6462                // Check all shared libraries and map to their actual file path.
6463                // We only do this here for apps not on a system dir, because those
6464                // are the only ones that can fail an install due to this.  We
6465                // will take care of the system apps by updating all of their
6466                // library paths after the scan is done.
6467                updateSharedLibrariesLPw(pkg, null);
6468            }
6469
6470            if (mFoundPolicyFile) {
6471                SELinuxMMAC.assignSeinfoValue(pkg);
6472            }
6473
6474            pkg.applicationInfo.uid = pkgSetting.appId;
6475            pkg.mExtras = pkgSetting;
6476            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6477                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6478                    // We just determined the app is signed correctly, so bring
6479                    // over the latest parsed certs.
6480                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6481                } else {
6482                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6483                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6484                                "Package " + pkg.packageName + " upgrade keys do not match the "
6485                                + "previously installed version");
6486                    } else {
6487                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6488                        String msg = "System package " + pkg.packageName
6489                            + " signature changed; retaining data.";
6490                        reportSettingsProblem(Log.WARN, msg);
6491                    }
6492                }
6493            } else {
6494                try {
6495                    verifySignaturesLP(pkgSetting, pkg);
6496                    // We just determined the app is signed correctly, so bring
6497                    // over the latest parsed certs.
6498                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6499                } catch (PackageManagerException e) {
6500                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6501                        throw e;
6502                    }
6503                    // The signature has changed, but this package is in the system
6504                    // image...  let's recover!
6505                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6506                    // However...  if this package is part of a shared user, but it
6507                    // doesn't match the signature of the shared user, let's fail.
6508                    // What this means is that you can't change the signatures
6509                    // associated with an overall shared user, which doesn't seem all
6510                    // that unreasonable.
6511                    if (pkgSetting.sharedUser != null) {
6512                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6513                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6514                            throw new PackageManagerException(
6515                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6516                                            "Signature mismatch for shared user : "
6517                                            + pkgSetting.sharedUser);
6518                        }
6519                    }
6520                    // File a report about this.
6521                    String msg = "System package " + pkg.packageName
6522                        + " signature changed; retaining data.";
6523                    reportSettingsProblem(Log.WARN, msg);
6524                }
6525            }
6526            // Verify that this new package doesn't have any content providers
6527            // that conflict with existing packages.  Only do this if the
6528            // package isn't already installed, since we don't want to break
6529            // things that are installed.
6530            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6531                final int N = pkg.providers.size();
6532                int i;
6533                for (i=0; i<N; i++) {
6534                    PackageParser.Provider p = pkg.providers.get(i);
6535                    if (p.info.authority != null) {
6536                        String names[] = p.info.authority.split(";");
6537                        for (int j = 0; j < names.length; j++) {
6538                            if (mProvidersByAuthority.containsKey(names[j])) {
6539                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6540                                final String otherPackageName =
6541                                        ((other != null && other.getComponentName() != null) ?
6542                                                other.getComponentName().getPackageName() : "?");
6543                                throw new PackageManagerException(
6544                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6545                                                "Can't install because provider name " + names[j]
6546                                                + " (in package " + pkg.applicationInfo.packageName
6547                                                + ") is already used by " + otherPackageName);
6548                            }
6549                        }
6550                    }
6551                }
6552            }
6553
6554            if (pkg.mAdoptPermissions != null) {
6555                // This package wants to adopt ownership of permissions from
6556                // another package.
6557                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6558                    final String origName = pkg.mAdoptPermissions.get(i);
6559                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6560                    if (orig != null) {
6561                        if (verifyPackageUpdateLPr(orig, pkg)) {
6562                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6563                                    + pkg.packageName);
6564                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6565                        }
6566                    }
6567                }
6568            }
6569        }
6570
6571        final String pkgName = pkg.packageName;
6572
6573        final long scanFileTime = scanFile.lastModified();
6574        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6575        pkg.applicationInfo.processName = fixProcessName(
6576                pkg.applicationInfo.packageName,
6577                pkg.applicationInfo.processName,
6578                pkg.applicationInfo.uid);
6579
6580        File dataPath;
6581        if (mPlatformPackage == pkg) {
6582            // The system package is special.
6583            dataPath = new File(Environment.getDataDirectory(), "system");
6584
6585            pkg.applicationInfo.dataDir = dataPath.getPath();
6586
6587        } else {
6588            // This is a normal package, need to make its data directory.
6589            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6590                    UserHandle.USER_OWNER);
6591
6592            boolean uidError = false;
6593            if (dataPath.exists()) {
6594                int currentUid = 0;
6595                try {
6596                    StructStat stat = Os.stat(dataPath.getPath());
6597                    currentUid = stat.st_uid;
6598                } catch (ErrnoException e) {
6599                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6600                }
6601
6602                // If we have mismatched owners for the data path, we have a problem.
6603                if (currentUid != pkg.applicationInfo.uid) {
6604                    boolean recovered = false;
6605                    if (currentUid == 0) {
6606                        // The directory somehow became owned by root.  Wow.
6607                        // This is probably because the system was stopped while
6608                        // installd was in the middle of messing with its libs
6609                        // directory.  Ask installd to fix that.
6610                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6611                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6612                        if (ret >= 0) {
6613                            recovered = true;
6614                            String msg = "Package " + pkg.packageName
6615                                    + " unexpectedly changed to uid 0; recovered to " +
6616                                    + pkg.applicationInfo.uid;
6617                            reportSettingsProblem(Log.WARN, msg);
6618                        }
6619                    }
6620                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6621                            || (scanFlags&SCAN_BOOTING) != 0)) {
6622                        // If this is a system app, we can at least delete its
6623                        // current data so the application will still work.
6624                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6625                        if (ret >= 0) {
6626                            // TODO: Kill the processes first
6627                            // Old data gone!
6628                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6629                                    ? "System package " : "Third party package ";
6630                            String msg = prefix + pkg.packageName
6631                                    + " has changed from uid: "
6632                                    + currentUid + " to "
6633                                    + pkg.applicationInfo.uid + "; old data erased";
6634                            reportSettingsProblem(Log.WARN, msg);
6635                            recovered = true;
6636
6637                            // And now re-install the app.
6638                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6639                                    pkg.applicationInfo.seinfo);
6640                            if (ret == -1) {
6641                                // Ack should not happen!
6642                                msg = prefix + pkg.packageName
6643                                        + " could not have data directory re-created after delete.";
6644                                reportSettingsProblem(Log.WARN, msg);
6645                                throw new PackageManagerException(
6646                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6647                            }
6648                        }
6649                        if (!recovered) {
6650                            mHasSystemUidErrors = true;
6651                        }
6652                    } else if (!recovered) {
6653                        // If we allow this install to proceed, we will be broken.
6654                        // Abort, abort!
6655                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6656                                "scanPackageLI");
6657                    }
6658                    if (!recovered) {
6659                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6660                            + pkg.applicationInfo.uid + "/fs_"
6661                            + currentUid;
6662                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6663                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6664                        String msg = "Package " + pkg.packageName
6665                                + " has mismatched uid: "
6666                                + currentUid + " on disk, "
6667                                + pkg.applicationInfo.uid + " in settings";
6668                        // writer
6669                        synchronized (mPackages) {
6670                            mSettings.mReadMessages.append(msg);
6671                            mSettings.mReadMessages.append('\n');
6672                            uidError = true;
6673                            if (!pkgSetting.uidError) {
6674                                reportSettingsProblem(Log.ERROR, msg);
6675                            }
6676                        }
6677                    }
6678                }
6679                pkg.applicationInfo.dataDir = dataPath.getPath();
6680                if (mShouldRestoreconData) {
6681                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6682                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6683                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6684                }
6685            } else {
6686                if (DEBUG_PACKAGE_SCANNING) {
6687                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6688                        Log.v(TAG, "Want this data dir: " + dataPath);
6689                }
6690                //invoke installer to do the actual installation
6691                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6692                        pkg.applicationInfo.seinfo);
6693                if (ret < 0) {
6694                    // Error from installer
6695                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6696                            "Unable to create data dirs [errorCode=" + ret + "]");
6697                }
6698
6699                if (dataPath.exists()) {
6700                    pkg.applicationInfo.dataDir = dataPath.getPath();
6701                } else {
6702                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6703                    pkg.applicationInfo.dataDir = null;
6704                }
6705            }
6706
6707            pkgSetting.uidError = uidError;
6708        }
6709
6710        final String path = scanFile.getPath();
6711        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6712
6713        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6714            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6715
6716            // Some system apps still use directory structure for native libraries
6717            // in which case we might end up not detecting abi solely based on apk
6718            // structure. Try to detect abi based on directory structure.
6719            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6720                    pkg.applicationInfo.primaryCpuAbi == null) {
6721                setBundledAppAbisAndRoots(pkg, pkgSetting);
6722                setNativeLibraryPaths(pkg);
6723            }
6724
6725        } else {
6726            if ((scanFlags & SCAN_MOVE) != 0) {
6727                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6728                // but we already have this packages package info in the PackageSetting. We just
6729                // use that and derive the native library path based on the new codepath.
6730                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6731                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6732            }
6733
6734            // Set native library paths again. For moves, the path will be updated based on the
6735            // ABIs we've determined above. For non-moves, the path will be updated based on the
6736            // ABIs we determined during compilation, but the path will depend on the final
6737            // package path (after the rename away from the stage path).
6738            setNativeLibraryPaths(pkg);
6739        }
6740
6741        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6742        final int[] userIds = sUserManager.getUserIds();
6743        synchronized (mInstallLock) {
6744            // Create a native library symlink only if we have native libraries
6745            // and if the native libraries are 32 bit libraries. We do not provide
6746            // this symlink for 64 bit libraries.
6747            if (pkg.applicationInfo.primaryCpuAbi != null &&
6748                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6749                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6750                for (int userId : userIds) {
6751                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6752                            nativeLibPath, userId) < 0) {
6753                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6754                                "Failed linking native library dir (user=" + userId + ")");
6755                    }
6756                }
6757            }
6758        }
6759
6760        // This is a special case for the "system" package, where the ABI is
6761        // dictated by the zygote configuration (and init.rc). We should keep track
6762        // of this ABI so that we can deal with "normal" applications that run under
6763        // the same UID correctly.
6764        if (mPlatformPackage == pkg) {
6765            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6766                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6767        }
6768
6769        // If there's a mismatch between the abi-override in the package setting
6770        // and the abiOverride specified for the install. Warn about this because we
6771        // would've already compiled the app without taking the package setting into
6772        // account.
6773        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6774            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6775                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6776                        " for package: " + pkg.packageName);
6777            }
6778        }
6779
6780        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6781        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6782        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6783
6784        // Copy the derived override back to the parsed package, so that we can
6785        // update the package settings accordingly.
6786        pkg.cpuAbiOverride = cpuAbiOverride;
6787
6788        if (DEBUG_ABI_SELECTION) {
6789            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6790                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6791                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6792        }
6793
6794        // Push the derived path down into PackageSettings so we know what to
6795        // clean up at uninstall time.
6796        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6797
6798        if (DEBUG_ABI_SELECTION) {
6799            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6800                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6801                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6802        }
6803
6804        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6805            // We don't do this here during boot because we can do it all
6806            // at once after scanning all existing packages.
6807            //
6808            // We also do this *before* we perform dexopt on this package, so that
6809            // we can avoid redundant dexopts, and also to make sure we've got the
6810            // code and package path correct.
6811            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6812                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6813        }
6814
6815        if ((scanFlags & SCAN_NO_DEX) == 0) {
6816            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6817                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6818            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6819                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6820            }
6821        }
6822        if (mFactoryTest && pkg.requestedPermissions.contains(
6823                android.Manifest.permission.FACTORY_TEST)) {
6824            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6825        }
6826
6827        ArrayList<PackageParser.Package> clientLibPkgs = null;
6828
6829        // writer
6830        synchronized (mPackages) {
6831            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6832                // Only system apps can add new shared libraries.
6833                if (pkg.libraryNames != null) {
6834                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6835                        String name = pkg.libraryNames.get(i);
6836                        boolean allowed = false;
6837                        if (pkg.isUpdatedSystemApp()) {
6838                            // New library entries can only be added through the
6839                            // system image.  This is important to get rid of a lot
6840                            // of nasty edge cases: for example if we allowed a non-
6841                            // system update of the app to add a library, then uninstalling
6842                            // the update would make the library go away, and assumptions
6843                            // we made such as through app install filtering would now
6844                            // have allowed apps on the device which aren't compatible
6845                            // with it.  Better to just have the restriction here, be
6846                            // conservative, and create many fewer cases that can negatively
6847                            // impact the user experience.
6848                            final PackageSetting sysPs = mSettings
6849                                    .getDisabledSystemPkgLPr(pkg.packageName);
6850                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6851                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6852                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6853                                        allowed = true;
6854                                        allowed = true;
6855                                        break;
6856                                    }
6857                                }
6858                            }
6859                        } else {
6860                            allowed = true;
6861                        }
6862                        if (allowed) {
6863                            if (!mSharedLibraries.containsKey(name)) {
6864                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6865                            } else if (!name.equals(pkg.packageName)) {
6866                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6867                                        + name + " already exists; skipping");
6868                            }
6869                        } else {
6870                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6871                                    + name + " that is not declared on system image; skipping");
6872                        }
6873                    }
6874                    if ((scanFlags&SCAN_BOOTING) == 0) {
6875                        // If we are not booting, we need to update any applications
6876                        // that are clients of our shared library.  If we are booting,
6877                        // this will all be done once the scan is complete.
6878                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6879                    }
6880                }
6881            }
6882        }
6883
6884        // We also need to dexopt any apps that are dependent on this library.  Note that
6885        // if these fail, we should abort the install since installing the library will
6886        // result in some apps being broken.
6887        if (clientLibPkgs != null) {
6888            if ((scanFlags & SCAN_NO_DEX) == 0) {
6889                for (int i = 0; i < clientLibPkgs.size(); i++) {
6890                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6891                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6892                            null /* instruction sets */, forceDex,
6893                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6894                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6895                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6896                                "scanPackageLI failed to dexopt clientLibPkgs");
6897                    }
6898                }
6899            }
6900        }
6901
6902        // Also need to kill any apps that are dependent on the library.
6903        if (clientLibPkgs != null) {
6904            for (int i=0; i<clientLibPkgs.size(); i++) {
6905                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6906                killApplication(clientPkg.applicationInfo.packageName,
6907                        clientPkg.applicationInfo.uid, "update lib");
6908            }
6909        }
6910
6911        // Make sure we're not adding any bogus keyset info
6912        KeySetManagerService ksms = mSettings.mKeySetManagerService;
6913        ksms.assertScannedPackageValid(pkg);
6914
6915        // writer
6916        synchronized (mPackages) {
6917            // We don't expect installation to fail beyond this point
6918
6919            // Add the new setting to mSettings
6920            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6921            // Add the new setting to mPackages
6922            mPackages.put(pkg.applicationInfo.packageName, pkg);
6923            // Make sure we don't accidentally delete its data.
6924            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6925            while (iter.hasNext()) {
6926                PackageCleanItem item = iter.next();
6927                if (pkgName.equals(item.packageName)) {
6928                    iter.remove();
6929                }
6930            }
6931
6932            // Take care of first install / last update times.
6933            if (currentTime != 0) {
6934                if (pkgSetting.firstInstallTime == 0) {
6935                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6936                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6937                    pkgSetting.lastUpdateTime = currentTime;
6938                }
6939            } else if (pkgSetting.firstInstallTime == 0) {
6940                // We need *something*.  Take time time stamp of the file.
6941                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6942            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6943                if (scanFileTime != pkgSetting.timeStamp) {
6944                    // A package on the system image has changed; consider this
6945                    // to be an update.
6946                    pkgSetting.lastUpdateTime = scanFileTime;
6947                }
6948            }
6949
6950            // Add the package's KeySets to the global KeySetManagerService
6951            ksms.addScannedPackageLPw(pkg);
6952
6953            int N = pkg.providers.size();
6954            StringBuilder r = null;
6955            int i;
6956            for (i=0; i<N; i++) {
6957                PackageParser.Provider p = pkg.providers.get(i);
6958                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6959                        p.info.processName, pkg.applicationInfo.uid);
6960                mProviders.addProvider(p);
6961                p.syncable = p.info.isSyncable;
6962                if (p.info.authority != null) {
6963                    String names[] = p.info.authority.split(";");
6964                    p.info.authority = null;
6965                    for (int j = 0; j < names.length; j++) {
6966                        if (j == 1 && p.syncable) {
6967                            // We only want the first authority for a provider to possibly be
6968                            // syncable, so if we already added this provider using a different
6969                            // authority clear the syncable flag. We copy the provider before
6970                            // changing it because the mProviders object contains a reference
6971                            // to a provider that we don't want to change.
6972                            // Only do this for the second authority since the resulting provider
6973                            // object can be the same for all future authorities for this provider.
6974                            p = new PackageParser.Provider(p);
6975                            p.syncable = false;
6976                        }
6977                        if (!mProvidersByAuthority.containsKey(names[j])) {
6978                            mProvidersByAuthority.put(names[j], p);
6979                            if (p.info.authority == null) {
6980                                p.info.authority = names[j];
6981                            } else {
6982                                p.info.authority = p.info.authority + ";" + names[j];
6983                            }
6984                            if (DEBUG_PACKAGE_SCANNING) {
6985                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6986                                    Log.d(TAG, "Registered content provider: " + names[j]
6987                                            + ", className = " + p.info.name + ", isSyncable = "
6988                                            + p.info.isSyncable);
6989                            }
6990                        } else {
6991                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6992                            Slog.w(TAG, "Skipping provider name " + names[j] +
6993                                    " (in package " + pkg.applicationInfo.packageName +
6994                                    "): name already used by "
6995                                    + ((other != null && other.getComponentName() != null)
6996                                            ? other.getComponentName().getPackageName() : "?"));
6997                        }
6998                    }
6999                }
7000                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7001                    if (r == null) {
7002                        r = new StringBuilder(256);
7003                    } else {
7004                        r.append(' ');
7005                    }
7006                    r.append(p.info.name);
7007                }
7008            }
7009            if (r != null) {
7010                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7011            }
7012
7013            N = pkg.services.size();
7014            r = null;
7015            for (i=0; i<N; i++) {
7016                PackageParser.Service s = pkg.services.get(i);
7017                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7018                        s.info.processName, pkg.applicationInfo.uid);
7019                mServices.addService(s);
7020                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7021                    if (r == null) {
7022                        r = new StringBuilder(256);
7023                    } else {
7024                        r.append(' ');
7025                    }
7026                    r.append(s.info.name);
7027                }
7028            }
7029            if (r != null) {
7030                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7031            }
7032
7033            N = pkg.receivers.size();
7034            r = null;
7035            for (i=0; i<N; i++) {
7036                PackageParser.Activity a = pkg.receivers.get(i);
7037                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7038                        a.info.processName, pkg.applicationInfo.uid);
7039                mReceivers.addActivity(a, "receiver");
7040                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7041                    if (r == null) {
7042                        r = new StringBuilder(256);
7043                    } else {
7044                        r.append(' ');
7045                    }
7046                    r.append(a.info.name);
7047                }
7048            }
7049            if (r != null) {
7050                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7051            }
7052
7053            N = pkg.activities.size();
7054            r = null;
7055            for (i=0; i<N; i++) {
7056                PackageParser.Activity a = pkg.activities.get(i);
7057                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7058                        a.info.processName, pkg.applicationInfo.uid);
7059                mActivities.addActivity(a, "activity");
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, "  Activities: " + r);
7071            }
7072
7073            N = pkg.permissionGroups.size();
7074            r = null;
7075            for (i=0; i<N; i++) {
7076                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7077                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7078                if (cur == null) {
7079                    mPermissionGroups.put(pg.info.name, pg);
7080                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7081                        if (r == null) {
7082                            r = new StringBuilder(256);
7083                        } else {
7084                            r.append(' ');
7085                        }
7086                        r.append(pg.info.name);
7087                    }
7088                } else {
7089                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7090                            + pg.info.packageName + " ignored: original from "
7091                            + cur.info.packageName);
7092                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7093                        if (r == null) {
7094                            r = new StringBuilder(256);
7095                        } else {
7096                            r.append(' ');
7097                        }
7098                        r.append("DUP:");
7099                        r.append(pg.info.name);
7100                    }
7101                }
7102            }
7103            if (r != null) {
7104                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7105            }
7106
7107            N = pkg.permissions.size();
7108            r = null;
7109            for (i=0; i<N; i++) {
7110                PackageParser.Permission p = pkg.permissions.get(i);
7111
7112                // Now that permission groups have a special meaning, we ignore permission
7113                // groups for legacy apps to prevent unexpected behavior. In particular,
7114                // permissions for one app being granted to someone just becuase they happen
7115                // to be in a group defined by another app (before this had no implications).
7116                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7117                    p.group = mPermissionGroups.get(p.info.group);
7118                    // Warn for a permission in an unknown group.
7119                    if (p.info.group != null && p.group == null) {
7120                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7121                                + p.info.packageName + " in an unknown group " + p.info.group);
7122                    }
7123                }
7124
7125                ArrayMap<String, BasePermission> permissionMap =
7126                        p.tree ? mSettings.mPermissionTrees
7127                                : mSettings.mPermissions;
7128                BasePermission bp = permissionMap.get(p.info.name);
7129
7130                // Allow system apps to redefine non-system permissions
7131                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7132                    final boolean currentOwnerIsSystem = (bp.perm != null
7133                            && isSystemApp(bp.perm.owner));
7134                    if (isSystemApp(p.owner)) {
7135                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7136                            // It's a built-in permission and no owner, take ownership now
7137                            bp.packageSetting = pkgSetting;
7138                            bp.perm = p;
7139                            bp.uid = pkg.applicationInfo.uid;
7140                            bp.sourcePackage = p.info.packageName;
7141                        } else if (!currentOwnerIsSystem) {
7142                            String msg = "New decl " + p.owner + " of permission  "
7143                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7144                            reportSettingsProblem(Log.WARN, msg);
7145                            bp = null;
7146                        }
7147                    }
7148                }
7149
7150                if (bp == null) {
7151                    bp = new BasePermission(p.info.name, p.info.packageName,
7152                            BasePermission.TYPE_NORMAL);
7153                    permissionMap.put(p.info.name, bp);
7154                }
7155
7156                if (bp.perm == null) {
7157                    if (bp.sourcePackage == null
7158                            || bp.sourcePackage.equals(p.info.packageName)) {
7159                        BasePermission tree = findPermissionTreeLP(p.info.name);
7160                        if (tree == null
7161                                || tree.sourcePackage.equals(p.info.packageName)) {
7162                            bp.packageSetting = pkgSetting;
7163                            bp.perm = p;
7164                            bp.uid = pkg.applicationInfo.uid;
7165                            bp.sourcePackage = p.info.packageName;
7166                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7167                                if (r == null) {
7168                                    r = new StringBuilder(256);
7169                                } else {
7170                                    r.append(' ');
7171                                }
7172                                r.append(p.info.name);
7173                            }
7174                        } else {
7175                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7176                                    + p.info.packageName + " ignored: base tree "
7177                                    + tree.name + " is from package "
7178                                    + tree.sourcePackage);
7179                        }
7180                    } else {
7181                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7182                                + p.info.packageName + " ignored: original from "
7183                                + bp.sourcePackage);
7184                    }
7185                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7186                    if (r == null) {
7187                        r = new StringBuilder(256);
7188                    } else {
7189                        r.append(' ');
7190                    }
7191                    r.append("DUP:");
7192                    r.append(p.info.name);
7193                }
7194                if (bp.perm == p) {
7195                    bp.protectionLevel = p.info.protectionLevel;
7196                }
7197            }
7198
7199            if (r != null) {
7200                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7201            }
7202
7203            N = pkg.instrumentation.size();
7204            r = null;
7205            for (i=0; i<N; i++) {
7206                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7207                a.info.packageName = pkg.applicationInfo.packageName;
7208                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7209                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7210                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7211                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7212                a.info.dataDir = pkg.applicationInfo.dataDir;
7213
7214                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7215                // need other information about the application, like the ABI and what not ?
7216                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7217                mInstrumentation.put(a.getComponentName(), a);
7218                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7219                    if (r == null) {
7220                        r = new StringBuilder(256);
7221                    } else {
7222                        r.append(' ');
7223                    }
7224                    r.append(a.info.name);
7225                }
7226            }
7227            if (r != null) {
7228                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7229            }
7230
7231            if (pkg.protectedBroadcasts != null) {
7232                N = pkg.protectedBroadcasts.size();
7233                for (i=0; i<N; i++) {
7234                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7235                }
7236            }
7237
7238            pkgSetting.setTimeStamp(scanFileTime);
7239
7240            // Create idmap files for pairs of (packages, overlay packages).
7241            // Note: "android", ie framework-res.apk, is handled by native layers.
7242            if (pkg.mOverlayTarget != null) {
7243                // This is an overlay package.
7244                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7245                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7246                        mOverlays.put(pkg.mOverlayTarget,
7247                                new ArrayMap<String, PackageParser.Package>());
7248                    }
7249                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7250                    map.put(pkg.packageName, pkg);
7251                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7252                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7253                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7254                                "scanPackageLI failed to createIdmap");
7255                    }
7256                }
7257            } else if (mOverlays.containsKey(pkg.packageName) &&
7258                    !pkg.packageName.equals("android")) {
7259                // This is a regular package, with one or more known overlay packages.
7260                createIdmapsForPackageLI(pkg);
7261            }
7262        }
7263
7264        return pkg;
7265    }
7266
7267    /**
7268     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7269     * is derived purely on the basis of the contents of {@code scanFile} and
7270     * {@code cpuAbiOverride}.
7271     *
7272     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7273     */
7274    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7275                                 String cpuAbiOverride, boolean extractLibs)
7276            throws PackageManagerException {
7277        // TODO: We can probably be smarter about this stuff. For installed apps,
7278        // we can calculate this information at install time once and for all. For
7279        // system apps, we can probably assume that this information doesn't change
7280        // after the first boot scan. As things stand, we do lots of unnecessary work.
7281
7282        // Give ourselves some initial paths; we'll come back for another
7283        // pass once we've determined ABI below.
7284        setNativeLibraryPaths(pkg);
7285
7286        // We would never need to extract libs for forward-locked and external packages,
7287        // since the container service will do it for us. We shouldn't attempt to
7288        // extract libs from system app when it was not updated.
7289        if (pkg.isForwardLocked() || isExternal(pkg) ||
7290            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7291            extractLibs = false;
7292        }
7293
7294        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7295        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7296
7297        NativeLibraryHelper.Handle handle = null;
7298        try {
7299            handle = NativeLibraryHelper.Handle.create(scanFile);
7300            // TODO(multiArch): This can be null for apps that didn't go through the
7301            // usual installation process. We can calculate it again, like we
7302            // do during install time.
7303            //
7304            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7305            // unnecessary.
7306            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7307
7308            // Null out the abis so that they can be recalculated.
7309            pkg.applicationInfo.primaryCpuAbi = null;
7310            pkg.applicationInfo.secondaryCpuAbi = null;
7311            if (isMultiArch(pkg.applicationInfo)) {
7312                // Warn if we've set an abiOverride for multi-lib packages..
7313                // By definition, we need to copy both 32 and 64 bit libraries for
7314                // such packages.
7315                if (pkg.cpuAbiOverride != null
7316                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7317                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7318                }
7319
7320                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7321                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7322                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7323                    if (extractLibs) {
7324                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7325                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7326                                useIsaSpecificSubdirs);
7327                    } else {
7328                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7329                    }
7330                }
7331
7332                maybeThrowExceptionForMultiArchCopy(
7333                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7334
7335                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7336                    if (extractLibs) {
7337                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7338                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7339                                useIsaSpecificSubdirs);
7340                    } else {
7341                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7342                    }
7343                }
7344
7345                maybeThrowExceptionForMultiArchCopy(
7346                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7347
7348                if (abi64 >= 0) {
7349                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7350                }
7351
7352                if (abi32 >= 0) {
7353                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7354                    if (abi64 >= 0) {
7355                        pkg.applicationInfo.secondaryCpuAbi = abi;
7356                    } else {
7357                        pkg.applicationInfo.primaryCpuAbi = abi;
7358                    }
7359                }
7360            } else {
7361                String[] abiList = (cpuAbiOverride != null) ?
7362                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7363
7364                // Enable gross and lame hacks for apps that are built with old
7365                // SDK tools. We must scan their APKs for renderscript bitcode and
7366                // not launch them if it's present. Don't bother checking on devices
7367                // that don't have 64 bit support.
7368                boolean needsRenderScriptOverride = false;
7369                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7370                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7371                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7372                    needsRenderScriptOverride = true;
7373                }
7374
7375                final int copyRet;
7376                if (extractLibs) {
7377                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7378                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7379                } else {
7380                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7381                }
7382
7383                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7384                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7385                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7386                }
7387
7388                if (copyRet >= 0) {
7389                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7390                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7391                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7392                } else if (needsRenderScriptOverride) {
7393                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7394                }
7395            }
7396        } catch (IOException ioe) {
7397            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7398        } finally {
7399            IoUtils.closeQuietly(handle);
7400        }
7401
7402        // Now that we've calculated the ABIs and determined if it's an internal app,
7403        // we will go ahead and populate the nativeLibraryPath.
7404        setNativeLibraryPaths(pkg);
7405    }
7406
7407    /**
7408     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7409     * i.e, so that all packages can be run inside a single process if required.
7410     *
7411     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7412     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7413     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7414     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7415     * updating a package that belongs to a shared user.
7416     *
7417     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7418     * adds unnecessary complexity.
7419     */
7420    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7421            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7422        String requiredInstructionSet = null;
7423        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7424            requiredInstructionSet = VMRuntime.getInstructionSet(
7425                     scannedPackage.applicationInfo.primaryCpuAbi);
7426        }
7427
7428        PackageSetting requirer = null;
7429        for (PackageSetting ps : packagesForUser) {
7430            // If packagesForUser contains scannedPackage, we skip it. This will happen
7431            // when scannedPackage is an update of an existing package. Without this check,
7432            // we will never be able to change the ABI of any package belonging to a shared
7433            // user, even if it's compatible with other packages.
7434            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7435                if (ps.primaryCpuAbiString == null) {
7436                    continue;
7437                }
7438
7439                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7440                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7441                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7442                    // this but there's not much we can do.
7443                    String errorMessage = "Instruction set mismatch, "
7444                            + ((requirer == null) ? "[caller]" : requirer)
7445                            + " requires " + requiredInstructionSet + " whereas " + ps
7446                            + " requires " + instructionSet;
7447                    Slog.w(TAG, errorMessage);
7448                }
7449
7450                if (requiredInstructionSet == null) {
7451                    requiredInstructionSet = instructionSet;
7452                    requirer = ps;
7453                }
7454            }
7455        }
7456
7457        if (requiredInstructionSet != null) {
7458            String adjustedAbi;
7459            if (requirer != null) {
7460                // requirer != null implies that either scannedPackage was null or that scannedPackage
7461                // did not require an ABI, in which case we have to adjust scannedPackage to match
7462                // the ABI of the set (which is the same as requirer's ABI)
7463                adjustedAbi = requirer.primaryCpuAbiString;
7464                if (scannedPackage != null) {
7465                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7466                }
7467            } else {
7468                // requirer == null implies that we're updating all ABIs in the set to
7469                // match scannedPackage.
7470                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7471            }
7472
7473            for (PackageSetting ps : packagesForUser) {
7474                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7475                    if (ps.primaryCpuAbiString != null) {
7476                        continue;
7477                    }
7478
7479                    ps.primaryCpuAbiString = adjustedAbi;
7480                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7481                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7482                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7483
7484                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7485                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7486                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7487                            ps.primaryCpuAbiString = null;
7488                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7489                            return;
7490                        } else {
7491                            mInstaller.rmdex(ps.codePathString,
7492                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7493                        }
7494                    }
7495                }
7496            }
7497        }
7498    }
7499
7500    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7501        synchronized (mPackages) {
7502            mResolverReplaced = true;
7503            // Set up information for custom user intent resolution activity.
7504            mResolveActivity.applicationInfo = pkg.applicationInfo;
7505            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7506            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7507            mResolveActivity.processName = pkg.applicationInfo.packageName;
7508            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7509            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7510                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7511            mResolveActivity.theme = 0;
7512            mResolveActivity.exported = true;
7513            mResolveActivity.enabled = true;
7514            mResolveInfo.activityInfo = mResolveActivity;
7515            mResolveInfo.priority = 0;
7516            mResolveInfo.preferredOrder = 0;
7517            mResolveInfo.match = 0;
7518            mResolveComponentName = mCustomResolverComponentName;
7519            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7520                    mResolveComponentName);
7521        }
7522    }
7523
7524    private static String calculateBundledApkRoot(final String codePathString) {
7525        final File codePath = new File(codePathString);
7526        final File codeRoot;
7527        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7528            codeRoot = Environment.getRootDirectory();
7529        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7530            codeRoot = Environment.getOemDirectory();
7531        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7532            codeRoot = Environment.getVendorDirectory();
7533        } else {
7534            // Unrecognized code path; take its top real segment as the apk root:
7535            // e.g. /something/app/blah.apk => /something
7536            try {
7537                File f = codePath.getCanonicalFile();
7538                File parent = f.getParentFile();    // non-null because codePath is a file
7539                File tmp;
7540                while ((tmp = parent.getParentFile()) != null) {
7541                    f = parent;
7542                    parent = tmp;
7543                }
7544                codeRoot = f;
7545                Slog.w(TAG, "Unrecognized code path "
7546                        + codePath + " - using " + codeRoot);
7547            } catch (IOException e) {
7548                // Can't canonicalize the code path -- shenanigans?
7549                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7550                return Environment.getRootDirectory().getPath();
7551            }
7552        }
7553        return codeRoot.getPath();
7554    }
7555
7556    /**
7557     * Derive and set the location of native libraries for the given package,
7558     * which varies depending on where and how the package was installed.
7559     */
7560    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7561        final ApplicationInfo info = pkg.applicationInfo;
7562        final String codePath = pkg.codePath;
7563        final File codeFile = new File(codePath);
7564        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7565        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7566
7567        info.nativeLibraryRootDir = null;
7568        info.nativeLibraryRootRequiresIsa = false;
7569        info.nativeLibraryDir = null;
7570        info.secondaryNativeLibraryDir = null;
7571
7572        if (isApkFile(codeFile)) {
7573            // Monolithic install
7574            if (bundledApp) {
7575                // If "/system/lib64/apkname" exists, assume that is the per-package
7576                // native library directory to use; otherwise use "/system/lib/apkname".
7577                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7578                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7579                        getPrimaryInstructionSet(info));
7580
7581                // This is a bundled system app so choose the path based on the ABI.
7582                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7583                // is just the default path.
7584                final String apkName = deriveCodePathName(codePath);
7585                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7586                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7587                        apkName).getAbsolutePath();
7588
7589                if (info.secondaryCpuAbi != null) {
7590                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7591                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7592                            secondaryLibDir, apkName).getAbsolutePath();
7593                }
7594            } else if (asecApp) {
7595                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7596                        .getAbsolutePath();
7597            } else {
7598                final String apkName = deriveCodePathName(codePath);
7599                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7600                        .getAbsolutePath();
7601            }
7602
7603            info.nativeLibraryRootRequiresIsa = false;
7604            info.nativeLibraryDir = info.nativeLibraryRootDir;
7605        } else {
7606            // Cluster install
7607            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7608            info.nativeLibraryRootRequiresIsa = true;
7609
7610            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7611                    getPrimaryInstructionSet(info)).getAbsolutePath();
7612
7613            if (info.secondaryCpuAbi != null) {
7614                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7615                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7616            }
7617        }
7618    }
7619
7620    /**
7621     * Calculate the abis and roots for a bundled app. These can uniquely
7622     * be determined from the contents of the system partition, i.e whether
7623     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7624     * of this information, and instead assume that the system was built
7625     * sensibly.
7626     */
7627    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7628                                           PackageSetting pkgSetting) {
7629        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7630
7631        // If "/system/lib64/apkname" exists, assume that is the per-package
7632        // native library directory to use; otherwise use "/system/lib/apkname".
7633        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7634        setBundledAppAbi(pkg, apkRoot, apkName);
7635        // pkgSetting might be null during rescan following uninstall of updates
7636        // to a bundled app, so accommodate that possibility.  The settings in
7637        // that case will be established later from the parsed package.
7638        //
7639        // If the settings aren't null, sync them up with what we've just derived.
7640        // note that apkRoot isn't stored in the package settings.
7641        if (pkgSetting != null) {
7642            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7643            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7644        }
7645    }
7646
7647    /**
7648     * Deduces the ABI of a bundled app and sets the relevant fields on the
7649     * parsed pkg object.
7650     *
7651     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7652     *        under which system libraries are installed.
7653     * @param apkName the name of the installed package.
7654     */
7655    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7656        final File codeFile = new File(pkg.codePath);
7657
7658        final boolean has64BitLibs;
7659        final boolean has32BitLibs;
7660        if (isApkFile(codeFile)) {
7661            // Monolithic install
7662            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7663            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7664        } else {
7665            // Cluster install
7666            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7667            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7668                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7669                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7670                has64BitLibs = (new File(rootDir, isa)).exists();
7671            } else {
7672                has64BitLibs = false;
7673            }
7674            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7675                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7676                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7677                has32BitLibs = (new File(rootDir, isa)).exists();
7678            } else {
7679                has32BitLibs = false;
7680            }
7681        }
7682
7683        if (has64BitLibs && !has32BitLibs) {
7684            // The package has 64 bit libs, but not 32 bit libs. Its primary
7685            // ABI should be 64 bit. We can safely assume here that the bundled
7686            // native libraries correspond to the most preferred ABI in the list.
7687
7688            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7689            pkg.applicationInfo.secondaryCpuAbi = null;
7690        } else if (has32BitLibs && !has64BitLibs) {
7691            // The package has 32 bit libs but not 64 bit libs. Its primary
7692            // ABI should be 32 bit.
7693
7694            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7695            pkg.applicationInfo.secondaryCpuAbi = null;
7696        } else if (has32BitLibs && has64BitLibs) {
7697            // The application has both 64 and 32 bit bundled libraries. We check
7698            // here that the app declares multiArch support, and warn if it doesn't.
7699            //
7700            // We will be lenient here and record both ABIs. The primary will be the
7701            // ABI that's higher on the list, i.e, a device that's configured to prefer
7702            // 64 bit apps will see a 64 bit primary ABI,
7703
7704            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7705                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7706            }
7707
7708            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7709                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7710                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7711            } else {
7712                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7713                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7714            }
7715        } else {
7716            pkg.applicationInfo.primaryCpuAbi = null;
7717            pkg.applicationInfo.secondaryCpuAbi = null;
7718        }
7719    }
7720
7721    private void killApplication(String pkgName, int appId, String reason) {
7722        // Request the ActivityManager to kill the process(only for existing packages)
7723        // so that we do not end up in a confused state while the user is still using the older
7724        // version of the application while the new one gets installed.
7725        IActivityManager am = ActivityManagerNative.getDefault();
7726        if (am != null) {
7727            try {
7728                am.killApplicationWithAppId(pkgName, appId, reason);
7729            } catch (RemoteException e) {
7730            }
7731        }
7732    }
7733
7734    void removePackageLI(PackageSetting ps, boolean chatty) {
7735        if (DEBUG_INSTALL) {
7736            if (chatty)
7737                Log.d(TAG, "Removing package " + ps.name);
7738        }
7739
7740        // writer
7741        synchronized (mPackages) {
7742            mPackages.remove(ps.name);
7743            final PackageParser.Package pkg = ps.pkg;
7744            if (pkg != null) {
7745                cleanPackageDataStructuresLILPw(pkg, chatty);
7746            }
7747        }
7748    }
7749
7750    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7751        if (DEBUG_INSTALL) {
7752            if (chatty)
7753                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7754        }
7755
7756        // writer
7757        synchronized (mPackages) {
7758            mPackages.remove(pkg.applicationInfo.packageName);
7759            cleanPackageDataStructuresLILPw(pkg, chatty);
7760        }
7761    }
7762
7763    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7764        int N = pkg.providers.size();
7765        StringBuilder r = null;
7766        int i;
7767        for (i=0; i<N; i++) {
7768            PackageParser.Provider p = pkg.providers.get(i);
7769            mProviders.removeProvider(p);
7770            if (p.info.authority == null) {
7771
7772                /* There was another ContentProvider with this authority when
7773                 * this app was installed so this authority is null,
7774                 * Ignore it as we don't have to unregister the provider.
7775                 */
7776                continue;
7777            }
7778            String names[] = p.info.authority.split(";");
7779            for (int j = 0; j < names.length; j++) {
7780                if (mProvidersByAuthority.get(names[j]) == p) {
7781                    mProvidersByAuthority.remove(names[j]);
7782                    if (DEBUG_REMOVE) {
7783                        if (chatty)
7784                            Log.d(TAG, "Unregistered content provider: " + names[j]
7785                                    + ", className = " + p.info.name + ", isSyncable = "
7786                                    + p.info.isSyncable);
7787                    }
7788                }
7789            }
7790            if (DEBUG_REMOVE && chatty) {
7791                if (r == null) {
7792                    r = new StringBuilder(256);
7793                } else {
7794                    r.append(' ');
7795                }
7796                r.append(p.info.name);
7797            }
7798        }
7799        if (r != null) {
7800            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7801        }
7802
7803        N = pkg.services.size();
7804        r = null;
7805        for (i=0; i<N; i++) {
7806            PackageParser.Service s = pkg.services.get(i);
7807            mServices.removeService(s);
7808            if (chatty) {
7809                if (r == null) {
7810                    r = new StringBuilder(256);
7811                } else {
7812                    r.append(' ');
7813                }
7814                r.append(s.info.name);
7815            }
7816        }
7817        if (r != null) {
7818            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7819        }
7820
7821        N = pkg.receivers.size();
7822        r = null;
7823        for (i=0; i<N; i++) {
7824            PackageParser.Activity a = pkg.receivers.get(i);
7825            mReceivers.removeActivity(a, "receiver");
7826            if (DEBUG_REMOVE && chatty) {
7827                if (r == null) {
7828                    r = new StringBuilder(256);
7829                } else {
7830                    r.append(' ');
7831                }
7832                r.append(a.info.name);
7833            }
7834        }
7835        if (r != null) {
7836            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7837        }
7838
7839        N = pkg.activities.size();
7840        r = null;
7841        for (i=0; i<N; i++) {
7842            PackageParser.Activity a = pkg.activities.get(i);
7843            mActivities.removeActivity(a, "activity");
7844            if (DEBUG_REMOVE && chatty) {
7845                if (r == null) {
7846                    r = new StringBuilder(256);
7847                } else {
7848                    r.append(' ');
7849                }
7850                r.append(a.info.name);
7851            }
7852        }
7853        if (r != null) {
7854            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7855        }
7856
7857        N = pkg.permissions.size();
7858        r = null;
7859        for (i=0; i<N; i++) {
7860            PackageParser.Permission p = pkg.permissions.get(i);
7861            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7862            if (bp == null) {
7863                bp = mSettings.mPermissionTrees.get(p.info.name);
7864            }
7865            if (bp != null && bp.perm == p) {
7866                bp.perm = null;
7867                if (DEBUG_REMOVE && chatty) {
7868                    if (r == null) {
7869                        r = new StringBuilder(256);
7870                    } else {
7871                        r.append(' ');
7872                    }
7873                    r.append(p.info.name);
7874                }
7875            }
7876            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7877                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7878                if (appOpPerms != null) {
7879                    appOpPerms.remove(pkg.packageName);
7880                }
7881            }
7882        }
7883        if (r != null) {
7884            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7885        }
7886
7887        N = pkg.requestedPermissions.size();
7888        r = null;
7889        for (i=0; i<N; i++) {
7890            String perm = pkg.requestedPermissions.get(i);
7891            BasePermission bp = mSettings.mPermissions.get(perm);
7892            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7893                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7894                if (appOpPerms != null) {
7895                    appOpPerms.remove(pkg.packageName);
7896                    if (appOpPerms.isEmpty()) {
7897                        mAppOpPermissionPackages.remove(perm);
7898                    }
7899                }
7900            }
7901        }
7902        if (r != null) {
7903            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7904        }
7905
7906        N = pkg.instrumentation.size();
7907        r = null;
7908        for (i=0; i<N; i++) {
7909            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7910            mInstrumentation.remove(a.getComponentName());
7911            if (DEBUG_REMOVE && chatty) {
7912                if (r == null) {
7913                    r = new StringBuilder(256);
7914                } else {
7915                    r.append(' ');
7916                }
7917                r.append(a.info.name);
7918            }
7919        }
7920        if (r != null) {
7921            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7922        }
7923
7924        r = null;
7925        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7926            // Only system apps can hold shared libraries.
7927            if (pkg.libraryNames != null) {
7928                for (i=0; i<pkg.libraryNames.size(); i++) {
7929                    String name = pkg.libraryNames.get(i);
7930                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7931                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7932                        mSharedLibraries.remove(name);
7933                        if (DEBUG_REMOVE && chatty) {
7934                            if (r == null) {
7935                                r = new StringBuilder(256);
7936                            } else {
7937                                r.append(' ');
7938                            }
7939                            r.append(name);
7940                        }
7941                    }
7942                }
7943            }
7944        }
7945        if (r != null) {
7946            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7947        }
7948    }
7949
7950    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7951        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7952            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7953                return true;
7954            }
7955        }
7956        return false;
7957    }
7958
7959    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7960    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7961    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7962
7963    private void updatePermissionsLPw(String changingPkg,
7964            PackageParser.Package pkgInfo, int flags) {
7965        // Make sure there are no dangling permission trees.
7966        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7967        while (it.hasNext()) {
7968            final BasePermission bp = it.next();
7969            if (bp.packageSetting == null) {
7970                // We may not yet have parsed the package, so just see if
7971                // we still know about its settings.
7972                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7973            }
7974            if (bp.packageSetting == null) {
7975                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7976                        + " from package " + bp.sourcePackage);
7977                it.remove();
7978            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7979                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7980                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7981                            + " from package " + bp.sourcePackage);
7982                    flags |= UPDATE_PERMISSIONS_ALL;
7983                    it.remove();
7984                }
7985            }
7986        }
7987
7988        // Make sure all dynamic permissions have been assigned to a package,
7989        // and make sure there are no dangling permissions.
7990        it = mSettings.mPermissions.values().iterator();
7991        while (it.hasNext()) {
7992            final BasePermission bp = it.next();
7993            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7994                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7995                        + bp.name + " pkg=" + bp.sourcePackage
7996                        + " info=" + bp.pendingInfo);
7997                if (bp.packageSetting == null && bp.pendingInfo != null) {
7998                    final BasePermission tree = findPermissionTreeLP(bp.name);
7999                    if (tree != null && tree.perm != null) {
8000                        bp.packageSetting = tree.packageSetting;
8001                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8002                                new PermissionInfo(bp.pendingInfo));
8003                        bp.perm.info.packageName = tree.perm.info.packageName;
8004                        bp.perm.info.name = bp.name;
8005                        bp.uid = tree.uid;
8006                    }
8007                }
8008            }
8009            if (bp.packageSetting == null) {
8010                // We may not yet have parsed the package, so just see if
8011                // we still know about its settings.
8012                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8013            }
8014            if (bp.packageSetting == null) {
8015                Slog.w(TAG, "Removing dangling permission: " + bp.name
8016                        + " from package " + bp.sourcePackage);
8017                it.remove();
8018            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8019                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8020                    Slog.i(TAG, "Removing old permission: " + bp.name
8021                            + " from package " + bp.sourcePackage);
8022                    flags |= UPDATE_PERMISSIONS_ALL;
8023                    it.remove();
8024                }
8025            }
8026        }
8027
8028        // Now update the permissions for all packages, in particular
8029        // replace the granted permissions of the system packages.
8030        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8031            for (PackageParser.Package pkg : mPackages.values()) {
8032                if (pkg != pkgInfo) {
8033                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8034                            changingPkg);
8035                }
8036            }
8037        }
8038
8039        if (pkgInfo != null) {
8040            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8041        }
8042    }
8043
8044    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8045            String packageOfInterest) {
8046        // IMPORTANT: There are two types of permissions: install and runtime.
8047        // Install time permissions are granted when the app is installed to
8048        // all device users and users added in the future. Runtime permissions
8049        // are granted at runtime explicitly to specific users. Normal and signature
8050        // protected permissions are install time permissions. Dangerous permissions
8051        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8052        // otherwise they are runtime permissions. This function does not manage
8053        // runtime permissions except for the case an app targeting Lollipop MR1
8054        // being upgraded to target a newer SDK, in which case dangerous permissions
8055        // are transformed from install time to runtime ones.
8056
8057        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8058        if (ps == null) {
8059            return;
8060        }
8061
8062        PermissionsState permissionsState = ps.getPermissionsState();
8063        PermissionsState origPermissions = permissionsState;
8064
8065        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8066
8067        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8068
8069        boolean changedInstallPermission = false;
8070
8071        if (replace) {
8072            ps.installPermissionsFixed = false;
8073            if (!ps.isSharedUser()) {
8074                origPermissions = new PermissionsState(permissionsState);
8075                permissionsState.reset();
8076            }
8077        }
8078
8079        permissionsState.setGlobalGids(mGlobalGids);
8080
8081        final int N = pkg.requestedPermissions.size();
8082        for (int i=0; i<N; i++) {
8083            final String name = pkg.requestedPermissions.get(i);
8084            final BasePermission bp = mSettings.mPermissions.get(name);
8085
8086            if (DEBUG_INSTALL) {
8087                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8088            }
8089
8090            if (bp == null || bp.packageSetting == null) {
8091                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8092                    Slog.w(TAG, "Unknown permission " + name
8093                            + " in package " + pkg.packageName);
8094                }
8095                continue;
8096            }
8097
8098            final String perm = bp.name;
8099            boolean allowedSig = false;
8100            int grant = GRANT_DENIED;
8101
8102            // Keep track of app op permissions.
8103            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8104                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8105                if (pkgs == null) {
8106                    pkgs = new ArraySet<>();
8107                    mAppOpPermissionPackages.put(bp.name, pkgs);
8108                }
8109                pkgs.add(pkg.packageName);
8110            }
8111
8112            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8113            switch (level) {
8114                case PermissionInfo.PROTECTION_NORMAL: {
8115                    // For all apps normal permissions are install time ones.
8116                    grant = GRANT_INSTALL;
8117                } break;
8118
8119                case PermissionInfo.PROTECTION_DANGEROUS: {
8120                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8121                        // For legacy apps dangerous permissions are install time ones.
8122                        grant = GRANT_INSTALL_LEGACY;
8123                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8124                        // For legacy apps that became modern, install becomes runtime.
8125                        grant = GRANT_UPGRADE;
8126                    } else {
8127                        // For modern apps keep runtime permissions unchanged.
8128                        grant = GRANT_RUNTIME;
8129                    }
8130                } break;
8131
8132                case PermissionInfo.PROTECTION_SIGNATURE: {
8133                    // For all apps signature permissions are install time ones.
8134                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8135                    if (allowedSig) {
8136                        grant = GRANT_INSTALL;
8137                    }
8138                } break;
8139            }
8140
8141            if (DEBUG_INSTALL) {
8142                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8143            }
8144
8145            if (grant != GRANT_DENIED) {
8146                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8147                    // If this is an existing, non-system package, then
8148                    // we can't add any new permissions to it.
8149                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8150                        // Except...  if this is a permission that was added
8151                        // to the platform (note: need to only do this when
8152                        // updating the platform).
8153                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8154                            grant = GRANT_DENIED;
8155                        }
8156                    }
8157                }
8158
8159                switch (grant) {
8160                    case GRANT_INSTALL: {
8161                        // Revoke this as runtime permission to handle the case of
8162                        // a runtime permission being downgraded to an install one.
8163                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8164                            if (origPermissions.getRuntimePermissionState(
8165                                    bp.name, userId) != null) {
8166                                // Revoke the runtime permission and clear the flags.
8167                                origPermissions.revokeRuntimePermission(bp, userId);
8168                                origPermissions.updatePermissionFlags(bp, userId,
8169                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8170                                // If we revoked a permission permission, we have to write.
8171                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8172                                        changedRuntimePermissionUserIds, userId);
8173                            }
8174                        }
8175                        // Grant an install permission.
8176                        if (permissionsState.grantInstallPermission(bp) !=
8177                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8178                            changedInstallPermission = true;
8179                        }
8180                    } break;
8181
8182                    case GRANT_INSTALL_LEGACY: {
8183                        // Grant an install permission.
8184                        if (permissionsState.grantInstallPermission(bp) !=
8185                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8186                            changedInstallPermission = true;
8187                        }
8188                    } break;
8189
8190                    case GRANT_RUNTIME: {
8191                        // Grant previously granted runtime permissions.
8192                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8193                            PermissionState permissionState = origPermissions
8194                                    .getRuntimePermissionState(bp.name, userId);
8195                            final int flags = permissionState != null
8196                                    ? permissionState.getFlags() : 0;
8197                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8198                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8199                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8200                                    // If we cannot put the permission as it was, we have to write.
8201                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8202                                            changedRuntimePermissionUserIds, userId);
8203                                }
8204                            }
8205                            // Propagate the permission flags.
8206                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8207                        }
8208                    } break;
8209
8210                    case GRANT_UPGRADE: {
8211                        // Grant runtime permissions for a previously held install permission.
8212                        PermissionState permissionState = origPermissions
8213                                .getInstallPermissionState(bp.name);
8214                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8215
8216                        if (origPermissions.revokeInstallPermission(bp)
8217                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8218                            // We will be transferring the permission flags, so clear them.
8219                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8220                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8221                            changedInstallPermission = true;
8222                        }
8223
8224                        // If the permission is not to be promoted to runtime we ignore it and
8225                        // also its other flags as they are not applicable to install permissions.
8226                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8227                            for (int userId : currentUserIds) {
8228                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8229                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8230                                    // Transfer the permission flags.
8231                                    permissionsState.updatePermissionFlags(bp, userId,
8232                                            flags, flags);
8233                                    // If we granted the permission, we have to write.
8234                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8235                                            changedRuntimePermissionUserIds, userId);
8236                                }
8237                            }
8238                        }
8239                    } break;
8240
8241                    default: {
8242                        if (packageOfInterest == null
8243                                || packageOfInterest.equals(pkg.packageName)) {
8244                            Slog.w(TAG, "Not granting permission " + perm
8245                                    + " to package " + pkg.packageName
8246                                    + " because it was previously installed without");
8247                        }
8248                    } break;
8249                }
8250            } else {
8251                if (permissionsState.revokeInstallPermission(bp) !=
8252                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8253                    // Also drop the permission flags.
8254                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8255                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8256                    changedInstallPermission = true;
8257                    Slog.i(TAG, "Un-granting permission " + perm
8258                            + " from package " + pkg.packageName
8259                            + " (protectionLevel=" + bp.protectionLevel
8260                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8261                            + ")");
8262                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8263                    // Don't print warning for app op permissions, since it is fine for them
8264                    // not to be granted, there is a UI for the user to decide.
8265                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8266                        Slog.w(TAG, "Not granting permission " + perm
8267                                + " to package " + pkg.packageName
8268                                + " (protectionLevel=" + bp.protectionLevel
8269                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8270                                + ")");
8271                    }
8272                }
8273            }
8274        }
8275
8276        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8277                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8278            // This is the first that we have heard about this package, so the
8279            // permissions we have now selected are fixed until explicitly
8280            // changed.
8281            ps.installPermissionsFixed = true;
8282        }
8283
8284        // Persist the runtime permissions state for users with changes.
8285        for (int userId : changedRuntimePermissionUserIds) {
8286            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8287        }
8288    }
8289
8290    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8291        boolean allowed = false;
8292        final int NP = PackageParser.NEW_PERMISSIONS.length;
8293        for (int ip=0; ip<NP; ip++) {
8294            final PackageParser.NewPermissionInfo npi
8295                    = PackageParser.NEW_PERMISSIONS[ip];
8296            if (npi.name.equals(perm)
8297                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8298                allowed = true;
8299                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8300                        + pkg.packageName);
8301                break;
8302            }
8303        }
8304        return allowed;
8305    }
8306
8307    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8308            BasePermission bp, PermissionsState origPermissions) {
8309        boolean allowed;
8310        allowed = (compareSignatures(
8311                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8312                        == PackageManager.SIGNATURE_MATCH)
8313                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8314                        == PackageManager.SIGNATURE_MATCH);
8315        if (!allowed && (bp.protectionLevel
8316                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
8317            if (isSystemApp(pkg)) {
8318                // For updated system applications, a system permission
8319                // is granted only if it had been defined by the original application.
8320                if (pkg.isUpdatedSystemApp()) {
8321                    final PackageSetting sysPs = mSettings
8322                            .getDisabledSystemPkgLPr(pkg.packageName);
8323                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8324                        // If the original was granted this permission, we take
8325                        // that grant decision as read and propagate it to the
8326                        // update.
8327                        if (sysPs.isPrivileged()) {
8328                            allowed = true;
8329                        }
8330                    } else {
8331                        // The system apk may have been updated with an older
8332                        // version of the one on the data partition, but which
8333                        // granted a new system permission that it didn't have
8334                        // before.  In this case we do want to allow the app to
8335                        // now get the new permission if the ancestral apk is
8336                        // privileged to get it.
8337                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8338                            for (int j=0;
8339                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8340                                if (perm.equals(
8341                                        sysPs.pkg.requestedPermissions.get(j))) {
8342                                    allowed = true;
8343                                    break;
8344                                }
8345                            }
8346                        }
8347                    }
8348                } else {
8349                    allowed = isPrivilegedApp(pkg);
8350                }
8351            }
8352        }
8353        if (!allowed && (bp.protectionLevel
8354                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8355            // For development permissions, a development permission
8356            // is granted only if it was already granted.
8357            allowed = origPermissions.hasInstallPermission(perm);
8358        }
8359        return allowed;
8360    }
8361
8362    final class ActivityIntentResolver
8363            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8364        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8365                boolean defaultOnly, int userId) {
8366            if (!sUserManager.exists(userId)) return null;
8367            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8368            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8369        }
8370
8371        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8372                int userId) {
8373            if (!sUserManager.exists(userId)) return null;
8374            mFlags = flags;
8375            return super.queryIntent(intent, resolvedType,
8376                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8377        }
8378
8379        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8380                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8381            if (!sUserManager.exists(userId)) return null;
8382            if (packageActivities == null) {
8383                return null;
8384            }
8385            mFlags = flags;
8386            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8387            final int N = packageActivities.size();
8388            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8389                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8390
8391            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8392            for (int i = 0; i < N; ++i) {
8393                intentFilters = packageActivities.get(i).intents;
8394                if (intentFilters != null && intentFilters.size() > 0) {
8395                    PackageParser.ActivityIntentInfo[] array =
8396                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8397                    intentFilters.toArray(array);
8398                    listCut.add(array);
8399                }
8400            }
8401            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8402        }
8403
8404        public final void addActivity(PackageParser.Activity a, String type) {
8405            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8406            mActivities.put(a.getComponentName(), a);
8407            if (DEBUG_SHOW_INFO)
8408                Log.v(
8409                TAG, "  " + type + " " +
8410                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8411            if (DEBUG_SHOW_INFO)
8412                Log.v(TAG, "    Class=" + a.info.name);
8413            final int NI = a.intents.size();
8414            for (int j=0; j<NI; j++) {
8415                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8416                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8417                    intent.setPriority(0);
8418                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8419                            + a.className + " with priority > 0, forcing to 0");
8420                }
8421                if (DEBUG_SHOW_INFO) {
8422                    Log.v(TAG, "    IntentFilter:");
8423                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8424                }
8425                if (!intent.debugCheck()) {
8426                    Log.w(TAG, "==> For Activity " + a.info.name);
8427                }
8428                addFilter(intent);
8429            }
8430        }
8431
8432        public final void removeActivity(PackageParser.Activity a, String type) {
8433            mActivities.remove(a.getComponentName());
8434            if (DEBUG_SHOW_INFO) {
8435                Log.v(TAG, "  " + type + " "
8436                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8437                                : a.info.name) + ":");
8438                Log.v(TAG, "    Class=" + a.info.name);
8439            }
8440            final int NI = a.intents.size();
8441            for (int j=0; j<NI; j++) {
8442                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8443                if (DEBUG_SHOW_INFO) {
8444                    Log.v(TAG, "    IntentFilter:");
8445                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8446                }
8447                removeFilter(intent);
8448            }
8449        }
8450
8451        @Override
8452        protected boolean allowFilterResult(
8453                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8454            ActivityInfo filterAi = filter.activity.info;
8455            for (int i=dest.size()-1; i>=0; i--) {
8456                ActivityInfo destAi = dest.get(i).activityInfo;
8457                if (destAi.name == filterAi.name
8458                        && destAi.packageName == filterAi.packageName) {
8459                    return false;
8460                }
8461            }
8462            return true;
8463        }
8464
8465        @Override
8466        protected ActivityIntentInfo[] newArray(int size) {
8467            return new ActivityIntentInfo[size];
8468        }
8469
8470        @Override
8471        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8472            if (!sUserManager.exists(userId)) return true;
8473            PackageParser.Package p = filter.activity.owner;
8474            if (p != null) {
8475                PackageSetting ps = (PackageSetting)p.mExtras;
8476                if (ps != null) {
8477                    // System apps are never considered stopped for purposes of
8478                    // filtering, because there may be no way for the user to
8479                    // actually re-launch them.
8480                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8481                            && ps.getStopped(userId);
8482                }
8483            }
8484            return false;
8485        }
8486
8487        @Override
8488        protected boolean isPackageForFilter(String packageName,
8489                PackageParser.ActivityIntentInfo info) {
8490            return packageName.equals(info.activity.owner.packageName);
8491        }
8492
8493        @Override
8494        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8495                int match, int userId) {
8496            if (!sUserManager.exists(userId)) return null;
8497            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8498                return null;
8499            }
8500            final PackageParser.Activity activity = info.activity;
8501            if (mSafeMode && (activity.info.applicationInfo.flags
8502                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8503                return null;
8504            }
8505            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8506            if (ps == null) {
8507                return null;
8508            }
8509            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8510                    ps.readUserState(userId), userId);
8511            if (ai == null) {
8512                return null;
8513            }
8514            final ResolveInfo res = new ResolveInfo();
8515            res.activityInfo = ai;
8516            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8517                res.filter = info;
8518            }
8519            if (info != null) {
8520                res.handleAllWebDataURI = info.handleAllWebDataURI();
8521            }
8522            res.priority = info.getPriority();
8523            res.preferredOrder = activity.owner.mPreferredOrder;
8524            //System.out.println("Result: " + res.activityInfo.className +
8525            //                   " = " + res.priority);
8526            res.match = match;
8527            res.isDefault = info.hasDefault;
8528            res.labelRes = info.labelRes;
8529            res.nonLocalizedLabel = info.nonLocalizedLabel;
8530            if (userNeedsBadging(userId)) {
8531                res.noResourceId = true;
8532            } else {
8533                res.icon = info.icon;
8534            }
8535            res.iconResourceId = info.icon;
8536            res.system = res.activityInfo.applicationInfo.isSystemApp();
8537            return res;
8538        }
8539
8540        @Override
8541        protected void sortResults(List<ResolveInfo> results) {
8542            Collections.sort(results, mResolvePrioritySorter);
8543        }
8544
8545        @Override
8546        protected void dumpFilter(PrintWriter out, String prefix,
8547                PackageParser.ActivityIntentInfo filter) {
8548            out.print(prefix); out.print(
8549                    Integer.toHexString(System.identityHashCode(filter.activity)));
8550                    out.print(' ');
8551                    filter.activity.printComponentShortName(out);
8552                    out.print(" filter ");
8553                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8554        }
8555
8556        @Override
8557        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8558            return filter.activity;
8559        }
8560
8561        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8562            PackageParser.Activity activity = (PackageParser.Activity)label;
8563            out.print(prefix); out.print(
8564                    Integer.toHexString(System.identityHashCode(activity)));
8565                    out.print(' ');
8566                    activity.printComponentShortName(out);
8567            if (count > 1) {
8568                out.print(" ("); out.print(count); out.print(" filters)");
8569            }
8570            out.println();
8571        }
8572
8573//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8574//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8575//            final List<ResolveInfo> retList = Lists.newArrayList();
8576//            while (i.hasNext()) {
8577//                final ResolveInfo resolveInfo = i.next();
8578//                if (isEnabledLP(resolveInfo.activityInfo)) {
8579//                    retList.add(resolveInfo);
8580//                }
8581//            }
8582//            return retList;
8583//        }
8584
8585        // Keys are String (activity class name), values are Activity.
8586        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8587                = new ArrayMap<ComponentName, PackageParser.Activity>();
8588        private int mFlags;
8589    }
8590
8591    private final class ServiceIntentResolver
8592            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8593        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8594                boolean defaultOnly, int userId) {
8595            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8596            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8597        }
8598
8599        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8600                int userId) {
8601            if (!sUserManager.exists(userId)) return null;
8602            mFlags = flags;
8603            return super.queryIntent(intent, resolvedType,
8604                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8605        }
8606
8607        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8608                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8609            if (!sUserManager.exists(userId)) return null;
8610            if (packageServices == null) {
8611                return null;
8612            }
8613            mFlags = flags;
8614            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8615            final int N = packageServices.size();
8616            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8617                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8618
8619            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8620            for (int i = 0; i < N; ++i) {
8621                intentFilters = packageServices.get(i).intents;
8622                if (intentFilters != null && intentFilters.size() > 0) {
8623                    PackageParser.ServiceIntentInfo[] array =
8624                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8625                    intentFilters.toArray(array);
8626                    listCut.add(array);
8627                }
8628            }
8629            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8630        }
8631
8632        public final void addService(PackageParser.Service s) {
8633            mServices.put(s.getComponentName(), s);
8634            if (DEBUG_SHOW_INFO) {
8635                Log.v(TAG, "  "
8636                        + (s.info.nonLocalizedLabel != null
8637                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8638                Log.v(TAG, "    Class=" + s.info.name);
8639            }
8640            final int NI = s.intents.size();
8641            int j;
8642            for (j=0; j<NI; j++) {
8643                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8644                if (DEBUG_SHOW_INFO) {
8645                    Log.v(TAG, "    IntentFilter:");
8646                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8647                }
8648                if (!intent.debugCheck()) {
8649                    Log.w(TAG, "==> For Service " + s.info.name);
8650                }
8651                addFilter(intent);
8652            }
8653        }
8654
8655        public final void removeService(PackageParser.Service s) {
8656            mServices.remove(s.getComponentName());
8657            if (DEBUG_SHOW_INFO) {
8658                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8659                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8660                Log.v(TAG, "    Class=" + s.info.name);
8661            }
8662            final int NI = s.intents.size();
8663            int j;
8664            for (j=0; j<NI; j++) {
8665                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8666                if (DEBUG_SHOW_INFO) {
8667                    Log.v(TAG, "    IntentFilter:");
8668                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8669                }
8670                removeFilter(intent);
8671            }
8672        }
8673
8674        @Override
8675        protected boolean allowFilterResult(
8676                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8677            ServiceInfo filterSi = filter.service.info;
8678            for (int i=dest.size()-1; i>=0; i--) {
8679                ServiceInfo destAi = dest.get(i).serviceInfo;
8680                if (destAi.name == filterSi.name
8681                        && destAi.packageName == filterSi.packageName) {
8682                    return false;
8683                }
8684            }
8685            return true;
8686        }
8687
8688        @Override
8689        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8690            return new PackageParser.ServiceIntentInfo[size];
8691        }
8692
8693        @Override
8694        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8695            if (!sUserManager.exists(userId)) return true;
8696            PackageParser.Package p = filter.service.owner;
8697            if (p != null) {
8698                PackageSetting ps = (PackageSetting)p.mExtras;
8699                if (ps != null) {
8700                    // System apps are never considered stopped for purposes of
8701                    // filtering, because there may be no way for the user to
8702                    // actually re-launch them.
8703                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8704                            && ps.getStopped(userId);
8705                }
8706            }
8707            return false;
8708        }
8709
8710        @Override
8711        protected boolean isPackageForFilter(String packageName,
8712                PackageParser.ServiceIntentInfo info) {
8713            return packageName.equals(info.service.owner.packageName);
8714        }
8715
8716        @Override
8717        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8718                int match, int userId) {
8719            if (!sUserManager.exists(userId)) return null;
8720            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8721            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8722                return null;
8723            }
8724            final PackageParser.Service service = info.service;
8725            if (mSafeMode && (service.info.applicationInfo.flags
8726                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8727                return null;
8728            }
8729            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8730            if (ps == null) {
8731                return null;
8732            }
8733            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8734                    ps.readUserState(userId), userId);
8735            if (si == null) {
8736                return null;
8737            }
8738            final ResolveInfo res = new ResolveInfo();
8739            res.serviceInfo = si;
8740            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8741                res.filter = filter;
8742            }
8743            res.priority = info.getPriority();
8744            res.preferredOrder = service.owner.mPreferredOrder;
8745            res.match = match;
8746            res.isDefault = info.hasDefault;
8747            res.labelRes = info.labelRes;
8748            res.nonLocalizedLabel = info.nonLocalizedLabel;
8749            res.icon = info.icon;
8750            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8751            return res;
8752        }
8753
8754        @Override
8755        protected void sortResults(List<ResolveInfo> results) {
8756            Collections.sort(results, mResolvePrioritySorter);
8757        }
8758
8759        @Override
8760        protected void dumpFilter(PrintWriter out, String prefix,
8761                PackageParser.ServiceIntentInfo filter) {
8762            out.print(prefix); out.print(
8763                    Integer.toHexString(System.identityHashCode(filter.service)));
8764                    out.print(' ');
8765                    filter.service.printComponentShortName(out);
8766                    out.print(" filter ");
8767                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8768        }
8769
8770        @Override
8771        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8772            return filter.service;
8773        }
8774
8775        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8776            PackageParser.Service service = (PackageParser.Service)label;
8777            out.print(prefix); out.print(
8778                    Integer.toHexString(System.identityHashCode(service)));
8779                    out.print(' ');
8780                    service.printComponentShortName(out);
8781            if (count > 1) {
8782                out.print(" ("); out.print(count); out.print(" filters)");
8783            }
8784            out.println();
8785        }
8786
8787//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8788//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8789//            final List<ResolveInfo> retList = Lists.newArrayList();
8790//            while (i.hasNext()) {
8791//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8792//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8793//                    retList.add(resolveInfo);
8794//                }
8795//            }
8796//            return retList;
8797//        }
8798
8799        // Keys are String (activity class name), values are Activity.
8800        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8801                = new ArrayMap<ComponentName, PackageParser.Service>();
8802        private int mFlags;
8803    };
8804
8805    private final class ProviderIntentResolver
8806            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8807        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8808                boolean defaultOnly, int userId) {
8809            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8810            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8811        }
8812
8813        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8814                int userId) {
8815            if (!sUserManager.exists(userId))
8816                return null;
8817            mFlags = flags;
8818            return super.queryIntent(intent, resolvedType,
8819                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8820        }
8821
8822        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8823                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8824            if (!sUserManager.exists(userId))
8825                return null;
8826            if (packageProviders == null) {
8827                return null;
8828            }
8829            mFlags = flags;
8830            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8831            final int N = packageProviders.size();
8832            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8833                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8834
8835            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8836            for (int i = 0; i < N; ++i) {
8837                intentFilters = packageProviders.get(i).intents;
8838                if (intentFilters != null && intentFilters.size() > 0) {
8839                    PackageParser.ProviderIntentInfo[] array =
8840                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8841                    intentFilters.toArray(array);
8842                    listCut.add(array);
8843                }
8844            }
8845            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8846        }
8847
8848        public final void addProvider(PackageParser.Provider p) {
8849            if (mProviders.containsKey(p.getComponentName())) {
8850                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8851                return;
8852            }
8853
8854            mProviders.put(p.getComponentName(), p);
8855            if (DEBUG_SHOW_INFO) {
8856                Log.v(TAG, "  "
8857                        + (p.info.nonLocalizedLabel != null
8858                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8859                Log.v(TAG, "    Class=" + p.info.name);
8860            }
8861            final int NI = p.intents.size();
8862            int j;
8863            for (j = 0; j < NI; j++) {
8864                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8865                if (DEBUG_SHOW_INFO) {
8866                    Log.v(TAG, "    IntentFilter:");
8867                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8868                }
8869                if (!intent.debugCheck()) {
8870                    Log.w(TAG, "==> For Provider " + p.info.name);
8871                }
8872                addFilter(intent);
8873            }
8874        }
8875
8876        public final void removeProvider(PackageParser.Provider p) {
8877            mProviders.remove(p.getComponentName());
8878            if (DEBUG_SHOW_INFO) {
8879                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8880                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8881                Log.v(TAG, "    Class=" + p.info.name);
8882            }
8883            final int NI = p.intents.size();
8884            int j;
8885            for (j = 0; j < NI; j++) {
8886                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8887                if (DEBUG_SHOW_INFO) {
8888                    Log.v(TAG, "    IntentFilter:");
8889                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8890                }
8891                removeFilter(intent);
8892            }
8893        }
8894
8895        @Override
8896        protected boolean allowFilterResult(
8897                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8898            ProviderInfo filterPi = filter.provider.info;
8899            for (int i = dest.size() - 1; i >= 0; i--) {
8900                ProviderInfo destPi = dest.get(i).providerInfo;
8901                if (destPi.name == filterPi.name
8902                        && destPi.packageName == filterPi.packageName) {
8903                    return false;
8904                }
8905            }
8906            return true;
8907        }
8908
8909        @Override
8910        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8911            return new PackageParser.ProviderIntentInfo[size];
8912        }
8913
8914        @Override
8915        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8916            if (!sUserManager.exists(userId))
8917                return true;
8918            PackageParser.Package p = filter.provider.owner;
8919            if (p != null) {
8920                PackageSetting ps = (PackageSetting) p.mExtras;
8921                if (ps != null) {
8922                    // System apps are never considered stopped for purposes of
8923                    // filtering, because there may be no way for the user to
8924                    // actually re-launch them.
8925                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8926                            && ps.getStopped(userId);
8927                }
8928            }
8929            return false;
8930        }
8931
8932        @Override
8933        protected boolean isPackageForFilter(String packageName,
8934                PackageParser.ProviderIntentInfo info) {
8935            return packageName.equals(info.provider.owner.packageName);
8936        }
8937
8938        @Override
8939        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8940                int match, int userId) {
8941            if (!sUserManager.exists(userId))
8942                return null;
8943            final PackageParser.ProviderIntentInfo info = filter;
8944            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8945                return null;
8946            }
8947            final PackageParser.Provider provider = info.provider;
8948            if (mSafeMode && (provider.info.applicationInfo.flags
8949                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8950                return null;
8951            }
8952            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8953            if (ps == null) {
8954                return null;
8955            }
8956            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8957                    ps.readUserState(userId), userId);
8958            if (pi == null) {
8959                return null;
8960            }
8961            final ResolveInfo res = new ResolveInfo();
8962            res.providerInfo = pi;
8963            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8964                res.filter = filter;
8965            }
8966            res.priority = info.getPriority();
8967            res.preferredOrder = provider.owner.mPreferredOrder;
8968            res.match = match;
8969            res.isDefault = info.hasDefault;
8970            res.labelRes = info.labelRes;
8971            res.nonLocalizedLabel = info.nonLocalizedLabel;
8972            res.icon = info.icon;
8973            res.system = res.providerInfo.applicationInfo.isSystemApp();
8974            return res;
8975        }
8976
8977        @Override
8978        protected void sortResults(List<ResolveInfo> results) {
8979            Collections.sort(results, mResolvePrioritySorter);
8980        }
8981
8982        @Override
8983        protected void dumpFilter(PrintWriter out, String prefix,
8984                PackageParser.ProviderIntentInfo filter) {
8985            out.print(prefix);
8986            out.print(
8987                    Integer.toHexString(System.identityHashCode(filter.provider)));
8988            out.print(' ');
8989            filter.provider.printComponentShortName(out);
8990            out.print(" filter ");
8991            out.println(Integer.toHexString(System.identityHashCode(filter)));
8992        }
8993
8994        @Override
8995        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8996            return filter.provider;
8997        }
8998
8999        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9000            PackageParser.Provider provider = (PackageParser.Provider)label;
9001            out.print(prefix); out.print(
9002                    Integer.toHexString(System.identityHashCode(provider)));
9003                    out.print(' ');
9004                    provider.printComponentShortName(out);
9005            if (count > 1) {
9006                out.print(" ("); out.print(count); out.print(" filters)");
9007            }
9008            out.println();
9009        }
9010
9011        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9012                = new ArrayMap<ComponentName, PackageParser.Provider>();
9013        private int mFlags;
9014    };
9015
9016    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9017            new Comparator<ResolveInfo>() {
9018        public int compare(ResolveInfo r1, ResolveInfo r2) {
9019            int v1 = r1.priority;
9020            int v2 = r2.priority;
9021            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9022            if (v1 != v2) {
9023                return (v1 > v2) ? -1 : 1;
9024            }
9025            v1 = r1.preferredOrder;
9026            v2 = r2.preferredOrder;
9027            if (v1 != v2) {
9028                return (v1 > v2) ? -1 : 1;
9029            }
9030            if (r1.isDefault != r2.isDefault) {
9031                return r1.isDefault ? -1 : 1;
9032            }
9033            v1 = r1.match;
9034            v2 = r2.match;
9035            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9036            if (v1 != v2) {
9037                return (v1 > v2) ? -1 : 1;
9038            }
9039            if (r1.system != r2.system) {
9040                return r1.system ? -1 : 1;
9041            }
9042            return 0;
9043        }
9044    };
9045
9046    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9047            new Comparator<ProviderInfo>() {
9048        public int compare(ProviderInfo p1, ProviderInfo p2) {
9049            final int v1 = p1.initOrder;
9050            final int v2 = p2.initOrder;
9051            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9052        }
9053    };
9054
9055    final void sendPackageBroadcast(final String action, final String pkg,
9056            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9057            final int[] userIds) {
9058        mHandler.post(new Runnable() {
9059            @Override
9060            public void run() {
9061                try {
9062                    final IActivityManager am = ActivityManagerNative.getDefault();
9063                    if (am == null) return;
9064                    final int[] resolvedUserIds;
9065                    if (userIds == null) {
9066                        resolvedUserIds = am.getRunningUserIds();
9067                    } else {
9068                        resolvedUserIds = userIds;
9069                    }
9070                    for (int id : resolvedUserIds) {
9071                        final Intent intent = new Intent(action,
9072                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9073                        if (extras != null) {
9074                            intent.putExtras(extras);
9075                        }
9076                        if (targetPkg != null) {
9077                            intent.setPackage(targetPkg);
9078                        }
9079                        // Modify the UID when posting to other users
9080                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9081                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9082                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9083                            intent.putExtra(Intent.EXTRA_UID, uid);
9084                        }
9085                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9086                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9087                        if (DEBUG_BROADCASTS) {
9088                            RuntimeException here = new RuntimeException("here");
9089                            here.fillInStackTrace();
9090                            Slog.d(TAG, "Sending to user " + id + ": "
9091                                    + intent.toShortString(false, true, false, false)
9092                                    + " " + intent.getExtras(), here);
9093                        }
9094                        am.broadcastIntent(null, intent, null, finishedReceiver,
9095                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9096                                null, finishedReceiver != null, false, id);
9097                    }
9098                } catch (RemoteException ex) {
9099                }
9100            }
9101        });
9102    }
9103
9104    /**
9105     * Check if the external storage media is available. This is true if there
9106     * is a mounted external storage medium or if the external storage is
9107     * emulated.
9108     */
9109    private boolean isExternalMediaAvailable() {
9110        return mMediaMounted || Environment.isExternalStorageEmulated();
9111    }
9112
9113    @Override
9114    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9115        // writer
9116        synchronized (mPackages) {
9117            if (!isExternalMediaAvailable()) {
9118                // If the external storage is no longer mounted at this point,
9119                // the caller may not have been able to delete all of this
9120                // packages files and can not delete any more.  Bail.
9121                return null;
9122            }
9123            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9124            if (lastPackage != null) {
9125                pkgs.remove(lastPackage);
9126            }
9127            if (pkgs.size() > 0) {
9128                return pkgs.get(0);
9129            }
9130        }
9131        return null;
9132    }
9133
9134    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9135        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9136                userId, andCode ? 1 : 0, packageName);
9137        if (mSystemReady) {
9138            msg.sendToTarget();
9139        } else {
9140            if (mPostSystemReadyMessages == null) {
9141                mPostSystemReadyMessages = new ArrayList<>();
9142            }
9143            mPostSystemReadyMessages.add(msg);
9144        }
9145    }
9146
9147    void startCleaningPackages() {
9148        // reader
9149        synchronized (mPackages) {
9150            if (!isExternalMediaAvailable()) {
9151                return;
9152            }
9153            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9154                return;
9155            }
9156        }
9157        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9158        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9159        IActivityManager am = ActivityManagerNative.getDefault();
9160        if (am != null) {
9161            try {
9162                am.startService(null, intent, null, UserHandle.USER_OWNER);
9163            } catch (RemoteException e) {
9164            }
9165        }
9166    }
9167
9168    @Override
9169    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9170            int installFlags, String installerPackageName, VerificationParams verificationParams,
9171            String packageAbiOverride) {
9172        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9173                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9174    }
9175
9176    @Override
9177    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9178            int installFlags, String installerPackageName, VerificationParams verificationParams,
9179            String packageAbiOverride, int userId) {
9180        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9181
9182        final int callingUid = Binder.getCallingUid();
9183        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9184
9185        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9186            try {
9187                if (observer != null) {
9188                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9189                }
9190            } catch (RemoteException re) {
9191            }
9192            return;
9193        }
9194
9195        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9196            installFlags |= PackageManager.INSTALL_FROM_ADB;
9197
9198        } else {
9199            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9200            // about installerPackageName.
9201
9202            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9203            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9204        }
9205
9206        UserHandle user;
9207        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9208            user = UserHandle.ALL;
9209        } else {
9210            user = new UserHandle(userId);
9211        }
9212
9213        // Only system components can circumvent runtime permissions when installing.
9214        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9215                && mContext.checkCallingOrSelfPermission(Manifest.permission
9216                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9217            throw new SecurityException("You need the "
9218                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9219                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9220        }
9221
9222        verificationParams.setInstallerUid(callingUid);
9223
9224        final File originFile = new File(originPath);
9225        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9226
9227        final Message msg = mHandler.obtainMessage(INIT_COPY);
9228        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9229                null, verificationParams, user, packageAbiOverride);
9230        mHandler.sendMessage(msg);
9231    }
9232
9233    void installStage(String packageName, File stagedDir, String stagedCid,
9234            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9235            String installerPackageName, int installerUid, UserHandle user) {
9236        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9237                params.referrerUri, installerUid, null);
9238        verifParams.setInstallerUid(installerUid);
9239
9240        final OriginInfo origin;
9241        if (stagedDir != null) {
9242            origin = OriginInfo.fromStagedFile(stagedDir);
9243        } else {
9244            origin = OriginInfo.fromStagedContainer(stagedCid);
9245        }
9246
9247        final Message msg = mHandler.obtainMessage(INIT_COPY);
9248        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9249                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9250        mHandler.sendMessage(msg);
9251    }
9252
9253    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9254        Bundle extras = new Bundle(1);
9255        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9256
9257        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9258                packageName, extras, null, null, new int[] {userId});
9259        try {
9260            IActivityManager am = ActivityManagerNative.getDefault();
9261            final boolean isSystem =
9262                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9263            if (isSystem && am.isUserRunning(userId, false)) {
9264                // The just-installed/enabled app is bundled on the system, so presumed
9265                // to be able to run automatically without needing an explicit launch.
9266                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9267                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9268                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9269                        .setPackage(packageName);
9270                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9271                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9272            }
9273        } catch (RemoteException e) {
9274            // shouldn't happen
9275            Slog.w(TAG, "Unable to bootstrap installed package", e);
9276        }
9277    }
9278
9279    @Override
9280    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9281            int userId) {
9282        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9283        PackageSetting pkgSetting;
9284        final int uid = Binder.getCallingUid();
9285        enforceCrossUserPermission(uid, userId, true, true,
9286                "setApplicationHiddenSetting for user " + userId);
9287
9288        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9289            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9290            return false;
9291        }
9292
9293        long callingId = Binder.clearCallingIdentity();
9294        try {
9295            boolean sendAdded = false;
9296            boolean sendRemoved = false;
9297            // writer
9298            synchronized (mPackages) {
9299                pkgSetting = mSettings.mPackages.get(packageName);
9300                if (pkgSetting == null) {
9301                    return false;
9302                }
9303                if (pkgSetting.getHidden(userId) != hidden) {
9304                    pkgSetting.setHidden(hidden, userId);
9305                    mSettings.writePackageRestrictionsLPr(userId);
9306                    if (hidden) {
9307                        sendRemoved = true;
9308                    } else {
9309                        sendAdded = true;
9310                    }
9311                }
9312            }
9313            if (sendAdded) {
9314                sendPackageAddedForUser(packageName, pkgSetting, userId);
9315                return true;
9316            }
9317            if (sendRemoved) {
9318                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9319                        "hiding pkg");
9320                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9321            }
9322        } finally {
9323            Binder.restoreCallingIdentity(callingId);
9324        }
9325        return false;
9326    }
9327
9328    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9329            int userId) {
9330        final PackageRemovedInfo info = new PackageRemovedInfo();
9331        info.removedPackage = packageName;
9332        info.removedUsers = new int[] {userId};
9333        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9334        info.sendBroadcast(false, false, false);
9335    }
9336
9337    /**
9338     * Returns true if application is not found or there was an error. Otherwise it returns
9339     * the hidden state of the package for the given user.
9340     */
9341    @Override
9342    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9343        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9344        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9345                false, "getApplicationHidden for user " + userId);
9346        PackageSetting pkgSetting;
9347        long callingId = Binder.clearCallingIdentity();
9348        try {
9349            // writer
9350            synchronized (mPackages) {
9351                pkgSetting = mSettings.mPackages.get(packageName);
9352                if (pkgSetting == null) {
9353                    return true;
9354                }
9355                return pkgSetting.getHidden(userId);
9356            }
9357        } finally {
9358            Binder.restoreCallingIdentity(callingId);
9359        }
9360    }
9361
9362    /**
9363     * @hide
9364     */
9365    @Override
9366    public int installExistingPackageAsUser(String packageName, int userId) {
9367        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9368                null);
9369        PackageSetting pkgSetting;
9370        final int uid = Binder.getCallingUid();
9371        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9372                + userId);
9373        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9374            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9375        }
9376
9377        long callingId = Binder.clearCallingIdentity();
9378        try {
9379            boolean sendAdded = false;
9380
9381            // writer
9382            synchronized (mPackages) {
9383                pkgSetting = mSettings.mPackages.get(packageName);
9384                if (pkgSetting == null) {
9385                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9386                }
9387                if (!pkgSetting.getInstalled(userId)) {
9388                    pkgSetting.setInstalled(true, userId);
9389                    pkgSetting.setHidden(false, userId);
9390                    mSettings.writePackageRestrictionsLPr(userId);
9391                    sendAdded = true;
9392                }
9393            }
9394
9395            if (sendAdded) {
9396                sendPackageAddedForUser(packageName, pkgSetting, userId);
9397            }
9398        } finally {
9399            Binder.restoreCallingIdentity(callingId);
9400        }
9401
9402        return PackageManager.INSTALL_SUCCEEDED;
9403    }
9404
9405    boolean isUserRestricted(int userId, String restrictionKey) {
9406        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9407        if (restrictions.getBoolean(restrictionKey, false)) {
9408            Log.w(TAG, "User is restricted: " + restrictionKey);
9409            return true;
9410        }
9411        return false;
9412    }
9413
9414    @Override
9415    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9416        mContext.enforceCallingOrSelfPermission(
9417                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9418                "Only package verification agents can verify applications");
9419
9420        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9421        final PackageVerificationResponse response = new PackageVerificationResponse(
9422                verificationCode, Binder.getCallingUid());
9423        msg.arg1 = id;
9424        msg.obj = response;
9425        mHandler.sendMessage(msg);
9426    }
9427
9428    @Override
9429    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9430            long millisecondsToDelay) {
9431        mContext.enforceCallingOrSelfPermission(
9432                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9433                "Only package verification agents can extend verification timeouts");
9434
9435        final PackageVerificationState state = mPendingVerification.get(id);
9436        final PackageVerificationResponse response = new PackageVerificationResponse(
9437                verificationCodeAtTimeout, Binder.getCallingUid());
9438
9439        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9440            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9441        }
9442        if (millisecondsToDelay < 0) {
9443            millisecondsToDelay = 0;
9444        }
9445        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9446                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9447            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9448        }
9449
9450        if ((state != null) && !state.timeoutExtended()) {
9451            state.extendTimeout();
9452
9453            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9454            msg.arg1 = id;
9455            msg.obj = response;
9456            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9457        }
9458    }
9459
9460    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9461            int verificationCode, UserHandle user) {
9462        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9463        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9464        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9465        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9466        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9467
9468        mContext.sendBroadcastAsUser(intent, user,
9469                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9470    }
9471
9472    private ComponentName matchComponentForVerifier(String packageName,
9473            List<ResolveInfo> receivers) {
9474        ActivityInfo targetReceiver = null;
9475
9476        final int NR = receivers.size();
9477        for (int i = 0; i < NR; i++) {
9478            final ResolveInfo info = receivers.get(i);
9479            if (info.activityInfo == null) {
9480                continue;
9481            }
9482
9483            if (packageName.equals(info.activityInfo.packageName)) {
9484                targetReceiver = info.activityInfo;
9485                break;
9486            }
9487        }
9488
9489        if (targetReceiver == null) {
9490            return null;
9491        }
9492
9493        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9494    }
9495
9496    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9497            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9498        if (pkgInfo.verifiers.length == 0) {
9499            return null;
9500        }
9501
9502        final int N = pkgInfo.verifiers.length;
9503        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9504        for (int i = 0; i < N; i++) {
9505            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9506
9507            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9508                    receivers);
9509            if (comp == null) {
9510                continue;
9511            }
9512
9513            final int verifierUid = getUidForVerifier(verifierInfo);
9514            if (verifierUid == -1) {
9515                continue;
9516            }
9517
9518            if (DEBUG_VERIFY) {
9519                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9520                        + " with the correct signature");
9521            }
9522            sufficientVerifiers.add(comp);
9523            verificationState.addSufficientVerifier(verifierUid);
9524        }
9525
9526        return sufficientVerifiers;
9527    }
9528
9529    private int getUidForVerifier(VerifierInfo verifierInfo) {
9530        synchronized (mPackages) {
9531            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9532            if (pkg == null) {
9533                return -1;
9534            } else if (pkg.mSignatures.length != 1) {
9535                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9536                        + " has more than one signature; ignoring");
9537                return -1;
9538            }
9539
9540            /*
9541             * If the public key of the package's signature does not match
9542             * our expected public key, then this is a different package and
9543             * we should skip.
9544             */
9545
9546            final byte[] expectedPublicKey;
9547            try {
9548                final Signature verifierSig = pkg.mSignatures[0];
9549                final PublicKey publicKey = verifierSig.getPublicKey();
9550                expectedPublicKey = publicKey.getEncoded();
9551            } catch (CertificateException e) {
9552                return -1;
9553            }
9554
9555            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9556
9557            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9558                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9559                        + " does not have the expected public key; ignoring");
9560                return -1;
9561            }
9562
9563            return pkg.applicationInfo.uid;
9564        }
9565    }
9566
9567    @Override
9568    public void finishPackageInstall(int token) {
9569        enforceSystemOrRoot("Only the system is allowed to finish installs");
9570
9571        if (DEBUG_INSTALL) {
9572            Slog.v(TAG, "BM finishing package install for " + token);
9573        }
9574
9575        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9576        mHandler.sendMessage(msg);
9577    }
9578
9579    /**
9580     * Get the verification agent timeout.
9581     *
9582     * @return verification timeout in milliseconds
9583     */
9584    private long getVerificationTimeout() {
9585        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9586                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9587                DEFAULT_VERIFICATION_TIMEOUT);
9588    }
9589
9590    /**
9591     * Get the default verification agent response code.
9592     *
9593     * @return default verification response code
9594     */
9595    private int getDefaultVerificationResponse() {
9596        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9597                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9598                DEFAULT_VERIFICATION_RESPONSE);
9599    }
9600
9601    /**
9602     * Check whether or not package verification has been enabled.
9603     *
9604     * @return true if verification should be performed
9605     */
9606    private boolean isVerificationEnabled(int userId, int installFlags) {
9607        if (!DEFAULT_VERIFY_ENABLE) {
9608            return false;
9609        }
9610
9611        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9612
9613        // Check if installing from ADB
9614        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9615            // Do not run verification in a test harness environment
9616            if (ActivityManager.isRunningInTestHarness()) {
9617                return false;
9618            }
9619            if (ensureVerifyAppsEnabled) {
9620                return true;
9621            }
9622            // Check if the developer does not want package verification for ADB installs
9623            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9624                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9625                return false;
9626            }
9627        }
9628
9629        if (ensureVerifyAppsEnabled) {
9630            return true;
9631        }
9632
9633        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9634                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9635    }
9636
9637    @Override
9638    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9639            throws RemoteException {
9640        mContext.enforceCallingOrSelfPermission(
9641                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9642                "Only intentfilter verification agents can verify applications");
9643
9644        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9645        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9646                Binder.getCallingUid(), verificationCode, failedDomains);
9647        msg.arg1 = id;
9648        msg.obj = response;
9649        mHandler.sendMessage(msg);
9650    }
9651
9652    @Override
9653    public int getIntentVerificationStatus(String packageName, int userId) {
9654        synchronized (mPackages) {
9655            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9656        }
9657    }
9658
9659    @Override
9660    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9661        mContext.enforceCallingOrSelfPermission(
9662                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9663
9664        boolean result = false;
9665        synchronized (mPackages) {
9666            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9667        }
9668        if (result) {
9669            scheduleWritePackageRestrictionsLocked(userId);
9670        }
9671        return result;
9672    }
9673
9674    @Override
9675    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9676        synchronized (mPackages) {
9677            return mSettings.getIntentFilterVerificationsLPr(packageName);
9678        }
9679    }
9680
9681    @Override
9682    public List<IntentFilter> getAllIntentFilters(String packageName) {
9683        if (TextUtils.isEmpty(packageName)) {
9684            return Collections.<IntentFilter>emptyList();
9685        }
9686        synchronized (mPackages) {
9687            PackageParser.Package pkg = mPackages.get(packageName);
9688            if (pkg == null || pkg.activities == null) {
9689                return Collections.<IntentFilter>emptyList();
9690            }
9691            final int count = pkg.activities.size();
9692            ArrayList<IntentFilter> result = new ArrayList<>();
9693            for (int n=0; n<count; n++) {
9694                PackageParser.Activity activity = pkg.activities.get(n);
9695                if (activity.intents != null || activity.intents.size() > 0) {
9696                    result.addAll(activity.intents);
9697                }
9698            }
9699            return result;
9700        }
9701    }
9702
9703    @Override
9704    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9705        mContext.enforceCallingOrSelfPermission(
9706                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9707
9708        synchronized (mPackages) {
9709            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9710            if (packageName != null) {
9711                result |= updateIntentVerificationStatus(packageName,
9712                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9713                        UserHandle.myUserId());
9714            }
9715            return result;
9716        }
9717    }
9718
9719    @Override
9720    public String getDefaultBrowserPackageName(int userId) {
9721        synchronized (mPackages) {
9722            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9723        }
9724    }
9725
9726    /**
9727     * Get the "allow unknown sources" setting.
9728     *
9729     * @return the current "allow unknown sources" setting
9730     */
9731    private int getUnknownSourcesSettings() {
9732        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9733                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9734                -1);
9735    }
9736
9737    @Override
9738    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9739        final int uid = Binder.getCallingUid();
9740        // writer
9741        synchronized (mPackages) {
9742            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9743            if (targetPackageSetting == null) {
9744                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9745            }
9746
9747            PackageSetting installerPackageSetting;
9748            if (installerPackageName != null) {
9749                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9750                if (installerPackageSetting == null) {
9751                    throw new IllegalArgumentException("Unknown installer package: "
9752                            + installerPackageName);
9753                }
9754            } else {
9755                installerPackageSetting = null;
9756            }
9757
9758            Signature[] callerSignature;
9759            Object obj = mSettings.getUserIdLPr(uid);
9760            if (obj != null) {
9761                if (obj instanceof SharedUserSetting) {
9762                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9763                } else if (obj instanceof PackageSetting) {
9764                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9765                } else {
9766                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9767                }
9768            } else {
9769                throw new SecurityException("Unknown calling uid " + uid);
9770            }
9771
9772            // Verify: can't set installerPackageName to a package that is
9773            // not signed with the same cert as the caller.
9774            if (installerPackageSetting != null) {
9775                if (compareSignatures(callerSignature,
9776                        installerPackageSetting.signatures.mSignatures)
9777                        != PackageManager.SIGNATURE_MATCH) {
9778                    throw new SecurityException(
9779                            "Caller does not have same cert as new installer package "
9780                            + installerPackageName);
9781                }
9782            }
9783
9784            // Verify: if target already has an installer package, it must
9785            // be signed with the same cert as the caller.
9786            if (targetPackageSetting.installerPackageName != null) {
9787                PackageSetting setting = mSettings.mPackages.get(
9788                        targetPackageSetting.installerPackageName);
9789                // If the currently set package isn't valid, then it's always
9790                // okay to change it.
9791                if (setting != null) {
9792                    if (compareSignatures(callerSignature,
9793                            setting.signatures.mSignatures)
9794                            != PackageManager.SIGNATURE_MATCH) {
9795                        throw new SecurityException(
9796                                "Caller does not have same cert as old installer package "
9797                                + targetPackageSetting.installerPackageName);
9798                    }
9799                }
9800            }
9801
9802            // Okay!
9803            targetPackageSetting.installerPackageName = installerPackageName;
9804            scheduleWriteSettingsLocked();
9805        }
9806    }
9807
9808    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9809        // Queue up an async operation since the package installation may take a little while.
9810        mHandler.post(new Runnable() {
9811            public void run() {
9812                mHandler.removeCallbacks(this);
9813                 // Result object to be returned
9814                PackageInstalledInfo res = new PackageInstalledInfo();
9815                res.returnCode = currentStatus;
9816                res.uid = -1;
9817                res.pkg = null;
9818                res.removedInfo = new PackageRemovedInfo();
9819                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9820                    args.doPreInstall(res.returnCode);
9821                    synchronized (mInstallLock) {
9822                        installPackageLI(args, res);
9823                    }
9824                    args.doPostInstall(res.returnCode, res.uid);
9825                }
9826
9827                // A restore should be performed at this point if (a) the install
9828                // succeeded, (b) the operation is not an update, and (c) the new
9829                // package has not opted out of backup participation.
9830                final boolean update = res.removedInfo.removedPackage != null;
9831                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9832                boolean doRestore = !update
9833                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9834
9835                // Set up the post-install work request bookkeeping.  This will be used
9836                // and cleaned up by the post-install event handling regardless of whether
9837                // there's a restore pass performed.  Token values are >= 1.
9838                int token;
9839                if (mNextInstallToken < 0) mNextInstallToken = 1;
9840                token = mNextInstallToken++;
9841
9842                PostInstallData data = new PostInstallData(args, res);
9843                mRunningInstalls.put(token, data);
9844                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9845
9846                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9847                    // Pass responsibility to the Backup Manager.  It will perform a
9848                    // restore if appropriate, then pass responsibility back to the
9849                    // Package Manager to run the post-install observer callbacks
9850                    // and broadcasts.
9851                    IBackupManager bm = IBackupManager.Stub.asInterface(
9852                            ServiceManager.getService(Context.BACKUP_SERVICE));
9853                    if (bm != null) {
9854                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9855                                + " to BM for possible restore");
9856                        try {
9857                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9858                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9859                            } else {
9860                                doRestore = false;
9861                            }
9862                        } catch (RemoteException e) {
9863                            // can't happen; the backup manager is local
9864                        } catch (Exception e) {
9865                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9866                            doRestore = false;
9867                        }
9868                    } else {
9869                        Slog.e(TAG, "Backup Manager not found!");
9870                        doRestore = false;
9871                    }
9872                }
9873
9874                if (!doRestore) {
9875                    // No restore possible, or the Backup Manager was mysteriously not
9876                    // available -- just fire the post-install work request directly.
9877                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9878                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9879                    mHandler.sendMessage(msg);
9880                }
9881            }
9882        });
9883    }
9884
9885    private abstract class HandlerParams {
9886        private static final int MAX_RETRIES = 4;
9887
9888        /**
9889         * Number of times startCopy() has been attempted and had a non-fatal
9890         * error.
9891         */
9892        private int mRetries = 0;
9893
9894        /** User handle for the user requesting the information or installation. */
9895        private final UserHandle mUser;
9896
9897        HandlerParams(UserHandle user) {
9898            mUser = user;
9899        }
9900
9901        UserHandle getUser() {
9902            return mUser;
9903        }
9904
9905        final boolean startCopy() {
9906            boolean res;
9907            try {
9908                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9909
9910                if (++mRetries > MAX_RETRIES) {
9911                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9912                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9913                    handleServiceError();
9914                    return false;
9915                } else {
9916                    handleStartCopy();
9917                    res = true;
9918                }
9919            } catch (RemoteException e) {
9920                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9921                mHandler.sendEmptyMessage(MCS_RECONNECT);
9922                res = false;
9923            }
9924            handleReturnCode();
9925            return res;
9926        }
9927
9928        final void serviceError() {
9929            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9930            handleServiceError();
9931            handleReturnCode();
9932        }
9933
9934        abstract void handleStartCopy() throws RemoteException;
9935        abstract void handleServiceError();
9936        abstract void handleReturnCode();
9937    }
9938
9939    class MeasureParams extends HandlerParams {
9940        private final PackageStats mStats;
9941        private boolean mSuccess;
9942
9943        private final IPackageStatsObserver mObserver;
9944
9945        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9946            super(new UserHandle(stats.userHandle));
9947            mObserver = observer;
9948            mStats = stats;
9949        }
9950
9951        @Override
9952        public String toString() {
9953            return "MeasureParams{"
9954                + Integer.toHexString(System.identityHashCode(this))
9955                + " " + mStats.packageName + "}";
9956        }
9957
9958        @Override
9959        void handleStartCopy() throws RemoteException {
9960            synchronized (mInstallLock) {
9961                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9962            }
9963
9964            if (mSuccess) {
9965                final boolean mounted;
9966                if (Environment.isExternalStorageEmulated()) {
9967                    mounted = true;
9968                } else {
9969                    final String status = Environment.getExternalStorageState();
9970                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9971                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9972                }
9973
9974                if (mounted) {
9975                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9976
9977                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9978                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9979
9980                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9981                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9982
9983                    // Always subtract cache size, since it's a subdirectory
9984                    mStats.externalDataSize -= mStats.externalCacheSize;
9985
9986                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9987                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9988
9989                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9990                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9991                }
9992            }
9993        }
9994
9995        @Override
9996        void handleReturnCode() {
9997            if (mObserver != null) {
9998                try {
9999                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10000                } catch (RemoteException e) {
10001                    Slog.i(TAG, "Observer no longer exists.");
10002                }
10003            }
10004        }
10005
10006        @Override
10007        void handleServiceError() {
10008            Slog.e(TAG, "Could not measure application " + mStats.packageName
10009                            + " external storage");
10010        }
10011    }
10012
10013    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10014            throws RemoteException {
10015        long result = 0;
10016        for (File path : paths) {
10017            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10018        }
10019        return result;
10020    }
10021
10022    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10023        for (File path : paths) {
10024            try {
10025                mcs.clearDirectory(path.getAbsolutePath());
10026            } catch (RemoteException e) {
10027            }
10028        }
10029    }
10030
10031    static class OriginInfo {
10032        /**
10033         * Location where install is coming from, before it has been
10034         * copied/renamed into place. This could be a single monolithic APK
10035         * file, or a cluster directory. This location may be untrusted.
10036         */
10037        final File file;
10038        final String cid;
10039
10040        /**
10041         * Flag indicating that {@link #file} or {@link #cid} has already been
10042         * staged, meaning downstream users don't need to defensively copy the
10043         * contents.
10044         */
10045        final boolean staged;
10046
10047        /**
10048         * Flag indicating that {@link #file} or {@link #cid} is an already
10049         * installed app that is being moved.
10050         */
10051        final boolean existing;
10052
10053        final String resolvedPath;
10054        final File resolvedFile;
10055
10056        static OriginInfo fromNothing() {
10057            return new OriginInfo(null, null, false, false);
10058        }
10059
10060        static OriginInfo fromUntrustedFile(File file) {
10061            return new OriginInfo(file, null, false, false);
10062        }
10063
10064        static OriginInfo fromExistingFile(File file) {
10065            return new OriginInfo(file, null, false, true);
10066        }
10067
10068        static OriginInfo fromStagedFile(File file) {
10069            return new OriginInfo(file, null, true, false);
10070        }
10071
10072        static OriginInfo fromStagedContainer(String cid) {
10073            return new OriginInfo(null, cid, true, false);
10074        }
10075
10076        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10077            this.file = file;
10078            this.cid = cid;
10079            this.staged = staged;
10080            this.existing = existing;
10081
10082            if (cid != null) {
10083                resolvedPath = PackageHelper.getSdDir(cid);
10084                resolvedFile = new File(resolvedPath);
10085            } else if (file != null) {
10086                resolvedPath = file.getAbsolutePath();
10087                resolvedFile = file;
10088            } else {
10089                resolvedPath = null;
10090                resolvedFile = null;
10091            }
10092        }
10093    }
10094
10095    class MoveInfo {
10096        final int moveId;
10097        final String fromUuid;
10098        final String toUuid;
10099        final String packageName;
10100        final String dataAppName;
10101        final int appId;
10102        final String seinfo;
10103
10104        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10105                String dataAppName, int appId, String seinfo) {
10106            this.moveId = moveId;
10107            this.fromUuid = fromUuid;
10108            this.toUuid = toUuid;
10109            this.packageName = packageName;
10110            this.dataAppName = dataAppName;
10111            this.appId = appId;
10112            this.seinfo = seinfo;
10113        }
10114    }
10115
10116    class InstallParams extends HandlerParams {
10117        final OriginInfo origin;
10118        final MoveInfo move;
10119        final IPackageInstallObserver2 observer;
10120        int installFlags;
10121        final String installerPackageName;
10122        final String volumeUuid;
10123        final VerificationParams verificationParams;
10124        private InstallArgs mArgs;
10125        private int mRet;
10126        final String packageAbiOverride;
10127
10128        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10129                int installFlags, String installerPackageName, String volumeUuid,
10130                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10131            super(user);
10132            this.origin = origin;
10133            this.move = move;
10134            this.observer = observer;
10135            this.installFlags = installFlags;
10136            this.installerPackageName = installerPackageName;
10137            this.volumeUuid = volumeUuid;
10138            this.verificationParams = verificationParams;
10139            this.packageAbiOverride = packageAbiOverride;
10140        }
10141
10142        @Override
10143        public String toString() {
10144            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10145                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10146        }
10147
10148        public ManifestDigest getManifestDigest() {
10149            if (verificationParams == null) {
10150                return null;
10151            }
10152            return verificationParams.getManifestDigest();
10153        }
10154
10155        private int installLocationPolicy(PackageInfoLite pkgLite) {
10156            String packageName = pkgLite.packageName;
10157            int installLocation = pkgLite.installLocation;
10158            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10159            // reader
10160            synchronized (mPackages) {
10161                PackageParser.Package pkg = mPackages.get(packageName);
10162                if (pkg != null) {
10163                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10164                        // Check for downgrading.
10165                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10166                            try {
10167                                checkDowngrade(pkg, pkgLite);
10168                            } catch (PackageManagerException e) {
10169                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10170                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10171                            }
10172                        }
10173                        // Check for updated system application.
10174                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10175                            if (onSd) {
10176                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10177                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10178                            }
10179                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10180                        } else {
10181                            if (onSd) {
10182                                // Install flag overrides everything.
10183                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10184                            }
10185                            // If current upgrade specifies particular preference
10186                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10187                                // Application explicitly specified internal.
10188                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10189                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10190                                // App explictly prefers external. Let policy decide
10191                            } else {
10192                                // Prefer previous location
10193                                if (isExternal(pkg)) {
10194                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10195                                }
10196                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10197                            }
10198                        }
10199                    } else {
10200                        // Invalid install. Return error code
10201                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10202                    }
10203                }
10204            }
10205            // All the special cases have been taken care of.
10206            // Return result based on recommended install location.
10207            if (onSd) {
10208                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10209            }
10210            return pkgLite.recommendedInstallLocation;
10211        }
10212
10213        /*
10214         * Invoke remote method to get package information and install
10215         * location values. Override install location based on default
10216         * policy if needed and then create install arguments based
10217         * on the install location.
10218         */
10219        public void handleStartCopy() throws RemoteException {
10220            int ret = PackageManager.INSTALL_SUCCEEDED;
10221
10222            // If we're already staged, we've firmly committed to an install location
10223            if (origin.staged) {
10224                if (origin.file != null) {
10225                    installFlags |= PackageManager.INSTALL_INTERNAL;
10226                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10227                } else if (origin.cid != null) {
10228                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10229                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10230                } else {
10231                    throw new IllegalStateException("Invalid stage location");
10232                }
10233            }
10234
10235            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10236            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10237
10238            PackageInfoLite pkgLite = null;
10239
10240            if (onInt && onSd) {
10241                // Check if both bits are set.
10242                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10243                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10244            } else {
10245                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10246                        packageAbiOverride);
10247
10248                /*
10249                 * If we have too little free space, try to free cache
10250                 * before giving up.
10251                 */
10252                if (!origin.staged && pkgLite.recommendedInstallLocation
10253                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10254                    // TODO: focus freeing disk space on the target device
10255                    final StorageManager storage = StorageManager.from(mContext);
10256                    final long lowThreshold = storage.getStorageLowBytes(
10257                            Environment.getDataDirectory());
10258
10259                    final long sizeBytes = mContainerService.calculateInstalledSize(
10260                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10261
10262                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10263                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10264                                installFlags, packageAbiOverride);
10265                    }
10266
10267                    /*
10268                     * The cache free must have deleted the file we
10269                     * downloaded to install.
10270                     *
10271                     * TODO: fix the "freeCache" call to not delete
10272                     *       the file we care about.
10273                     */
10274                    if (pkgLite.recommendedInstallLocation
10275                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10276                        pkgLite.recommendedInstallLocation
10277                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10278                    }
10279                }
10280            }
10281
10282            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10283                int loc = pkgLite.recommendedInstallLocation;
10284                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10285                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10286                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10287                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10288                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10289                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10290                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10291                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10292                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10293                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10294                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10295                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10296                } else {
10297                    // Override with defaults if needed.
10298                    loc = installLocationPolicy(pkgLite);
10299                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10300                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10301                    } else if (!onSd && !onInt) {
10302                        // Override install location with flags
10303                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10304                            // Set the flag to install on external media.
10305                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10306                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10307                        } else {
10308                            // Make sure the flag for installing on external
10309                            // media is unset
10310                            installFlags |= PackageManager.INSTALL_INTERNAL;
10311                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10312                        }
10313                    }
10314                }
10315            }
10316
10317            final InstallArgs args = createInstallArgs(this);
10318            mArgs = args;
10319
10320            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10321                 /*
10322                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10323                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10324                 */
10325                int userIdentifier = getUser().getIdentifier();
10326                if (userIdentifier == UserHandle.USER_ALL
10327                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10328                    userIdentifier = UserHandle.USER_OWNER;
10329                }
10330
10331                /*
10332                 * Determine if we have any installed package verifiers. If we
10333                 * do, then we'll defer to them to verify the packages.
10334                 */
10335                final int requiredUid = mRequiredVerifierPackage == null ? -1
10336                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10337                if (!origin.existing && requiredUid != -1
10338                        && isVerificationEnabled(userIdentifier, installFlags)) {
10339                    final Intent verification = new Intent(
10340                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10341                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10342                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10343                            PACKAGE_MIME_TYPE);
10344                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10345
10346                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10347                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10348                            0 /* TODO: Which userId? */);
10349
10350                    if (DEBUG_VERIFY) {
10351                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10352                                + verification.toString() + " with " + pkgLite.verifiers.length
10353                                + " optional verifiers");
10354                    }
10355
10356                    final int verificationId = mPendingVerificationToken++;
10357
10358                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10359
10360                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10361                            installerPackageName);
10362
10363                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10364                            installFlags);
10365
10366                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10367                            pkgLite.packageName);
10368
10369                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10370                            pkgLite.versionCode);
10371
10372                    if (verificationParams != null) {
10373                        if (verificationParams.getVerificationURI() != null) {
10374                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10375                                 verificationParams.getVerificationURI());
10376                        }
10377                        if (verificationParams.getOriginatingURI() != null) {
10378                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10379                                  verificationParams.getOriginatingURI());
10380                        }
10381                        if (verificationParams.getReferrer() != null) {
10382                            verification.putExtra(Intent.EXTRA_REFERRER,
10383                                  verificationParams.getReferrer());
10384                        }
10385                        if (verificationParams.getOriginatingUid() >= 0) {
10386                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10387                                  verificationParams.getOriginatingUid());
10388                        }
10389                        if (verificationParams.getInstallerUid() >= 0) {
10390                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10391                                  verificationParams.getInstallerUid());
10392                        }
10393                    }
10394
10395                    final PackageVerificationState verificationState = new PackageVerificationState(
10396                            requiredUid, args);
10397
10398                    mPendingVerification.append(verificationId, verificationState);
10399
10400                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10401                            receivers, verificationState);
10402
10403                    /*
10404                     * If any sufficient verifiers were listed in the package
10405                     * manifest, attempt to ask them.
10406                     */
10407                    if (sufficientVerifiers != null) {
10408                        final int N = sufficientVerifiers.size();
10409                        if (N == 0) {
10410                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10411                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10412                        } else {
10413                            for (int i = 0; i < N; i++) {
10414                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10415
10416                                final Intent sufficientIntent = new Intent(verification);
10417                                sufficientIntent.setComponent(verifierComponent);
10418
10419                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10420                            }
10421                        }
10422                    }
10423
10424                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10425                            mRequiredVerifierPackage, receivers);
10426                    if (ret == PackageManager.INSTALL_SUCCEEDED
10427                            && mRequiredVerifierPackage != null) {
10428                        /*
10429                         * Send the intent to the required verification agent,
10430                         * but only start the verification timeout after the
10431                         * target BroadcastReceivers have run.
10432                         */
10433                        verification.setComponent(requiredVerifierComponent);
10434                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10435                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10436                                new BroadcastReceiver() {
10437                                    @Override
10438                                    public void onReceive(Context context, Intent intent) {
10439                                        final Message msg = mHandler
10440                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10441                                        msg.arg1 = verificationId;
10442                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10443                                    }
10444                                }, null, 0, null, null);
10445
10446                        /*
10447                         * We don't want the copy to proceed until verification
10448                         * succeeds, so null out this field.
10449                         */
10450                        mArgs = null;
10451                    }
10452                } else {
10453                    /*
10454                     * No package verification is enabled, so immediately start
10455                     * the remote call to initiate copy using temporary file.
10456                     */
10457                    ret = args.copyApk(mContainerService, true);
10458                }
10459            }
10460
10461            mRet = ret;
10462        }
10463
10464        @Override
10465        void handleReturnCode() {
10466            // If mArgs is null, then MCS couldn't be reached. When it
10467            // reconnects, it will try again to install. At that point, this
10468            // will succeed.
10469            if (mArgs != null) {
10470                processPendingInstall(mArgs, mRet);
10471            }
10472        }
10473
10474        @Override
10475        void handleServiceError() {
10476            mArgs = createInstallArgs(this);
10477            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10478        }
10479
10480        public boolean isForwardLocked() {
10481            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10482        }
10483    }
10484
10485    /**
10486     * Used during creation of InstallArgs
10487     *
10488     * @param installFlags package installation flags
10489     * @return true if should be installed on external storage
10490     */
10491    private static boolean installOnExternalAsec(int installFlags) {
10492        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10493            return false;
10494        }
10495        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10496            return true;
10497        }
10498        return false;
10499    }
10500
10501    /**
10502     * Used during creation of InstallArgs
10503     *
10504     * @param installFlags package installation flags
10505     * @return true if should be installed as forward locked
10506     */
10507    private static boolean installForwardLocked(int installFlags) {
10508        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10509    }
10510
10511    private InstallArgs createInstallArgs(InstallParams params) {
10512        if (params.move != null) {
10513            return new MoveInstallArgs(params);
10514        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10515            return new AsecInstallArgs(params);
10516        } else {
10517            return new FileInstallArgs(params);
10518        }
10519    }
10520
10521    /**
10522     * Create args that describe an existing installed package. Typically used
10523     * when cleaning up old installs, or used as a move source.
10524     */
10525    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10526            String resourcePath, String[] instructionSets) {
10527        final boolean isInAsec;
10528        if (installOnExternalAsec(installFlags)) {
10529            /* Apps on SD card are always in ASEC containers. */
10530            isInAsec = true;
10531        } else if (installForwardLocked(installFlags)
10532                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10533            /*
10534             * Forward-locked apps are only in ASEC containers if they're the
10535             * new style
10536             */
10537            isInAsec = true;
10538        } else {
10539            isInAsec = false;
10540        }
10541
10542        if (isInAsec) {
10543            return new AsecInstallArgs(codePath, instructionSets,
10544                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10545        } else {
10546            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10547        }
10548    }
10549
10550    static abstract class InstallArgs {
10551        /** @see InstallParams#origin */
10552        final OriginInfo origin;
10553        /** @see InstallParams#move */
10554        final MoveInfo move;
10555
10556        final IPackageInstallObserver2 observer;
10557        // Always refers to PackageManager flags only
10558        final int installFlags;
10559        final String installerPackageName;
10560        final String volumeUuid;
10561        final ManifestDigest manifestDigest;
10562        final UserHandle user;
10563        final String abiOverride;
10564
10565        // The list of instruction sets supported by this app. This is currently
10566        // only used during the rmdex() phase to clean up resources. We can get rid of this
10567        // if we move dex files under the common app path.
10568        /* nullable */ String[] instructionSets;
10569
10570        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10571                int installFlags, String installerPackageName, String volumeUuid,
10572                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10573                String abiOverride) {
10574            this.origin = origin;
10575            this.move = move;
10576            this.installFlags = installFlags;
10577            this.observer = observer;
10578            this.installerPackageName = installerPackageName;
10579            this.volumeUuid = volumeUuid;
10580            this.manifestDigest = manifestDigest;
10581            this.user = user;
10582            this.instructionSets = instructionSets;
10583            this.abiOverride = abiOverride;
10584        }
10585
10586        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10587        abstract int doPreInstall(int status);
10588
10589        /**
10590         * Rename package into final resting place. All paths on the given
10591         * scanned package should be updated to reflect the rename.
10592         */
10593        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10594        abstract int doPostInstall(int status, int uid);
10595
10596        /** @see PackageSettingBase#codePathString */
10597        abstract String getCodePath();
10598        /** @see PackageSettingBase#resourcePathString */
10599        abstract String getResourcePath();
10600
10601        // Need installer lock especially for dex file removal.
10602        abstract void cleanUpResourcesLI();
10603        abstract boolean doPostDeleteLI(boolean delete);
10604
10605        /**
10606         * Called before the source arguments are copied. This is used mostly
10607         * for MoveParams when it needs to read the source file to put it in the
10608         * destination.
10609         */
10610        int doPreCopy() {
10611            return PackageManager.INSTALL_SUCCEEDED;
10612        }
10613
10614        /**
10615         * Called after the source arguments are copied. This is used mostly for
10616         * MoveParams when it needs to read the source file to put it in the
10617         * destination.
10618         *
10619         * @return
10620         */
10621        int doPostCopy(int uid) {
10622            return PackageManager.INSTALL_SUCCEEDED;
10623        }
10624
10625        protected boolean isFwdLocked() {
10626            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10627        }
10628
10629        protected boolean isExternalAsec() {
10630            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10631        }
10632
10633        UserHandle getUser() {
10634            return user;
10635        }
10636    }
10637
10638    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10639        if (!allCodePaths.isEmpty()) {
10640            if (instructionSets == null) {
10641                throw new IllegalStateException("instructionSet == null");
10642            }
10643            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10644            for (String codePath : allCodePaths) {
10645                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10646                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10647                    if (retCode < 0) {
10648                        Slog.w(TAG, "Couldn't remove dex file for package: "
10649                                + " at location " + codePath + ", retcode=" + retCode);
10650                        // we don't consider this to be a failure of the core package deletion
10651                    }
10652                }
10653            }
10654        }
10655    }
10656
10657    /**
10658     * Logic to handle installation of non-ASEC applications, including copying
10659     * and renaming logic.
10660     */
10661    class FileInstallArgs extends InstallArgs {
10662        private File codeFile;
10663        private File resourceFile;
10664
10665        // Example topology:
10666        // /data/app/com.example/base.apk
10667        // /data/app/com.example/split_foo.apk
10668        // /data/app/com.example/lib/arm/libfoo.so
10669        // /data/app/com.example/lib/arm64/libfoo.so
10670        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10671
10672        /** New install */
10673        FileInstallArgs(InstallParams params) {
10674            super(params.origin, params.move, params.observer, params.installFlags,
10675                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10676                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10677            if (isFwdLocked()) {
10678                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10679            }
10680        }
10681
10682        /** Existing install */
10683        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10684            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10685                    null);
10686            this.codeFile = (codePath != null) ? new File(codePath) : null;
10687            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10688        }
10689
10690        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10691            if (origin.staged) {
10692                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10693                codeFile = origin.file;
10694                resourceFile = origin.file;
10695                return PackageManager.INSTALL_SUCCEEDED;
10696            }
10697
10698            try {
10699                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10700                codeFile = tempDir;
10701                resourceFile = tempDir;
10702            } catch (IOException e) {
10703                Slog.w(TAG, "Failed to create copy file: " + e);
10704                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10705            }
10706
10707            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10708                @Override
10709                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10710                    if (!FileUtils.isValidExtFilename(name)) {
10711                        throw new IllegalArgumentException("Invalid filename: " + name);
10712                    }
10713                    try {
10714                        final File file = new File(codeFile, name);
10715                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10716                                O_RDWR | O_CREAT, 0644);
10717                        Os.chmod(file.getAbsolutePath(), 0644);
10718                        return new ParcelFileDescriptor(fd);
10719                    } catch (ErrnoException e) {
10720                        throw new RemoteException("Failed to open: " + e.getMessage());
10721                    }
10722                }
10723            };
10724
10725            int ret = PackageManager.INSTALL_SUCCEEDED;
10726            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10727            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10728                Slog.e(TAG, "Failed to copy package");
10729                return ret;
10730            }
10731
10732            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10733            NativeLibraryHelper.Handle handle = null;
10734            try {
10735                handle = NativeLibraryHelper.Handle.create(codeFile);
10736                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10737                        abiOverride);
10738            } catch (IOException e) {
10739                Slog.e(TAG, "Copying native libraries failed", e);
10740                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10741            } finally {
10742                IoUtils.closeQuietly(handle);
10743            }
10744
10745            return ret;
10746        }
10747
10748        int doPreInstall(int status) {
10749            if (status != PackageManager.INSTALL_SUCCEEDED) {
10750                cleanUp();
10751            }
10752            return status;
10753        }
10754
10755        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10756            if (status != PackageManager.INSTALL_SUCCEEDED) {
10757                cleanUp();
10758                return false;
10759            }
10760
10761            final File targetDir = codeFile.getParentFile();
10762            final File beforeCodeFile = codeFile;
10763            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10764
10765            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10766            try {
10767                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10768            } catch (ErrnoException e) {
10769                Slog.w(TAG, "Failed to rename", e);
10770                return false;
10771            }
10772
10773            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10774                Slog.w(TAG, "Failed to restorecon");
10775                return false;
10776            }
10777
10778            // Reflect the rename internally
10779            codeFile = afterCodeFile;
10780            resourceFile = afterCodeFile;
10781
10782            // Reflect the rename in scanned details
10783            pkg.codePath = afterCodeFile.getAbsolutePath();
10784            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10785                    pkg.baseCodePath);
10786            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10787                    pkg.splitCodePaths);
10788
10789            // Reflect the rename in app info
10790            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10791            pkg.applicationInfo.setCodePath(pkg.codePath);
10792            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10793            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10794            pkg.applicationInfo.setResourcePath(pkg.codePath);
10795            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10796            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10797
10798            return true;
10799        }
10800
10801        int doPostInstall(int status, int uid) {
10802            if (status != PackageManager.INSTALL_SUCCEEDED) {
10803                cleanUp();
10804            }
10805            return status;
10806        }
10807
10808        @Override
10809        String getCodePath() {
10810            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10811        }
10812
10813        @Override
10814        String getResourcePath() {
10815            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10816        }
10817
10818        private boolean cleanUp() {
10819            if (codeFile == null || !codeFile.exists()) {
10820                return false;
10821            }
10822
10823            if (codeFile.isDirectory()) {
10824                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10825            } else {
10826                codeFile.delete();
10827            }
10828
10829            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10830                resourceFile.delete();
10831            }
10832
10833            return true;
10834        }
10835
10836        void cleanUpResourcesLI() {
10837            // Try enumerating all code paths before deleting
10838            List<String> allCodePaths = Collections.EMPTY_LIST;
10839            if (codeFile != null && codeFile.exists()) {
10840                try {
10841                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10842                    allCodePaths = pkg.getAllCodePaths();
10843                } catch (PackageParserException e) {
10844                    // Ignored; we tried our best
10845                }
10846            }
10847
10848            cleanUp();
10849            removeDexFiles(allCodePaths, instructionSets);
10850        }
10851
10852        boolean doPostDeleteLI(boolean delete) {
10853            // XXX err, shouldn't we respect the delete flag?
10854            cleanUpResourcesLI();
10855            return true;
10856        }
10857    }
10858
10859    private boolean isAsecExternal(String cid) {
10860        final String asecPath = PackageHelper.getSdFilesystem(cid);
10861        return !asecPath.startsWith(mAsecInternalPath);
10862    }
10863
10864    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10865            PackageManagerException {
10866        if (copyRet < 0) {
10867            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10868                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10869                throw new PackageManagerException(copyRet, message);
10870            }
10871        }
10872    }
10873
10874    /**
10875     * Extract the MountService "container ID" from the full code path of an
10876     * .apk.
10877     */
10878    static String cidFromCodePath(String fullCodePath) {
10879        int eidx = fullCodePath.lastIndexOf("/");
10880        String subStr1 = fullCodePath.substring(0, eidx);
10881        int sidx = subStr1.lastIndexOf("/");
10882        return subStr1.substring(sidx+1, eidx);
10883    }
10884
10885    /**
10886     * Logic to handle installation of ASEC applications, including copying and
10887     * renaming logic.
10888     */
10889    class AsecInstallArgs extends InstallArgs {
10890        static final String RES_FILE_NAME = "pkg.apk";
10891        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10892
10893        String cid;
10894        String packagePath;
10895        String resourcePath;
10896
10897        /** New install */
10898        AsecInstallArgs(InstallParams params) {
10899            super(params.origin, params.move, params.observer, params.installFlags,
10900                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10901                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10902        }
10903
10904        /** Existing install */
10905        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10906                        boolean isExternal, boolean isForwardLocked) {
10907            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10908                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10909                    instructionSets, null);
10910            // Hackily pretend we're still looking at a full code path
10911            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10912                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10913            }
10914
10915            // Extract cid from fullCodePath
10916            int eidx = fullCodePath.lastIndexOf("/");
10917            String subStr1 = fullCodePath.substring(0, eidx);
10918            int sidx = subStr1.lastIndexOf("/");
10919            cid = subStr1.substring(sidx+1, eidx);
10920            setMountPath(subStr1);
10921        }
10922
10923        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10924            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10925                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10926                    instructionSets, null);
10927            this.cid = cid;
10928            setMountPath(PackageHelper.getSdDir(cid));
10929        }
10930
10931        void createCopyFile() {
10932            cid = mInstallerService.allocateExternalStageCidLegacy();
10933        }
10934
10935        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10936            if (origin.staged) {
10937                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
10938                cid = origin.cid;
10939                setMountPath(PackageHelper.getSdDir(cid));
10940                return PackageManager.INSTALL_SUCCEEDED;
10941            }
10942
10943            if (temp) {
10944                createCopyFile();
10945            } else {
10946                /*
10947                 * Pre-emptively destroy the container since it's destroyed if
10948                 * copying fails due to it existing anyway.
10949                 */
10950                PackageHelper.destroySdDir(cid);
10951            }
10952
10953            final String newMountPath = imcs.copyPackageToContainer(
10954                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10955                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10956
10957            if (newMountPath != null) {
10958                setMountPath(newMountPath);
10959                return PackageManager.INSTALL_SUCCEEDED;
10960            } else {
10961                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10962            }
10963        }
10964
10965        @Override
10966        String getCodePath() {
10967            return packagePath;
10968        }
10969
10970        @Override
10971        String getResourcePath() {
10972            return resourcePath;
10973        }
10974
10975        int doPreInstall(int status) {
10976            if (status != PackageManager.INSTALL_SUCCEEDED) {
10977                // Destroy container
10978                PackageHelper.destroySdDir(cid);
10979            } else {
10980                boolean mounted = PackageHelper.isContainerMounted(cid);
10981                if (!mounted) {
10982                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10983                            Process.SYSTEM_UID);
10984                    if (newMountPath != null) {
10985                        setMountPath(newMountPath);
10986                    } else {
10987                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10988                    }
10989                }
10990            }
10991            return status;
10992        }
10993
10994        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10995            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10996            String newMountPath = null;
10997            if (PackageHelper.isContainerMounted(cid)) {
10998                // Unmount the container
10999                if (!PackageHelper.unMountSdDir(cid)) {
11000                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11001                    return false;
11002                }
11003            }
11004            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11005                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11006                        " which might be stale. Will try to clean up.");
11007                // Clean up the stale container and proceed to recreate.
11008                if (!PackageHelper.destroySdDir(newCacheId)) {
11009                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11010                    return false;
11011                }
11012                // Successfully cleaned up stale container. Try to rename again.
11013                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11014                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11015                            + " inspite of cleaning it up.");
11016                    return false;
11017                }
11018            }
11019            if (!PackageHelper.isContainerMounted(newCacheId)) {
11020                Slog.w(TAG, "Mounting container " + newCacheId);
11021                newMountPath = PackageHelper.mountSdDir(newCacheId,
11022                        getEncryptKey(), Process.SYSTEM_UID);
11023            } else {
11024                newMountPath = PackageHelper.getSdDir(newCacheId);
11025            }
11026            if (newMountPath == null) {
11027                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11028                return false;
11029            }
11030            Log.i(TAG, "Succesfully renamed " + cid +
11031                    " to " + newCacheId +
11032                    " at new path: " + newMountPath);
11033            cid = newCacheId;
11034
11035            final File beforeCodeFile = new File(packagePath);
11036            setMountPath(newMountPath);
11037            final File afterCodeFile = new File(packagePath);
11038
11039            // Reflect the rename in scanned details
11040            pkg.codePath = afterCodeFile.getAbsolutePath();
11041            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11042                    pkg.baseCodePath);
11043            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11044                    pkg.splitCodePaths);
11045
11046            // Reflect the rename in app info
11047            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11048            pkg.applicationInfo.setCodePath(pkg.codePath);
11049            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11050            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11051            pkg.applicationInfo.setResourcePath(pkg.codePath);
11052            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11053            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11054
11055            return true;
11056        }
11057
11058        private void setMountPath(String mountPath) {
11059            final File mountFile = new File(mountPath);
11060
11061            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11062            if (monolithicFile.exists()) {
11063                packagePath = monolithicFile.getAbsolutePath();
11064                if (isFwdLocked()) {
11065                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11066                } else {
11067                    resourcePath = packagePath;
11068                }
11069            } else {
11070                packagePath = mountFile.getAbsolutePath();
11071                resourcePath = packagePath;
11072            }
11073        }
11074
11075        int doPostInstall(int status, int uid) {
11076            if (status != PackageManager.INSTALL_SUCCEEDED) {
11077                cleanUp();
11078            } else {
11079                final int groupOwner;
11080                final String protectedFile;
11081                if (isFwdLocked()) {
11082                    groupOwner = UserHandle.getSharedAppGid(uid);
11083                    protectedFile = RES_FILE_NAME;
11084                } else {
11085                    groupOwner = -1;
11086                    protectedFile = null;
11087                }
11088
11089                if (uid < Process.FIRST_APPLICATION_UID
11090                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11091                    Slog.e(TAG, "Failed to finalize " + cid);
11092                    PackageHelper.destroySdDir(cid);
11093                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11094                }
11095
11096                boolean mounted = PackageHelper.isContainerMounted(cid);
11097                if (!mounted) {
11098                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11099                }
11100            }
11101            return status;
11102        }
11103
11104        private void cleanUp() {
11105            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11106
11107            // Destroy secure container
11108            PackageHelper.destroySdDir(cid);
11109        }
11110
11111        private List<String> getAllCodePaths() {
11112            final File codeFile = new File(getCodePath());
11113            if (codeFile != null && codeFile.exists()) {
11114                try {
11115                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11116                    return pkg.getAllCodePaths();
11117                } catch (PackageParserException e) {
11118                    // Ignored; we tried our best
11119                }
11120            }
11121            return Collections.EMPTY_LIST;
11122        }
11123
11124        void cleanUpResourcesLI() {
11125            // Enumerate all code paths before deleting
11126            cleanUpResourcesLI(getAllCodePaths());
11127        }
11128
11129        private void cleanUpResourcesLI(List<String> allCodePaths) {
11130            cleanUp();
11131            removeDexFiles(allCodePaths, instructionSets);
11132        }
11133
11134        String getPackageName() {
11135            return getAsecPackageName(cid);
11136        }
11137
11138        boolean doPostDeleteLI(boolean delete) {
11139            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11140            final List<String> allCodePaths = getAllCodePaths();
11141            boolean mounted = PackageHelper.isContainerMounted(cid);
11142            if (mounted) {
11143                // Unmount first
11144                if (PackageHelper.unMountSdDir(cid)) {
11145                    mounted = false;
11146                }
11147            }
11148            if (!mounted && delete) {
11149                cleanUpResourcesLI(allCodePaths);
11150            }
11151            return !mounted;
11152        }
11153
11154        @Override
11155        int doPreCopy() {
11156            if (isFwdLocked()) {
11157                if (!PackageHelper.fixSdPermissions(cid,
11158                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11159                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11160                }
11161            }
11162
11163            return PackageManager.INSTALL_SUCCEEDED;
11164        }
11165
11166        @Override
11167        int doPostCopy(int uid) {
11168            if (isFwdLocked()) {
11169                if (uid < Process.FIRST_APPLICATION_UID
11170                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11171                                RES_FILE_NAME)) {
11172                    Slog.e(TAG, "Failed to finalize " + cid);
11173                    PackageHelper.destroySdDir(cid);
11174                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11175                }
11176            }
11177
11178            return PackageManager.INSTALL_SUCCEEDED;
11179        }
11180    }
11181
11182    /**
11183     * Logic to handle movement of existing installed applications.
11184     */
11185    class MoveInstallArgs extends InstallArgs {
11186        private File codeFile;
11187        private File resourceFile;
11188
11189        /** New install */
11190        MoveInstallArgs(InstallParams params) {
11191            super(params.origin, params.move, params.observer, params.installFlags,
11192                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11193                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11194        }
11195
11196        int copyApk(IMediaContainerService imcs, boolean temp) {
11197            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11198                    + move.fromUuid + " to " + move.toUuid);
11199            synchronized (mInstaller) {
11200                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11201                        move.dataAppName, move.appId, move.seinfo) != 0) {
11202                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11203                }
11204            }
11205
11206            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11207            resourceFile = codeFile;
11208            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11209
11210            return PackageManager.INSTALL_SUCCEEDED;
11211        }
11212
11213        int doPreInstall(int status) {
11214            if (status != PackageManager.INSTALL_SUCCEEDED) {
11215                cleanUp();
11216            }
11217            return status;
11218        }
11219
11220        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11221            if (status != PackageManager.INSTALL_SUCCEEDED) {
11222                cleanUp();
11223                return false;
11224            }
11225
11226            // Reflect the move in app info
11227            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11228            pkg.applicationInfo.setCodePath(pkg.codePath);
11229            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11230            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11231            pkg.applicationInfo.setResourcePath(pkg.codePath);
11232            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11233            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11234
11235            return true;
11236        }
11237
11238        int doPostInstall(int status, int uid) {
11239            if (status != PackageManager.INSTALL_SUCCEEDED) {
11240                cleanUp();
11241            }
11242            return status;
11243        }
11244
11245        @Override
11246        String getCodePath() {
11247            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11248        }
11249
11250        @Override
11251        String getResourcePath() {
11252            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11253        }
11254
11255        private boolean cleanUp() {
11256            if (codeFile == null || !codeFile.exists()) {
11257                return false;
11258            }
11259
11260            if (codeFile.isDirectory()) {
11261                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11262            } else {
11263                codeFile.delete();
11264            }
11265
11266            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11267                resourceFile.delete();
11268            }
11269
11270            return true;
11271        }
11272
11273        void cleanUpResourcesLI() {
11274            cleanUp();
11275        }
11276
11277        boolean doPostDeleteLI(boolean delete) {
11278            // XXX err, shouldn't we respect the delete flag?
11279            cleanUpResourcesLI();
11280            return true;
11281        }
11282    }
11283
11284    static String getAsecPackageName(String packageCid) {
11285        int idx = packageCid.lastIndexOf("-");
11286        if (idx == -1) {
11287            return packageCid;
11288        }
11289        return packageCid.substring(0, idx);
11290    }
11291
11292    // Utility method used to create code paths based on package name and available index.
11293    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11294        String idxStr = "";
11295        int idx = 1;
11296        // Fall back to default value of idx=1 if prefix is not
11297        // part of oldCodePath
11298        if (oldCodePath != null) {
11299            String subStr = oldCodePath;
11300            // Drop the suffix right away
11301            if (suffix != null && subStr.endsWith(suffix)) {
11302                subStr = subStr.substring(0, subStr.length() - suffix.length());
11303            }
11304            // If oldCodePath already contains prefix find out the
11305            // ending index to either increment or decrement.
11306            int sidx = subStr.lastIndexOf(prefix);
11307            if (sidx != -1) {
11308                subStr = subStr.substring(sidx + prefix.length());
11309                if (subStr != null) {
11310                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11311                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11312                    }
11313                    try {
11314                        idx = Integer.parseInt(subStr);
11315                        if (idx <= 1) {
11316                            idx++;
11317                        } else {
11318                            idx--;
11319                        }
11320                    } catch(NumberFormatException e) {
11321                    }
11322                }
11323            }
11324        }
11325        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11326        return prefix + idxStr;
11327    }
11328
11329    private File getNextCodePath(File targetDir, String packageName) {
11330        int suffix = 1;
11331        File result;
11332        do {
11333            result = new File(targetDir, packageName + "-" + suffix);
11334            suffix++;
11335        } while (result.exists());
11336        return result;
11337    }
11338
11339    // Utility method that returns the relative package path with respect
11340    // to the installation directory. Like say for /data/data/com.test-1.apk
11341    // string com.test-1 is returned.
11342    static String deriveCodePathName(String codePath) {
11343        if (codePath == null) {
11344            return null;
11345        }
11346        final File codeFile = new File(codePath);
11347        final String name = codeFile.getName();
11348        if (codeFile.isDirectory()) {
11349            return name;
11350        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11351            final int lastDot = name.lastIndexOf('.');
11352            return name.substring(0, lastDot);
11353        } else {
11354            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11355            return null;
11356        }
11357    }
11358
11359    class PackageInstalledInfo {
11360        String name;
11361        int uid;
11362        // The set of users that originally had this package installed.
11363        int[] origUsers;
11364        // The set of users that now have this package installed.
11365        int[] newUsers;
11366        PackageParser.Package pkg;
11367        int returnCode;
11368        String returnMsg;
11369        PackageRemovedInfo removedInfo;
11370
11371        public void setError(int code, String msg) {
11372            returnCode = code;
11373            returnMsg = msg;
11374            Slog.w(TAG, msg);
11375        }
11376
11377        public void setError(String msg, PackageParserException e) {
11378            returnCode = e.error;
11379            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11380            Slog.w(TAG, msg, e);
11381        }
11382
11383        public void setError(String msg, PackageManagerException e) {
11384            returnCode = e.error;
11385            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11386            Slog.w(TAG, msg, e);
11387        }
11388
11389        // In some error cases we want to convey more info back to the observer
11390        String origPackage;
11391        String origPermission;
11392    }
11393
11394    /*
11395     * Install a non-existing package.
11396     */
11397    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11398            UserHandle user, String installerPackageName, String volumeUuid,
11399            PackageInstalledInfo res) {
11400        // Remember this for later, in case we need to rollback this install
11401        String pkgName = pkg.packageName;
11402
11403        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11404        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
11405                UserHandle.USER_OWNER).exists();
11406        synchronized(mPackages) {
11407            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11408                // A package with the same name is already installed, though
11409                // it has been renamed to an older name.  The package we
11410                // are trying to install should be installed as an update to
11411                // the existing one, but that has not been requested, so bail.
11412                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11413                        + " without first uninstalling package running as "
11414                        + mSettings.mRenamedPackages.get(pkgName));
11415                return;
11416            }
11417            if (mPackages.containsKey(pkgName)) {
11418                // Don't allow installation over an existing package with the same name.
11419                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11420                        + " without first uninstalling.");
11421                return;
11422            }
11423        }
11424
11425        try {
11426            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11427                    System.currentTimeMillis(), user);
11428
11429            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11430            // delete the partially installed application. the data directory will have to be
11431            // restored if it was already existing
11432            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11433                // remove package from internal structures.  Note that we want deletePackageX to
11434                // delete the package data and cache directories that it created in
11435                // scanPackageLocked, unless those directories existed before we even tried to
11436                // install.
11437                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11438                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11439                                res.removedInfo, true);
11440            }
11441
11442        } catch (PackageManagerException e) {
11443            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11444        }
11445    }
11446
11447    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11448        // Can't rotate keys during boot or if sharedUser.
11449        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11450                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11451            return false;
11452        }
11453        // app is using upgradeKeySets; make sure all are valid
11454        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11455        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11456        for (int i = 0; i < upgradeKeySets.length; i++) {
11457            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11458                Slog.wtf(TAG, "Package "
11459                         + (oldPs.name != null ? oldPs.name : "<null>")
11460                         + " contains upgrade-key-set reference to unknown key-set: "
11461                         + upgradeKeySets[i]
11462                         + " reverting to signatures check.");
11463                return false;
11464            }
11465        }
11466        return true;
11467    }
11468
11469    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11470        // Upgrade keysets are being used.  Determine if new package has a superset of the
11471        // required keys.
11472        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11473        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11474        for (int i = 0; i < upgradeKeySets.length; i++) {
11475            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11476            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11477                return true;
11478            }
11479        }
11480        return false;
11481    }
11482
11483    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11484            UserHandle user, String installerPackageName, String volumeUuid,
11485            PackageInstalledInfo res) {
11486        final PackageParser.Package oldPackage;
11487        final String pkgName = pkg.packageName;
11488        final int[] allUsers;
11489        final boolean[] perUserInstalled;
11490        final boolean weFroze;
11491
11492        // First find the old package info and check signatures
11493        synchronized(mPackages) {
11494            oldPackage = mPackages.get(pkgName);
11495            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11496            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11497            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11498                if(!checkUpgradeKeySetLP(ps, pkg)) {
11499                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11500                            "New package not signed by keys specified by upgrade-keysets: "
11501                            + pkgName);
11502                    return;
11503                }
11504            } else {
11505                // default to original signature matching
11506                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11507                    != PackageManager.SIGNATURE_MATCH) {
11508                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11509                            "New package has a different signature: " + pkgName);
11510                    return;
11511                }
11512            }
11513
11514            // In case of rollback, remember per-user/profile install state
11515            allUsers = sUserManager.getUserIds();
11516            perUserInstalled = new boolean[allUsers.length];
11517            for (int i = 0; i < allUsers.length; i++) {
11518                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11519            }
11520
11521            // Mark the app as frozen to prevent launching during the upgrade
11522            // process, and then kill all running instances
11523            if (!ps.frozen) {
11524                ps.frozen = true;
11525                weFroze = true;
11526            } else {
11527                weFroze = false;
11528            }
11529        }
11530
11531        // Now that we're guarded by frozen state, kill app during upgrade
11532        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11533
11534        try {
11535            boolean sysPkg = (isSystemApp(oldPackage));
11536            if (sysPkg) {
11537                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11538                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11539            } else {
11540                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11541                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11542            }
11543        } finally {
11544            // Regardless of success or failure of upgrade steps above, always
11545            // unfreeze the package if we froze it
11546            if (weFroze) {
11547                unfreezePackage(pkgName);
11548            }
11549        }
11550    }
11551
11552    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11553            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11554            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11555            String volumeUuid, PackageInstalledInfo res) {
11556        String pkgName = deletedPackage.packageName;
11557        boolean deletedPkg = true;
11558        boolean updatedSettings = false;
11559
11560        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11561                + deletedPackage);
11562        long origUpdateTime;
11563        if (pkg.mExtras != null) {
11564            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11565        } else {
11566            origUpdateTime = 0;
11567        }
11568
11569        // First delete the existing package while retaining the data directory
11570        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11571                res.removedInfo, true)) {
11572            // If the existing package wasn't successfully deleted
11573            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11574            deletedPkg = false;
11575        } else {
11576            // Successfully deleted the old package; proceed with replace.
11577
11578            // If deleted package lived in a container, give users a chance to
11579            // relinquish resources before killing.
11580            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11581                if (DEBUG_INSTALL) {
11582                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11583                }
11584                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11585                final ArrayList<String> pkgList = new ArrayList<String>(1);
11586                pkgList.add(deletedPackage.applicationInfo.packageName);
11587                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11588            }
11589
11590            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11591            try {
11592                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11593                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11594                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11595                        perUserInstalled, res, user);
11596                updatedSettings = true;
11597            } catch (PackageManagerException e) {
11598                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11599            }
11600        }
11601
11602        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11603            // remove package from internal structures.  Note that we want deletePackageX to
11604            // delete the package data and cache directories that it created in
11605            // scanPackageLocked, unless those directories existed before we even tried to
11606            // install.
11607            if(updatedSettings) {
11608                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11609                deletePackageLI(
11610                        pkgName, null, true, allUsers, perUserInstalled,
11611                        PackageManager.DELETE_KEEP_DATA,
11612                                res.removedInfo, true);
11613            }
11614            // Since we failed to install the new package we need to restore the old
11615            // package that we deleted.
11616            if (deletedPkg) {
11617                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11618                File restoreFile = new File(deletedPackage.codePath);
11619                // Parse old package
11620                boolean oldExternal = isExternal(deletedPackage);
11621                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11622                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11623                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11624                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11625                try {
11626                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11627                } catch (PackageManagerException e) {
11628                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11629                            + e.getMessage());
11630                    return;
11631                }
11632                // Restore of old package succeeded. Update permissions.
11633                // writer
11634                synchronized (mPackages) {
11635                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11636                            UPDATE_PERMISSIONS_ALL);
11637                    // can downgrade to reader
11638                    mSettings.writeLPr();
11639                }
11640                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11641            }
11642        }
11643    }
11644
11645    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11646            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11647            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11648            String volumeUuid, PackageInstalledInfo res) {
11649        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11650                + ", old=" + deletedPackage);
11651        boolean disabledSystem = false;
11652        boolean updatedSettings = false;
11653        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11654        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11655                != 0) {
11656            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11657        }
11658        String packageName = deletedPackage.packageName;
11659        if (packageName == null) {
11660            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11661                    "Attempt to delete null packageName.");
11662            return;
11663        }
11664        PackageParser.Package oldPkg;
11665        PackageSetting oldPkgSetting;
11666        // reader
11667        synchronized (mPackages) {
11668            oldPkg = mPackages.get(packageName);
11669            oldPkgSetting = mSettings.mPackages.get(packageName);
11670            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11671                    (oldPkgSetting == null)) {
11672                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11673                        "Couldn't find package:" + packageName + " information");
11674                return;
11675            }
11676        }
11677
11678        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11679        res.removedInfo.removedPackage = packageName;
11680        // Remove existing system package
11681        removePackageLI(oldPkgSetting, true);
11682        // writer
11683        synchronized (mPackages) {
11684            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11685            if (!disabledSystem && deletedPackage != null) {
11686                // We didn't need to disable the .apk as a current system package,
11687                // which means we are replacing another update that is already
11688                // installed.  We need to make sure to delete the older one's .apk.
11689                res.removedInfo.args = createInstallArgsForExisting(0,
11690                        deletedPackage.applicationInfo.getCodePath(),
11691                        deletedPackage.applicationInfo.getResourcePath(),
11692                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11693            } else {
11694                res.removedInfo.args = null;
11695            }
11696        }
11697
11698        // Successfully disabled the old package. Now proceed with re-installation
11699        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11700
11701        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11702        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11703
11704        PackageParser.Package newPackage = null;
11705        try {
11706            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11707            if (newPackage.mExtras != null) {
11708                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11709                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11710                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11711
11712                // is the update attempting to change shared user? that isn't going to work...
11713                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11714                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11715                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11716                            + " to " + newPkgSetting.sharedUser);
11717                    updatedSettings = true;
11718                }
11719            }
11720
11721            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11722                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11723                        perUserInstalled, res, user);
11724                updatedSettings = true;
11725            }
11726
11727        } catch (PackageManagerException e) {
11728            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11729        }
11730
11731        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11732            // Re installation failed. Restore old information
11733            // Remove new pkg information
11734            if (newPackage != null) {
11735                removeInstalledPackageLI(newPackage, true);
11736            }
11737            // Add back the old system package
11738            try {
11739                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11740            } catch (PackageManagerException e) {
11741                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11742            }
11743            // Restore the old system information in Settings
11744            synchronized (mPackages) {
11745                if (disabledSystem) {
11746                    mSettings.enableSystemPackageLPw(packageName);
11747                }
11748                if (updatedSettings) {
11749                    mSettings.setInstallerPackageName(packageName,
11750                            oldPkgSetting.installerPackageName);
11751                }
11752                mSettings.writeLPr();
11753            }
11754        }
11755    }
11756
11757    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11758            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11759            UserHandle user) {
11760        String pkgName = newPackage.packageName;
11761        synchronized (mPackages) {
11762            //write settings. the installStatus will be incomplete at this stage.
11763            //note that the new package setting would have already been
11764            //added to mPackages. It hasn't been persisted yet.
11765            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11766            mSettings.writeLPr();
11767        }
11768
11769        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11770
11771        synchronized (mPackages) {
11772            updatePermissionsLPw(newPackage.packageName, newPackage,
11773                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11774                            ? UPDATE_PERMISSIONS_ALL : 0));
11775            // For system-bundled packages, we assume that installing an upgraded version
11776            // of the package implies that the user actually wants to run that new code,
11777            // so we enable the package.
11778            PackageSetting ps = mSettings.mPackages.get(pkgName);
11779            if (ps != null) {
11780                if (isSystemApp(newPackage)) {
11781                    // NB: implicit assumption that system package upgrades apply to all users
11782                    if (DEBUG_INSTALL) {
11783                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11784                    }
11785                    if (res.origUsers != null) {
11786                        for (int userHandle : res.origUsers) {
11787                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11788                                    userHandle, installerPackageName);
11789                        }
11790                    }
11791                    // Also convey the prior install/uninstall state
11792                    if (allUsers != null && perUserInstalled != null) {
11793                        for (int i = 0; i < allUsers.length; i++) {
11794                            if (DEBUG_INSTALL) {
11795                                Slog.d(TAG, "    user " + allUsers[i]
11796                                        + " => " + perUserInstalled[i]);
11797                            }
11798                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11799                        }
11800                        // these install state changes will be persisted in the
11801                        // upcoming call to mSettings.writeLPr().
11802                    }
11803                }
11804                // It's implied that when a user requests installation, they want the app to be
11805                // installed and enabled.
11806                int userId = user.getIdentifier();
11807                if (userId != UserHandle.USER_ALL) {
11808                    ps.setInstalled(true, userId);
11809                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11810                }
11811            }
11812            res.name = pkgName;
11813            res.uid = newPackage.applicationInfo.uid;
11814            res.pkg = newPackage;
11815            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11816            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11817            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11818            //to update install status
11819            mSettings.writeLPr();
11820        }
11821    }
11822
11823    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11824        final int installFlags = args.installFlags;
11825        final String installerPackageName = args.installerPackageName;
11826        final String volumeUuid = args.volumeUuid;
11827        final File tmpPackageFile = new File(args.getCodePath());
11828        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11829        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11830                || (args.volumeUuid != null));
11831        boolean replace = false;
11832        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11833        if (args.move != null) {
11834            // moving a complete application; perfom an initial scan on the new install location
11835            scanFlags |= SCAN_INITIAL;
11836        }
11837        // Result object to be returned
11838        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11839
11840        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11841        // Retrieve PackageSettings and parse package
11842        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11843                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11844                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11845        PackageParser pp = new PackageParser();
11846        pp.setSeparateProcesses(mSeparateProcesses);
11847        pp.setDisplayMetrics(mMetrics);
11848
11849        final PackageParser.Package pkg;
11850        try {
11851            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11852        } catch (PackageParserException e) {
11853            res.setError("Failed parse during installPackageLI", e);
11854            return;
11855        }
11856
11857        // Mark that we have an install time CPU ABI override.
11858        pkg.cpuAbiOverride = args.abiOverride;
11859
11860        String pkgName = res.name = pkg.packageName;
11861        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11862            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11863                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11864                return;
11865            }
11866        }
11867
11868        try {
11869            pp.collectCertificates(pkg, parseFlags);
11870            pp.collectManifestDigest(pkg);
11871        } catch (PackageParserException e) {
11872            res.setError("Failed collect during installPackageLI", e);
11873            return;
11874        }
11875
11876        /* If the installer passed in a manifest digest, compare it now. */
11877        if (args.manifestDigest != null) {
11878            if (DEBUG_INSTALL) {
11879                final String parsedManifest = pkg.manifestDigest == null ? "null"
11880                        : pkg.manifestDigest.toString();
11881                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11882                        + parsedManifest);
11883            }
11884
11885            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11886                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11887                return;
11888            }
11889        } else if (DEBUG_INSTALL) {
11890            final String parsedManifest = pkg.manifestDigest == null
11891                    ? "null" : pkg.manifestDigest.toString();
11892            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11893        }
11894
11895        // Get rid of all references to package scan path via parser.
11896        pp = null;
11897        String oldCodePath = null;
11898        boolean systemApp = false;
11899        synchronized (mPackages) {
11900            // Check if installing already existing package
11901            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11902                String oldName = mSettings.mRenamedPackages.get(pkgName);
11903                if (pkg.mOriginalPackages != null
11904                        && pkg.mOriginalPackages.contains(oldName)
11905                        && mPackages.containsKey(oldName)) {
11906                    // This package is derived from an original package,
11907                    // and this device has been updating from that original
11908                    // name.  We must continue using the original name, so
11909                    // rename the new package here.
11910                    pkg.setPackageName(oldName);
11911                    pkgName = pkg.packageName;
11912                    replace = true;
11913                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11914                            + oldName + " pkgName=" + pkgName);
11915                } else if (mPackages.containsKey(pkgName)) {
11916                    // This package, under its official name, already exists
11917                    // on the device; we should replace it.
11918                    replace = true;
11919                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11920                }
11921
11922                // Prevent apps opting out from runtime permissions
11923                if (replace) {
11924                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11925                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11926                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11927                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11928                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11929                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11930                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11931                                        + " doesn't support runtime permissions but the old"
11932                                        + " target SDK " + oldTargetSdk + " does.");
11933                        return;
11934                    }
11935                }
11936            }
11937
11938            PackageSetting ps = mSettings.mPackages.get(pkgName);
11939            if (ps != null) {
11940                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11941
11942                // Quick sanity check that we're signed correctly if updating;
11943                // we'll check this again later when scanning, but we want to
11944                // bail early here before tripping over redefined permissions.
11945                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11946                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11947                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11948                                + pkg.packageName + " upgrade keys do not match the "
11949                                + "previously installed version");
11950                        return;
11951                    }
11952                } else {
11953                    try {
11954                        verifySignaturesLP(ps, pkg);
11955                    } catch (PackageManagerException e) {
11956                        res.setError(e.error, e.getMessage());
11957                        return;
11958                    }
11959                }
11960
11961                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11962                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11963                    systemApp = (ps.pkg.applicationInfo.flags &
11964                            ApplicationInfo.FLAG_SYSTEM) != 0;
11965                }
11966                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11967            }
11968
11969            // Check whether the newly-scanned package wants to define an already-defined perm
11970            int N = pkg.permissions.size();
11971            for (int i = N-1; i >= 0; i--) {
11972                PackageParser.Permission perm = pkg.permissions.get(i);
11973                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11974                if (bp != null) {
11975                    // If the defining package is signed with our cert, it's okay.  This
11976                    // also includes the "updating the same package" case, of course.
11977                    // "updating same package" could also involve key-rotation.
11978                    final boolean sigsOk;
11979                    if (bp.sourcePackage.equals(pkg.packageName)
11980                            && (bp.packageSetting instanceof PackageSetting)
11981                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
11982                                    scanFlags))) {
11983                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11984                    } else {
11985                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11986                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11987                    }
11988                    if (!sigsOk) {
11989                        // If the owning package is the system itself, we log but allow
11990                        // install to proceed; we fail the install on all other permission
11991                        // redefinitions.
11992                        if (!bp.sourcePackage.equals("android")) {
11993                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11994                                    + pkg.packageName + " attempting to redeclare permission "
11995                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11996                            res.origPermission = perm.info.name;
11997                            res.origPackage = bp.sourcePackage;
11998                            return;
11999                        } else {
12000                            Slog.w(TAG, "Package " + pkg.packageName
12001                                    + " attempting to redeclare system permission "
12002                                    + perm.info.name + "; ignoring new declaration");
12003                            pkg.permissions.remove(i);
12004                        }
12005                    }
12006                }
12007            }
12008
12009        }
12010
12011        if (systemApp && onExternal) {
12012            // Disable updates to system apps on sdcard
12013            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12014                    "Cannot install updates to system apps on sdcard");
12015            return;
12016        }
12017
12018        if (args.move != null) {
12019            // We did an in-place move, so dex is ready to roll
12020            scanFlags |= SCAN_NO_DEX;
12021            scanFlags |= SCAN_MOVE;
12022        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12023            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12024            scanFlags |= SCAN_NO_DEX;
12025
12026            try {
12027                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12028                        true /* extract libs */);
12029            } catch (PackageManagerException pme) {
12030                Slog.e(TAG, "Error deriving application ABI", pme);
12031                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12032                return;
12033            }
12034
12035            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12036            int result = mPackageDexOptimizer
12037                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12038                            false /* defer */, false /* inclDependencies */);
12039            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12040                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12041                return;
12042            }
12043        }
12044
12045        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12046            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12047            return;
12048        }
12049
12050        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12051
12052        if (replace) {
12053            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12054                    installerPackageName, volumeUuid, res);
12055        } else {
12056            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12057                    args.user, installerPackageName, volumeUuid, res);
12058        }
12059        synchronized (mPackages) {
12060            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12061            if (ps != null) {
12062                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12063            }
12064        }
12065    }
12066
12067    private void startIntentFilterVerifications(int userId, boolean replacing,
12068            PackageParser.Package pkg) {
12069        if (mIntentFilterVerifierComponent == null) {
12070            Slog.w(TAG, "No IntentFilter verification will not be done as "
12071                    + "there is no IntentFilterVerifier available!");
12072            return;
12073        }
12074
12075        final int verifierUid = getPackageUid(
12076                mIntentFilterVerifierComponent.getPackageName(),
12077                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12078
12079        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12080        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12081        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12082        mHandler.sendMessage(msg);
12083    }
12084
12085    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12086            PackageParser.Package pkg) {
12087        int size = pkg.activities.size();
12088        if (size == 0) {
12089            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12090                    "No activity, so no need to verify any IntentFilter!");
12091            return;
12092        }
12093
12094        final boolean hasDomainURLs = hasDomainURLs(pkg);
12095        if (!hasDomainURLs) {
12096            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12097                    "No domain URLs, so no need to verify any IntentFilter!");
12098            return;
12099        }
12100
12101        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12102                + " if any IntentFilter from the " + size
12103                + " Activities needs verification ...");
12104
12105        int count = 0;
12106        final String packageName = pkg.packageName;
12107
12108        synchronized (mPackages) {
12109            // If this is a new install and we see that we've already run verification for this
12110            // package, we have nothing to do: it means the state was restored from backup.
12111            if (!replacing) {
12112                IntentFilterVerificationInfo ivi =
12113                        mSettings.getIntentFilterVerificationLPr(packageName);
12114                if (ivi != null) {
12115                    if (DEBUG_DOMAIN_VERIFICATION) {
12116                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12117                                + ivi.getStatusString());
12118                    }
12119                    return;
12120                }
12121            }
12122
12123            // If any filters need to be verified, then all need to be.
12124            boolean needToVerify = false;
12125            for (PackageParser.Activity a : pkg.activities) {
12126                for (ActivityIntentInfo filter : a.intents) {
12127                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12128                        if (DEBUG_DOMAIN_VERIFICATION) {
12129                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12130                        }
12131                        needToVerify = true;
12132                        break;
12133                    }
12134                }
12135            }
12136
12137            if (needToVerify) {
12138                final int verificationId = mIntentFilterVerificationToken++;
12139                for (PackageParser.Activity a : pkg.activities) {
12140                    for (ActivityIntentInfo filter : a.intents) {
12141                        if (filter.hasOnlyWebDataURI() && needsNetworkVerificationLPr(filter)) {
12142                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12143                                    "Verification needed for IntentFilter:" + filter.toString());
12144                            mIntentFilterVerifier.addOneIntentFilterVerification(
12145                                    verifierUid, userId, verificationId, filter, packageName);
12146                            count++;
12147                        }
12148                    }
12149                }
12150            }
12151        }
12152
12153        if (count > 0) {
12154            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12155                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12156                    +  " for userId:" + userId);
12157            mIntentFilterVerifier.startVerifications(userId);
12158        } else {
12159            if (DEBUG_DOMAIN_VERIFICATION) {
12160                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12161            }
12162        }
12163    }
12164
12165    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12166        final ComponentName cn  = filter.activity.getComponentName();
12167        final String packageName = cn.getPackageName();
12168
12169        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12170                packageName);
12171        if (ivi == null) {
12172            return true;
12173        }
12174        int status = ivi.getStatus();
12175        switch (status) {
12176            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12177            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12178                return true;
12179
12180            default:
12181                // Nothing to do
12182                return false;
12183        }
12184    }
12185
12186    private static boolean isMultiArch(PackageSetting ps) {
12187        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12188    }
12189
12190    private static boolean isMultiArch(ApplicationInfo info) {
12191        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12192    }
12193
12194    private static boolean isExternal(PackageParser.Package pkg) {
12195        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12196    }
12197
12198    private static boolean isExternal(PackageSetting ps) {
12199        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12200    }
12201
12202    private static boolean isExternal(ApplicationInfo info) {
12203        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12204    }
12205
12206    private static boolean isSystemApp(PackageParser.Package pkg) {
12207        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12208    }
12209
12210    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12211        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12212    }
12213
12214    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12215        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12216    }
12217
12218    private static boolean isSystemApp(PackageSetting ps) {
12219        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12220    }
12221
12222    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12223        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12224    }
12225
12226    private int packageFlagsToInstallFlags(PackageSetting ps) {
12227        int installFlags = 0;
12228        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12229            // This existing package was an external ASEC install when we have
12230            // the external flag without a UUID
12231            installFlags |= PackageManager.INSTALL_EXTERNAL;
12232        }
12233        if (ps.isForwardLocked()) {
12234            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12235        }
12236        return installFlags;
12237    }
12238
12239    private void deleteTempPackageFiles() {
12240        final FilenameFilter filter = new FilenameFilter() {
12241            public boolean accept(File dir, String name) {
12242                return name.startsWith("vmdl") && name.endsWith(".tmp");
12243            }
12244        };
12245        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12246            file.delete();
12247        }
12248    }
12249
12250    @Override
12251    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12252            int flags) {
12253        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12254                flags);
12255    }
12256
12257    @Override
12258    public void deletePackage(final String packageName,
12259            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12260        mContext.enforceCallingOrSelfPermission(
12261                android.Manifest.permission.DELETE_PACKAGES, null);
12262        final int uid = Binder.getCallingUid();
12263        if (UserHandle.getUserId(uid) != userId) {
12264            mContext.enforceCallingPermission(
12265                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12266                    "deletePackage for user " + userId);
12267        }
12268        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12269            try {
12270                observer.onPackageDeleted(packageName,
12271                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12272            } catch (RemoteException re) {
12273            }
12274            return;
12275        }
12276
12277        boolean uninstallBlocked = false;
12278        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12279            int[] users = sUserManager.getUserIds();
12280            for (int i = 0; i < users.length; ++i) {
12281                if (getBlockUninstallForUser(packageName, users[i])) {
12282                    uninstallBlocked = true;
12283                    break;
12284                }
12285            }
12286        } else {
12287            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12288        }
12289        if (uninstallBlocked) {
12290            try {
12291                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12292                        null);
12293            } catch (RemoteException re) {
12294            }
12295            return;
12296        }
12297
12298        if (DEBUG_REMOVE) {
12299            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12300        }
12301        // Queue up an async operation since the package deletion may take a little while.
12302        mHandler.post(new Runnable() {
12303            public void run() {
12304                mHandler.removeCallbacks(this);
12305                final int returnCode = deletePackageX(packageName, userId, flags);
12306                if (observer != null) {
12307                    try {
12308                        observer.onPackageDeleted(packageName, returnCode, null);
12309                    } catch (RemoteException e) {
12310                        Log.i(TAG, "Observer no longer exists.");
12311                    } //end catch
12312                } //end if
12313            } //end run
12314        });
12315    }
12316
12317    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12318        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12319                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12320        try {
12321            if (dpm != null) {
12322                if (dpm.isDeviceOwner(packageName)) {
12323                    return true;
12324                }
12325                int[] users;
12326                if (userId == UserHandle.USER_ALL) {
12327                    users = sUserManager.getUserIds();
12328                } else {
12329                    users = new int[]{userId};
12330                }
12331                for (int i = 0; i < users.length; ++i) {
12332                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12333                        return true;
12334                    }
12335                }
12336            }
12337        } catch (RemoteException e) {
12338        }
12339        return false;
12340    }
12341
12342    /**
12343     *  This method is an internal method that could be get invoked either
12344     *  to delete an installed package or to clean up a failed installation.
12345     *  After deleting an installed package, a broadcast is sent to notify any
12346     *  listeners that the package has been installed. For cleaning up a failed
12347     *  installation, the broadcast is not necessary since the package's
12348     *  installation wouldn't have sent the initial broadcast either
12349     *  The key steps in deleting a package are
12350     *  deleting the package information in internal structures like mPackages,
12351     *  deleting the packages base directories through installd
12352     *  updating mSettings to reflect current status
12353     *  persisting settings for later use
12354     *  sending a broadcast if necessary
12355     */
12356    private int deletePackageX(String packageName, int userId, int flags) {
12357        final PackageRemovedInfo info = new PackageRemovedInfo();
12358        final boolean res;
12359
12360        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12361                ? UserHandle.ALL : new UserHandle(userId);
12362
12363        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12364            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12365            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12366        }
12367
12368        boolean removedForAllUsers = false;
12369        boolean systemUpdate = false;
12370
12371        // for the uninstall-updates case and restricted profiles, remember the per-
12372        // userhandle installed state
12373        int[] allUsers;
12374        boolean[] perUserInstalled;
12375        synchronized (mPackages) {
12376            PackageSetting ps = mSettings.mPackages.get(packageName);
12377            allUsers = sUserManager.getUserIds();
12378            perUserInstalled = new boolean[allUsers.length];
12379            for (int i = 0; i < allUsers.length; i++) {
12380                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12381            }
12382        }
12383
12384        synchronized (mInstallLock) {
12385            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12386            res = deletePackageLI(packageName, removeForUser,
12387                    true, allUsers, perUserInstalled,
12388                    flags | REMOVE_CHATTY, info, true);
12389            systemUpdate = info.isRemovedPackageSystemUpdate;
12390            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12391                removedForAllUsers = true;
12392            }
12393            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12394                    + " removedForAllUsers=" + removedForAllUsers);
12395        }
12396
12397        if (res) {
12398            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12399
12400            // If the removed package was a system update, the old system package
12401            // was re-enabled; we need to broadcast this information
12402            if (systemUpdate) {
12403                Bundle extras = new Bundle(1);
12404                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12405                        ? info.removedAppId : info.uid);
12406                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12407
12408                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12409                        extras, null, null, null);
12410                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12411                        extras, null, null, null);
12412                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12413                        null, packageName, null, null);
12414            }
12415        }
12416        // Force a gc here.
12417        Runtime.getRuntime().gc();
12418        // Delete the resources here after sending the broadcast to let
12419        // other processes clean up before deleting resources.
12420        if (info.args != null) {
12421            synchronized (mInstallLock) {
12422                info.args.doPostDeleteLI(true);
12423            }
12424        }
12425
12426        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12427    }
12428
12429    class PackageRemovedInfo {
12430        String removedPackage;
12431        int uid = -1;
12432        int removedAppId = -1;
12433        int[] removedUsers = null;
12434        boolean isRemovedPackageSystemUpdate = false;
12435        // Clean up resources deleted packages.
12436        InstallArgs args = null;
12437
12438        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12439            Bundle extras = new Bundle(1);
12440            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12441            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12442            if (replacing) {
12443                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12444            }
12445            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12446            if (removedPackage != null) {
12447                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12448                        extras, null, null, removedUsers);
12449                if (fullRemove && !replacing) {
12450                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12451                            extras, null, null, removedUsers);
12452                }
12453            }
12454            if (removedAppId >= 0) {
12455                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12456                        removedUsers);
12457            }
12458        }
12459    }
12460
12461    /*
12462     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12463     * flag is not set, the data directory is removed as well.
12464     * make sure this flag is set for partially installed apps. If not its meaningless to
12465     * delete a partially installed application.
12466     */
12467    private void removePackageDataLI(PackageSetting ps,
12468            int[] allUserHandles, boolean[] perUserInstalled,
12469            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12470        String packageName = ps.name;
12471        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12472        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12473        // Retrieve object to delete permissions for shared user later on
12474        final PackageSetting deletedPs;
12475        // reader
12476        synchronized (mPackages) {
12477            deletedPs = mSettings.mPackages.get(packageName);
12478            if (outInfo != null) {
12479                outInfo.removedPackage = packageName;
12480                outInfo.removedUsers = deletedPs != null
12481                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12482                        : null;
12483            }
12484        }
12485        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12486            removeDataDirsLI(ps.volumeUuid, packageName);
12487            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12488        }
12489        // writer
12490        synchronized (mPackages) {
12491            if (deletedPs != null) {
12492                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12493                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12494                    clearDefaultBrowserIfNeeded(packageName);
12495                    if (outInfo != null) {
12496                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12497                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12498                    }
12499                    updatePermissionsLPw(deletedPs.name, null, 0);
12500                    if (deletedPs.sharedUser != null) {
12501                        // Remove permissions associated with package. Since runtime
12502                        // permissions are per user we have to kill the removed package
12503                        // or packages running under the shared user of the removed
12504                        // package if revoking the permissions requested only by the removed
12505                        // package is successful and this causes a change in gids.
12506                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12507                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12508                                    userId);
12509                            if (userIdToKill == UserHandle.USER_ALL
12510                                    || userIdToKill >= UserHandle.USER_OWNER) {
12511                                // If gids changed for this user, kill all affected packages.
12512                                mHandler.post(new Runnable() {
12513                                    @Override
12514                                    public void run() {
12515                                        // This has to happen with no lock held.
12516                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12517                                                KILL_APP_REASON_GIDS_CHANGED);
12518                                    }
12519                                });
12520                            break;
12521                            }
12522                        }
12523                    }
12524                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12525                }
12526                // make sure to preserve per-user disabled state if this removal was just
12527                // a downgrade of a system app to the factory package
12528                if (allUserHandles != null && perUserInstalled != null) {
12529                    if (DEBUG_REMOVE) {
12530                        Slog.d(TAG, "Propagating install state across downgrade");
12531                    }
12532                    for (int i = 0; i < allUserHandles.length; i++) {
12533                        if (DEBUG_REMOVE) {
12534                            Slog.d(TAG, "    user " + allUserHandles[i]
12535                                    + " => " + perUserInstalled[i]);
12536                        }
12537                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12538                    }
12539                }
12540            }
12541            // can downgrade to reader
12542            if (writeSettings) {
12543                // Save settings now
12544                mSettings.writeLPr();
12545            }
12546        }
12547        if (outInfo != null) {
12548            // A user ID was deleted here. Go through all users and remove it
12549            // from KeyStore.
12550            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12551        }
12552    }
12553
12554    static boolean locationIsPrivileged(File path) {
12555        try {
12556            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12557                    .getCanonicalPath();
12558            return path.getCanonicalPath().startsWith(privilegedAppDir);
12559        } catch (IOException e) {
12560            Slog.e(TAG, "Unable to access code path " + path);
12561        }
12562        return false;
12563    }
12564
12565    /*
12566     * Tries to delete system package.
12567     */
12568    private boolean deleteSystemPackageLI(PackageSetting newPs,
12569            int[] allUserHandles, boolean[] perUserInstalled,
12570            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12571        final boolean applyUserRestrictions
12572                = (allUserHandles != null) && (perUserInstalled != null);
12573        PackageSetting disabledPs = null;
12574        // Confirm if the system package has been updated
12575        // An updated system app can be deleted. This will also have to restore
12576        // the system pkg from system partition
12577        // reader
12578        synchronized (mPackages) {
12579            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12580        }
12581        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12582                + " disabledPs=" + disabledPs);
12583        if (disabledPs == null) {
12584            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12585            return false;
12586        } else if (DEBUG_REMOVE) {
12587            Slog.d(TAG, "Deleting system pkg from data partition");
12588        }
12589        if (DEBUG_REMOVE) {
12590            if (applyUserRestrictions) {
12591                Slog.d(TAG, "Remembering install states:");
12592                for (int i = 0; i < allUserHandles.length; i++) {
12593                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12594                }
12595            }
12596        }
12597        // Delete the updated package
12598        outInfo.isRemovedPackageSystemUpdate = true;
12599        if (disabledPs.versionCode < newPs.versionCode) {
12600            // Delete data for downgrades
12601            flags &= ~PackageManager.DELETE_KEEP_DATA;
12602        } else {
12603            // Preserve data by setting flag
12604            flags |= PackageManager.DELETE_KEEP_DATA;
12605        }
12606        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12607                allUserHandles, perUserInstalled, outInfo, writeSettings);
12608        if (!ret) {
12609            return false;
12610        }
12611        // writer
12612        synchronized (mPackages) {
12613            // Reinstate the old system package
12614            mSettings.enableSystemPackageLPw(newPs.name);
12615            // Remove any native libraries from the upgraded package.
12616            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12617        }
12618        // Install the system package
12619        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12620        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12621        if (locationIsPrivileged(disabledPs.codePath)) {
12622            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12623        }
12624
12625        final PackageParser.Package newPkg;
12626        try {
12627            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12628        } catch (PackageManagerException e) {
12629            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12630            return false;
12631        }
12632
12633        // writer
12634        synchronized (mPackages) {
12635            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12636            updatePermissionsLPw(newPkg.packageName, newPkg,
12637                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12638            if (applyUserRestrictions) {
12639                if (DEBUG_REMOVE) {
12640                    Slog.d(TAG, "Propagating install state across reinstall");
12641                }
12642                for (int i = 0; i < allUserHandles.length; i++) {
12643                    if (DEBUG_REMOVE) {
12644                        Slog.d(TAG, "    user " + allUserHandles[i]
12645                                + " => " + perUserInstalled[i]);
12646                    }
12647                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12648                }
12649                // Regardless of writeSettings we need to ensure that this restriction
12650                // state propagation is persisted
12651                mSettings.writeAllUsersPackageRestrictionsLPr();
12652            }
12653            // can downgrade to reader here
12654            if (writeSettings) {
12655                mSettings.writeLPr();
12656            }
12657        }
12658        return true;
12659    }
12660
12661    private boolean deleteInstalledPackageLI(PackageSetting ps,
12662            boolean deleteCodeAndResources, int flags,
12663            int[] allUserHandles, boolean[] perUserInstalled,
12664            PackageRemovedInfo outInfo, boolean writeSettings) {
12665        if (outInfo != null) {
12666            outInfo.uid = ps.appId;
12667        }
12668
12669        // Delete package data from internal structures and also remove data if flag is set
12670        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12671
12672        // Delete application code and resources
12673        if (deleteCodeAndResources && (outInfo != null)) {
12674            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12675                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12676            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12677        }
12678        return true;
12679    }
12680
12681    @Override
12682    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12683            int userId) {
12684        mContext.enforceCallingOrSelfPermission(
12685                android.Manifest.permission.DELETE_PACKAGES, null);
12686        synchronized (mPackages) {
12687            PackageSetting ps = mSettings.mPackages.get(packageName);
12688            if (ps == null) {
12689                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12690                return false;
12691            }
12692            if (!ps.getInstalled(userId)) {
12693                // Can't block uninstall for an app that is not installed or enabled.
12694                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12695                return false;
12696            }
12697            ps.setBlockUninstall(blockUninstall, userId);
12698            mSettings.writePackageRestrictionsLPr(userId);
12699        }
12700        return true;
12701    }
12702
12703    @Override
12704    public boolean getBlockUninstallForUser(String packageName, int userId) {
12705        synchronized (mPackages) {
12706            PackageSetting ps = mSettings.mPackages.get(packageName);
12707            if (ps == null) {
12708                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12709                return false;
12710            }
12711            return ps.getBlockUninstall(userId);
12712        }
12713    }
12714
12715    /*
12716     * This method handles package deletion in general
12717     */
12718    private boolean deletePackageLI(String packageName, UserHandle user,
12719            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12720            int flags, PackageRemovedInfo outInfo,
12721            boolean writeSettings) {
12722        if (packageName == null) {
12723            Slog.w(TAG, "Attempt to delete null packageName.");
12724            return false;
12725        }
12726        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12727        PackageSetting ps;
12728        boolean dataOnly = false;
12729        int removeUser = -1;
12730        int appId = -1;
12731        synchronized (mPackages) {
12732            ps = mSettings.mPackages.get(packageName);
12733            if (ps == null) {
12734                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12735                return false;
12736            }
12737            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12738                    && user.getIdentifier() != UserHandle.USER_ALL) {
12739                // The caller is asking that the package only be deleted for a single
12740                // user.  To do this, we just mark its uninstalled state and delete
12741                // its data.  If this is a system app, we only allow this to happen if
12742                // they have set the special DELETE_SYSTEM_APP which requests different
12743                // semantics than normal for uninstalling system apps.
12744                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12745                ps.setUserState(user.getIdentifier(),
12746                        COMPONENT_ENABLED_STATE_DEFAULT,
12747                        false, //installed
12748                        true,  //stopped
12749                        true,  //notLaunched
12750                        false, //hidden
12751                        null, null, null,
12752                        false, // blockUninstall
12753                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12754                if (!isSystemApp(ps)) {
12755                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12756                        // Other user still have this package installed, so all
12757                        // we need to do is clear this user's data and save that
12758                        // it is uninstalled.
12759                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12760                        removeUser = user.getIdentifier();
12761                        appId = ps.appId;
12762                        scheduleWritePackageRestrictionsLocked(removeUser);
12763                    } else {
12764                        // We need to set it back to 'installed' so the uninstall
12765                        // broadcasts will be sent correctly.
12766                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12767                        ps.setInstalled(true, user.getIdentifier());
12768                    }
12769                } else {
12770                    // This is a system app, so we assume that the
12771                    // other users still have this package installed, so all
12772                    // we need to do is clear this user's data and save that
12773                    // it is uninstalled.
12774                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12775                    removeUser = user.getIdentifier();
12776                    appId = ps.appId;
12777                    scheduleWritePackageRestrictionsLocked(removeUser);
12778                }
12779            }
12780        }
12781
12782        if (removeUser >= 0) {
12783            // From above, we determined that we are deleting this only
12784            // for a single user.  Continue the work here.
12785            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12786            if (outInfo != null) {
12787                outInfo.removedPackage = packageName;
12788                outInfo.removedAppId = appId;
12789                outInfo.removedUsers = new int[] {removeUser};
12790            }
12791            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12792            removeKeystoreDataIfNeeded(removeUser, appId);
12793            schedulePackageCleaning(packageName, removeUser, false);
12794            synchronized (mPackages) {
12795                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12796                    scheduleWritePackageRestrictionsLocked(removeUser);
12797                }
12798                revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(),
12799                        removeUser);
12800            }
12801            return true;
12802        }
12803
12804        if (dataOnly) {
12805            // Delete application data first
12806            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12807            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12808            return true;
12809        }
12810
12811        boolean ret = false;
12812        if (isSystemApp(ps)) {
12813            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12814            // When an updated system application is deleted we delete the existing resources as well and
12815            // fall back to existing code in system partition
12816            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12817                    flags, outInfo, writeSettings);
12818        } else {
12819            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12820            // Kill application pre-emptively especially for apps on sd.
12821            killApplication(packageName, ps.appId, "uninstall pkg");
12822            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12823                    allUserHandles, perUserInstalled,
12824                    outInfo, writeSettings);
12825        }
12826
12827        return ret;
12828    }
12829
12830    private final class ClearStorageConnection implements ServiceConnection {
12831        IMediaContainerService mContainerService;
12832
12833        @Override
12834        public void onServiceConnected(ComponentName name, IBinder service) {
12835            synchronized (this) {
12836                mContainerService = IMediaContainerService.Stub.asInterface(service);
12837                notifyAll();
12838            }
12839        }
12840
12841        @Override
12842        public void onServiceDisconnected(ComponentName name) {
12843        }
12844    }
12845
12846    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12847        final boolean mounted;
12848        if (Environment.isExternalStorageEmulated()) {
12849            mounted = true;
12850        } else {
12851            final String status = Environment.getExternalStorageState();
12852
12853            mounted = status.equals(Environment.MEDIA_MOUNTED)
12854                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12855        }
12856
12857        if (!mounted) {
12858            return;
12859        }
12860
12861        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12862        int[] users;
12863        if (userId == UserHandle.USER_ALL) {
12864            users = sUserManager.getUserIds();
12865        } else {
12866            users = new int[] { userId };
12867        }
12868        final ClearStorageConnection conn = new ClearStorageConnection();
12869        if (mContext.bindServiceAsUser(
12870                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12871            try {
12872                for (int curUser : users) {
12873                    long timeout = SystemClock.uptimeMillis() + 5000;
12874                    synchronized (conn) {
12875                        long now = SystemClock.uptimeMillis();
12876                        while (conn.mContainerService == null && now < timeout) {
12877                            try {
12878                                conn.wait(timeout - now);
12879                            } catch (InterruptedException e) {
12880                            }
12881                        }
12882                    }
12883                    if (conn.mContainerService == null) {
12884                        return;
12885                    }
12886
12887                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12888                    clearDirectory(conn.mContainerService,
12889                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12890                    if (allData) {
12891                        clearDirectory(conn.mContainerService,
12892                                userEnv.buildExternalStorageAppDataDirs(packageName));
12893                        clearDirectory(conn.mContainerService,
12894                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12895                    }
12896                }
12897            } finally {
12898                mContext.unbindService(conn);
12899            }
12900        }
12901    }
12902
12903    @Override
12904    public void clearApplicationUserData(final String packageName,
12905            final IPackageDataObserver observer, final int userId) {
12906        mContext.enforceCallingOrSelfPermission(
12907                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12908        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12909        // Queue up an async operation since the package deletion may take a little while.
12910        mHandler.post(new Runnable() {
12911            public void run() {
12912                mHandler.removeCallbacks(this);
12913                final boolean succeeded;
12914                synchronized (mInstallLock) {
12915                    succeeded = clearApplicationUserDataLI(packageName, userId);
12916                }
12917                clearExternalStorageDataSync(packageName, userId, true);
12918                if (succeeded) {
12919                    // invoke DeviceStorageMonitor's update method to clear any notifications
12920                    DeviceStorageMonitorInternal
12921                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12922                    if (dsm != null) {
12923                        dsm.checkMemory();
12924                    }
12925                }
12926                if(observer != null) {
12927                    try {
12928                        observer.onRemoveCompleted(packageName, succeeded);
12929                    } catch (RemoteException e) {
12930                        Log.i(TAG, "Observer no longer exists.");
12931                    }
12932                } //end if observer
12933            } //end run
12934        });
12935    }
12936
12937    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12938        if (packageName == null) {
12939            Slog.w(TAG, "Attempt to delete null packageName.");
12940            return false;
12941        }
12942
12943        // Try finding details about the requested package
12944        PackageParser.Package pkg;
12945        synchronized (mPackages) {
12946            pkg = mPackages.get(packageName);
12947            if (pkg == null) {
12948                final PackageSetting ps = mSettings.mPackages.get(packageName);
12949                if (ps != null) {
12950                    pkg = ps.pkg;
12951                }
12952            }
12953
12954            if (pkg == null) {
12955                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12956                return false;
12957            }
12958
12959            PackageSetting ps = (PackageSetting) pkg.mExtras;
12960            PermissionsState permissionsState = ps.getPermissionsState();
12961            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
12962        }
12963
12964        // Always delete data directories for package, even if we found no other
12965        // record of app. This helps users recover from UID mismatches without
12966        // resorting to a full data wipe.
12967        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12968        if (retCode < 0) {
12969            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12970            return false;
12971        }
12972
12973        final int appId = pkg.applicationInfo.uid;
12974        removeKeystoreDataIfNeeded(userId, appId);
12975
12976        // Create a native library symlink only if we have native libraries
12977        // and if the native libraries are 32 bit libraries. We do not provide
12978        // this symlink for 64 bit libraries.
12979        if (pkg.applicationInfo.primaryCpuAbi != null &&
12980                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12981            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12982            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12983                    nativeLibPath, userId) < 0) {
12984                Slog.w(TAG, "Failed linking native library dir");
12985                return false;
12986            }
12987        }
12988
12989        return true;
12990    }
12991
12992
12993    /**
12994     * Revokes granted runtime permissions and clears resettable flags
12995     * which are flags that can be set by a user interaction.
12996     *
12997     * @param permissionsState The permission state to reset.
12998     * @param userId The device user for which to do a reset.
12999     */
13000    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
13001            PermissionsState permissionsState, int userId) {
13002        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
13003                | PackageManager.FLAG_PERMISSION_USER_FIXED
13004                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13005
13006        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags);
13007    }
13008
13009    /**
13010     * Revokes granted runtime permissions and clears all flags.
13011     *
13012     * @param permissionsState The permission state to reset.
13013     * @param userId The device user for which to do a reset.
13014     */
13015    private void revokeRuntimePermissionsAndClearAllFlagsLocked(
13016            PermissionsState permissionsState, int userId) {
13017        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId,
13018                PackageManager.MASK_PERMISSION_FLAGS);
13019    }
13020
13021    /**
13022     * Revokes granted runtime permissions and clears certain flags.
13023     *
13024     * @param permissionsState The permission state to reset.
13025     * @param userId The device user for which to do a reset.
13026     * @param flags The flags that is going to be reset.
13027     */
13028    private void revokeRuntimePermissionsAndClearFlagsLocked(
13029            PermissionsState permissionsState, int userId, int flags) {
13030        boolean needsWrite = false;
13031
13032        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
13033            BasePermission bp = mSettings.mPermissions.get(state.getName());
13034            if (bp != null) {
13035                permissionsState.revokeRuntimePermission(bp, userId);
13036                permissionsState.updatePermissionFlags(bp, userId, flags, 0);
13037                needsWrite = true;
13038            }
13039        }
13040
13041        // Ensure default permissions are never cleared.
13042        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
13043
13044        if (needsWrite) {
13045            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13046        }
13047    }
13048
13049    /**
13050     * Remove entries from the keystore daemon. Will only remove it if the
13051     * {@code appId} is valid.
13052     */
13053    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13054        if (appId < 0) {
13055            return;
13056        }
13057
13058        final KeyStore keyStore = KeyStore.getInstance();
13059        if (keyStore != null) {
13060            if (userId == UserHandle.USER_ALL) {
13061                for (final int individual : sUserManager.getUserIds()) {
13062                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13063                }
13064            } else {
13065                keyStore.clearUid(UserHandle.getUid(userId, appId));
13066            }
13067        } else {
13068            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13069        }
13070    }
13071
13072    @Override
13073    public void deleteApplicationCacheFiles(final String packageName,
13074            final IPackageDataObserver observer) {
13075        mContext.enforceCallingOrSelfPermission(
13076                android.Manifest.permission.DELETE_CACHE_FILES, null);
13077        // Queue up an async operation since the package deletion may take a little while.
13078        final int userId = UserHandle.getCallingUserId();
13079        mHandler.post(new Runnable() {
13080            public void run() {
13081                mHandler.removeCallbacks(this);
13082                final boolean succeded;
13083                synchronized (mInstallLock) {
13084                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13085                }
13086                clearExternalStorageDataSync(packageName, userId, false);
13087                if (observer != null) {
13088                    try {
13089                        observer.onRemoveCompleted(packageName, succeded);
13090                    } catch (RemoteException e) {
13091                        Log.i(TAG, "Observer no longer exists.");
13092                    }
13093                } //end if observer
13094            } //end run
13095        });
13096    }
13097
13098    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13099        if (packageName == null) {
13100            Slog.w(TAG, "Attempt to delete null packageName.");
13101            return false;
13102        }
13103        PackageParser.Package p;
13104        synchronized (mPackages) {
13105            p = mPackages.get(packageName);
13106        }
13107        if (p == null) {
13108            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13109            return false;
13110        }
13111        final ApplicationInfo applicationInfo = p.applicationInfo;
13112        if (applicationInfo == null) {
13113            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13114            return false;
13115        }
13116        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13117        if (retCode < 0) {
13118            Slog.w(TAG, "Couldn't remove cache files for package: "
13119                       + packageName + " u" + userId);
13120            return false;
13121        }
13122        return true;
13123    }
13124
13125    @Override
13126    public void getPackageSizeInfo(final String packageName, int userHandle,
13127            final IPackageStatsObserver observer) {
13128        mContext.enforceCallingOrSelfPermission(
13129                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13130        if (packageName == null) {
13131            throw new IllegalArgumentException("Attempt to get size of null packageName");
13132        }
13133
13134        PackageStats stats = new PackageStats(packageName, userHandle);
13135
13136        /*
13137         * Queue up an async operation since the package measurement may take a
13138         * little while.
13139         */
13140        Message msg = mHandler.obtainMessage(INIT_COPY);
13141        msg.obj = new MeasureParams(stats, observer);
13142        mHandler.sendMessage(msg);
13143    }
13144
13145    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13146            PackageStats pStats) {
13147        if (packageName == null) {
13148            Slog.w(TAG, "Attempt to get size of null packageName.");
13149            return false;
13150        }
13151        PackageParser.Package p;
13152        boolean dataOnly = false;
13153        String libDirRoot = null;
13154        String asecPath = null;
13155        PackageSetting ps = null;
13156        synchronized (mPackages) {
13157            p = mPackages.get(packageName);
13158            ps = mSettings.mPackages.get(packageName);
13159            if(p == null) {
13160                dataOnly = true;
13161                if((ps == null) || (ps.pkg == null)) {
13162                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13163                    return false;
13164                }
13165                p = ps.pkg;
13166            }
13167            if (ps != null) {
13168                libDirRoot = ps.legacyNativeLibraryPathString;
13169            }
13170            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13171                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13172                if (secureContainerId != null) {
13173                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13174                }
13175            }
13176        }
13177        String publicSrcDir = null;
13178        if(!dataOnly) {
13179            final ApplicationInfo applicationInfo = p.applicationInfo;
13180            if (applicationInfo == null) {
13181                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13182                return false;
13183            }
13184            if (p.isForwardLocked()) {
13185                publicSrcDir = applicationInfo.getBaseResourcePath();
13186            }
13187        }
13188        // TODO: extend to measure size of split APKs
13189        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13190        // not just the first level.
13191        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13192        // just the primary.
13193        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13194        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13195                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13196        if (res < 0) {
13197            return false;
13198        }
13199
13200        // Fix-up for forward-locked applications in ASEC containers.
13201        if (!isExternal(p)) {
13202            pStats.codeSize += pStats.externalCodeSize;
13203            pStats.externalCodeSize = 0L;
13204        }
13205
13206        return true;
13207    }
13208
13209
13210    @Override
13211    public void addPackageToPreferred(String packageName) {
13212        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13213    }
13214
13215    @Override
13216    public void removePackageFromPreferred(String packageName) {
13217        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13218    }
13219
13220    @Override
13221    public List<PackageInfo> getPreferredPackages(int flags) {
13222        return new ArrayList<PackageInfo>();
13223    }
13224
13225    private int getUidTargetSdkVersionLockedLPr(int uid) {
13226        Object obj = mSettings.getUserIdLPr(uid);
13227        if (obj instanceof SharedUserSetting) {
13228            final SharedUserSetting sus = (SharedUserSetting) obj;
13229            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13230            final Iterator<PackageSetting> it = sus.packages.iterator();
13231            while (it.hasNext()) {
13232                final PackageSetting ps = it.next();
13233                if (ps.pkg != null) {
13234                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13235                    if (v < vers) vers = v;
13236                }
13237            }
13238            return vers;
13239        } else if (obj instanceof PackageSetting) {
13240            final PackageSetting ps = (PackageSetting) obj;
13241            if (ps.pkg != null) {
13242                return ps.pkg.applicationInfo.targetSdkVersion;
13243            }
13244        }
13245        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13246    }
13247
13248    @Override
13249    public void addPreferredActivity(IntentFilter filter, int match,
13250            ComponentName[] set, ComponentName activity, int userId) {
13251        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13252                "Adding preferred");
13253    }
13254
13255    private void addPreferredActivityInternal(IntentFilter filter, int match,
13256            ComponentName[] set, ComponentName activity, boolean always, int userId,
13257            String opname) {
13258        // writer
13259        int callingUid = Binder.getCallingUid();
13260        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13261        if (filter.countActions() == 0) {
13262            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13263            return;
13264        }
13265        synchronized (mPackages) {
13266            if (mContext.checkCallingOrSelfPermission(
13267                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13268                    != PackageManager.PERMISSION_GRANTED) {
13269                if (getUidTargetSdkVersionLockedLPr(callingUid)
13270                        < Build.VERSION_CODES.FROYO) {
13271                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13272                            + callingUid);
13273                    return;
13274                }
13275                mContext.enforceCallingOrSelfPermission(
13276                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13277            }
13278
13279            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13280            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13281                    + userId + ":");
13282            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13283            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13284            scheduleWritePackageRestrictionsLocked(userId);
13285        }
13286    }
13287
13288    @Override
13289    public void replacePreferredActivity(IntentFilter filter, int match,
13290            ComponentName[] set, ComponentName activity, int userId) {
13291        if (filter.countActions() != 1) {
13292            throw new IllegalArgumentException(
13293                    "replacePreferredActivity expects filter to have only 1 action.");
13294        }
13295        if (filter.countDataAuthorities() != 0
13296                || filter.countDataPaths() != 0
13297                || filter.countDataSchemes() > 1
13298                || filter.countDataTypes() != 0) {
13299            throw new IllegalArgumentException(
13300                    "replacePreferredActivity expects filter to have no data authorities, " +
13301                    "paths, or types; and at most one scheme.");
13302        }
13303
13304        final int callingUid = Binder.getCallingUid();
13305        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13306        synchronized (mPackages) {
13307            if (mContext.checkCallingOrSelfPermission(
13308                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13309                    != PackageManager.PERMISSION_GRANTED) {
13310                if (getUidTargetSdkVersionLockedLPr(callingUid)
13311                        < Build.VERSION_CODES.FROYO) {
13312                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13313                            + Binder.getCallingUid());
13314                    return;
13315                }
13316                mContext.enforceCallingOrSelfPermission(
13317                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13318            }
13319
13320            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13321            if (pir != null) {
13322                // Get all of the existing entries that exactly match this filter.
13323                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13324                if (existing != null && existing.size() == 1) {
13325                    PreferredActivity cur = existing.get(0);
13326                    if (DEBUG_PREFERRED) {
13327                        Slog.i(TAG, "Checking replace of preferred:");
13328                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13329                        if (!cur.mPref.mAlways) {
13330                            Slog.i(TAG, "  -- CUR; not mAlways!");
13331                        } else {
13332                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13333                            Slog.i(TAG, "  -- CUR: mSet="
13334                                    + Arrays.toString(cur.mPref.mSetComponents));
13335                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13336                            Slog.i(TAG, "  -- NEW: mMatch="
13337                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13338                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13339                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13340                        }
13341                    }
13342                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13343                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13344                            && cur.mPref.sameSet(set)) {
13345                        // Setting the preferred activity to what it happens to be already
13346                        if (DEBUG_PREFERRED) {
13347                            Slog.i(TAG, "Replacing with same preferred activity "
13348                                    + cur.mPref.mShortComponent + " for user "
13349                                    + userId + ":");
13350                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13351                        }
13352                        return;
13353                    }
13354                }
13355
13356                if (existing != null) {
13357                    if (DEBUG_PREFERRED) {
13358                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13359                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13360                    }
13361                    for (int i = 0; i < existing.size(); i++) {
13362                        PreferredActivity pa = existing.get(i);
13363                        if (DEBUG_PREFERRED) {
13364                            Slog.i(TAG, "Removing existing preferred activity "
13365                                    + pa.mPref.mComponent + ":");
13366                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13367                        }
13368                        pir.removeFilter(pa);
13369                    }
13370                }
13371            }
13372            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13373                    "Replacing preferred");
13374        }
13375    }
13376
13377    @Override
13378    public void clearPackagePreferredActivities(String packageName) {
13379        final int uid = Binder.getCallingUid();
13380        // writer
13381        synchronized (mPackages) {
13382            PackageParser.Package pkg = mPackages.get(packageName);
13383            if (pkg == null || pkg.applicationInfo.uid != uid) {
13384                if (mContext.checkCallingOrSelfPermission(
13385                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13386                        != PackageManager.PERMISSION_GRANTED) {
13387                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13388                            < Build.VERSION_CODES.FROYO) {
13389                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13390                                + Binder.getCallingUid());
13391                        return;
13392                    }
13393                    mContext.enforceCallingOrSelfPermission(
13394                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13395                }
13396            }
13397
13398            int user = UserHandle.getCallingUserId();
13399            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13400                scheduleWritePackageRestrictionsLocked(user);
13401            }
13402        }
13403    }
13404
13405    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13406    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13407        ArrayList<PreferredActivity> removed = null;
13408        boolean changed = false;
13409        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13410            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13411            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13412            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13413                continue;
13414            }
13415            Iterator<PreferredActivity> it = pir.filterIterator();
13416            while (it.hasNext()) {
13417                PreferredActivity pa = it.next();
13418                // Mark entry for removal only if it matches the package name
13419                // and the entry is of type "always".
13420                if (packageName == null ||
13421                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13422                                && pa.mPref.mAlways)) {
13423                    if (removed == null) {
13424                        removed = new ArrayList<PreferredActivity>();
13425                    }
13426                    removed.add(pa);
13427                }
13428            }
13429            if (removed != null) {
13430                for (int j=0; j<removed.size(); j++) {
13431                    PreferredActivity pa = removed.get(j);
13432                    pir.removeFilter(pa);
13433                }
13434                changed = true;
13435            }
13436        }
13437        return changed;
13438    }
13439
13440    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13441    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13442        if (userId == UserHandle.USER_ALL) {
13443            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13444                    sUserManager.getUserIds())) {
13445                for (int oneUserId : sUserManager.getUserIds()) {
13446                    scheduleWritePackageRestrictionsLocked(oneUserId);
13447                }
13448            }
13449        } else {
13450            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13451                scheduleWritePackageRestrictionsLocked(userId);
13452            }
13453        }
13454    }
13455
13456
13457    void clearDefaultBrowserIfNeeded(String packageName) {
13458        for (int oneUserId : sUserManager.getUserIds()) {
13459            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13460            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13461            if (packageName.equals(defaultBrowserPackageName)) {
13462                setDefaultBrowserPackageName(null, oneUserId);
13463            }
13464        }
13465    }
13466
13467    @Override
13468    public void resetPreferredActivities(int userId) {
13469        mContext.enforceCallingOrSelfPermission(
13470                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13471        // writer
13472        synchronized (mPackages) {
13473            clearPackagePreferredActivitiesLPw(null, userId);
13474            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13475            applyFactoryDefaultBrowserLPw(userId);
13476
13477            scheduleWritePackageRestrictionsLocked(userId);
13478        }
13479    }
13480
13481    @Override
13482    public int getPreferredActivities(List<IntentFilter> outFilters,
13483            List<ComponentName> outActivities, String packageName) {
13484
13485        int num = 0;
13486        final int userId = UserHandle.getCallingUserId();
13487        // reader
13488        synchronized (mPackages) {
13489            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13490            if (pir != null) {
13491                final Iterator<PreferredActivity> it = pir.filterIterator();
13492                while (it.hasNext()) {
13493                    final PreferredActivity pa = it.next();
13494                    if (packageName == null
13495                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13496                                    && pa.mPref.mAlways)) {
13497                        if (outFilters != null) {
13498                            outFilters.add(new IntentFilter(pa));
13499                        }
13500                        if (outActivities != null) {
13501                            outActivities.add(pa.mPref.mComponent);
13502                        }
13503                    }
13504                }
13505            }
13506        }
13507
13508        return num;
13509    }
13510
13511    @Override
13512    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13513            int userId) {
13514        int callingUid = Binder.getCallingUid();
13515        if (callingUid != Process.SYSTEM_UID) {
13516            throw new SecurityException(
13517                    "addPersistentPreferredActivity can only be run by the system");
13518        }
13519        if (filter.countActions() == 0) {
13520            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13521            return;
13522        }
13523        synchronized (mPackages) {
13524            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13525                    " :");
13526            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13527            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13528                    new PersistentPreferredActivity(filter, activity));
13529            scheduleWritePackageRestrictionsLocked(userId);
13530        }
13531    }
13532
13533    @Override
13534    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13535        int callingUid = Binder.getCallingUid();
13536        if (callingUid != Process.SYSTEM_UID) {
13537            throw new SecurityException(
13538                    "clearPackagePersistentPreferredActivities can only be run by the system");
13539        }
13540        ArrayList<PersistentPreferredActivity> removed = null;
13541        boolean changed = false;
13542        synchronized (mPackages) {
13543            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13544                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13545                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13546                        .valueAt(i);
13547                if (userId != thisUserId) {
13548                    continue;
13549                }
13550                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13551                while (it.hasNext()) {
13552                    PersistentPreferredActivity ppa = it.next();
13553                    // Mark entry for removal only if it matches the package name.
13554                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13555                        if (removed == null) {
13556                            removed = new ArrayList<PersistentPreferredActivity>();
13557                        }
13558                        removed.add(ppa);
13559                    }
13560                }
13561                if (removed != null) {
13562                    for (int j=0; j<removed.size(); j++) {
13563                        PersistentPreferredActivity ppa = removed.get(j);
13564                        ppir.removeFilter(ppa);
13565                    }
13566                    changed = true;
13567                }
13568            }
13569
13570            if (changed) {
13571                scheduleWritePackageRestrictionsLocked(userId);
13572            }
13573        }
13574    }
13575
13576    /**
13577     * Common machinery for picking apart a restored XML blob and passing
13578     * it to a caller-supplied functor to be applied to the running system.
13579     */
13580    private void restoreFromXml(XmlPullParser parser, int userId,
13581            String expectedStartTag, BlobXmlRestorer functor)
13582            throws IOException, XmlPullParserException {
13583        int type;
13584        while ((type = parser.next()) != XmlPullParser.START_TAG
13585                && type != XmlPullParser.END_DOCUMENT) {
13586        }
13587        if (type != XmlPullParser.START_TAG) {
13588            // oops didn't find a start tag?!
13589            if (DEBUG_BACKUP) {
13590                Slog.e(TAG, "Didn't find start tag during restore");
13591            }
13592            return;
13593        }
13594
13595        // this is supposed to be TAG_PREFERRED_BACKUP
13596        if (!expectedStartTag.equals(parser.getName())) {
13597            if (DEBUG_BACKUP) {
13598                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13599            }
13600            return;
13601        }
13602
13603        // skip interfering stuff, then we're aligned with the backing implementation
13604        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13605        functor.apply(parser, userId);
13606    }
13607
13608    private interface BlobXmlRestorer {
13609        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13610    }
13611
13612    /**
13613     * Non-Binder method, support for the backup/restore mechanism: write the
13614     * full set of preferred activities in its canonical XML format.  Returns the
13615     * XML output as a byte array, or null if there is none.
13616     */
13617    @Override
13618    public byte[] getPreferredActivityBackup(int userId) {
13619        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13620            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13621        }
13622
13623        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13624        try {
13625            final XmlSerializer serializer = new FastXmlSerializer();
13626            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13627            serializer.startDocument(null, true);
13628            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13629
13630            synchronized (mPackages) {
13631                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13632            }
13633
13634            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13635            serializer.endDocument();
13636            serializer.flush();
13637        } catch (Exception e) {
13638            if (DEBUG_BACKUP) {
13639                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13640            }
13641            return null;
13642        }
13643
13644        return dataStream.toByteArray();
13645    }
13646
13647    @Override
13648    public void restorePreferredActivities(byte[] backup, int userId) {
13649        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13650            throw new SecurityException("Only the system may call restorePreferredActivities()");
13651        }
13652
13653        try {
13654            final XmlPullParser parser = Xml.newPullParser();
13655            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13656            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13657                    new BlobXmlRestorer() {
13658                        @Override
13659                        public void apply(XmlPullParser parser, int userId)
13660                                throws XmlPullParserException, IOException {
13661                            synchronized (mPackages) {
13662                                mSettings.readPreferredActivitiesLPw(parser, userId);
13663                            }
13664                        }
13665                    } );
13666        } catch (Exception e) {
13667            if (DEBUG_BACKUP) {
13668                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13669            }
13670        }
13671    }
13672
13673    /**
13674     * Non-Binder method, support for the backup/restore mechanism: write the
13675     * default browser (etc) settings in its canonical XML format.  Returns the default
13676     * browser XML representation as a byte array, or null if there is none.
13677     */
13678    @Override
13679    public byte[] getDefaultAppsBackup(int userId) {
13680        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13681            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13682        }
13683
13684        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13685        try {
13686            final XmlSerializer serializer = new FastXmlSerializer();
13687            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13688            serializer.startDocument(null, true);
13689            serializer.startTag(null, TAG_DEFAULT_APPS);
13690
13691            synchronized (mPackages) {
13692                mSettings.writeDefaultAppsLPr(serializer, userId);
13693            }
13694
13695            serializer.endTag(null, TAG_DEFAULT_APPS);
13696            serializer.endDocument();
13697            serializer.flush();
13698        } catch (Exception e) {
13699            if (DEBUG_BACKUP) {
13700                Slog.e(TAG, "Unable to write default apps for backup", e);
13701            }
13702            return null;
13703        }
13704
13705        return dataStream.toByteArray();
13706    }
13707
13708    @Override
13709    public void restoreDefaultApps(byte[] backup, int userId) {
13710        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13711            throw new SecurityException("Only the system may call restoreDefaultApps()");
13712        }
13713
13714        try {
13715            final XmlPullParser parser = Xml.newPullParser();
13716            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13717            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13718                    new BlobXmlRestorer() {
13719                        @Override
13720                        public void apply(XmlPullParser parser, int userId)
13721                                throws XmlPullParserException, IOException {
13722                            synchronized (mPackages) {
13723                                mSettings.readDefaultAppsLPw(parser, userId);
13724                            }
13725                        }
13726                    } );
13727        } catch (Exception e) {
13728            if (DEBUG_BACKUP) {
13729                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13730            }
13731        }
13732    }
13733
13734    @Override
13735    public byte[] getIntentFilterVerificationBackup(int userId) {
13736        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13737            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
13738        }
13739
13740        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13741        try {
13742            final XmlSerializer serializer = new FastXmlSerializer();
13743            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13744            serializer.startDocument(null, true);
13745            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
13746
13747            synchronized (mPackages) {
13748                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
13749            }
13750
13751            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
13752            serializer.endDocument();
13753            serializer.flush();
13754        } catch (Exception e) {
13755            if (DEBUG_BACKUP) {
13756                Slog.e(TAG, "Unable to write default apps for backup", e);
13757            }
13758            return null;
13759        }
13760
13761        return dataStream.toByteArray();
13762    }
13763
13764    @Override
13765    public void restoreIntentFilterVerification(byte[] backup, int userId) {
13766        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13767            throw new SecurityException("Only the system may call restorePreferredActivities()");
13768        }
13769
13770        try {
13771            final XmlPullParser parser = Xml.newPullParser();
13772            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13773            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
13774                    new BlobXmlRestorer() {
13775                        @Override
13776                        public void apply(XmlPullParser parser, int userId)
13777                                throws XmlPullParserException, IOException {
13778                            synchronized (mPackages) {
13779                                mSettings.readAllDomainVerificationsLPr(parser, userId);
13780                                mSettings.writeLPr();
13781                            }
13782                        }
13783                    } );
13784        } catch (Exception e) {
13785            if (DEBUG_BACKUP) {
13786                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13787            }
13788        }
13789    }
13790
13791    @Override
13792    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13793            int sourceUserId, int targetUserId, int flags) {
13794        mContext.enforceCallingOrSelfPermission(
13795                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13796        int callingUid = Binder.getCallingUid();
13797        enforceOwnerRights(ownerPackage, callingUid);
13798        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13799        if (intentFilter.countActions() == 0) {
13800            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13801            return;
13802        }
13803        synchronized (mPackages) {
13804            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13805                    ownerPackage, targetUserId, flags);
13806            CrossProfileIntentResolver resolver =
13807                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13808            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13809            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13810            if (existing != null) {
13811                int size = existing.size();
13812                for (int i = 0; i < size; i++) {
13813                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13814                        return;
13815                    }
13816                }
13817            }
13818            resolver.addFilter(newFilter);
13819            scheduleWritePackageRestrictionsLocked(sourceUserId);
13820        }
13821    }
13822
13823    @Override
13824    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13825        mContext.enforceCallingOrSelfPermission(
13826                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13827        int callingUid = Binder.getCallingUid();
13828        enforceOwnerRights(ownerPackage, callingUid);
13829        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13830        synchronized (mPackages) {
13831            CrossProfileIntentResolver resolver =
13832                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13833            ArraySet<CrossProfileIntentFilter> set =
13834                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13835            for (CrossProfileIntentFilter filter : set) {
13836                if (filter.getOwnerPackage().equals(ownerPackage)) {
13837                    resolver.removeFilter(filter);
13838                }
13839            }
13840            scheduleWritePackageRestrictionsLocked(sourceUserId);
13841        }
13842    }
13843
13844    // Enforcing that callingUid is owning pkg on userId
13845    private void enforceOwnerRights(String pkg, int callingUid) {
13846        // The system owns everything.
13847        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13848            return;
13849        }
13850        int callingUserId = UserHandle.getUserId(callingUid);
13851        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13852        if (pi == null) {
13853            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13854                    + callingUserId);
13855        }
13856        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13857            throw new SecurityException("Calling uid " + callingUid
13858                    + " does not own package " + pkg);
13859        }
13860    }
13861
13862    @Override
13863    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13864        Intent intent = new Intent(Intent.ACTION_MAIN);
13865        intent.addCategory(Intent.CATEGORY_HOME);
13866
13867        final int callingUserId = UserHandle.getCallingUserId();
13868        List<ResolveInfo> list = queryIntentActivities(intent, null,
13869                PackageManager.GET_META_DATA, callingUserId);
13870        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13871                true, false, false, callingUserId);
13872
13873        allHomeCandidates.clear();
13874        if (list != null) {
13875            for (ResolveInfo ri : list) {
13876                allHomeCandidates.add(ri);
13877            }
13878        }
13879        return (preferred == null || preferred.activityInfo == null)
13880                ? null
13881                : new ComponentName(preferred.activityInfo.packageName,
13882                        preferred.activityInfo.name);
13883    }
13884
13885    @Override
13886    public void setApplicationEnabledSetting(String appPackageName,
13887            int newState, int flags, int userId, String callingPackage) {
13888        if (!sUserManager.exists(userId)) return;
13889        if (callingPackage == null) {
13890            callingPackage = Integer.toString(Binder.getCallingUid());
13891        }
13892        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13893    }
13894
13895    @Override
13896    public void setComponentEnabledSetting(ComponentName componentName,
13897            int newState, int flags, int userId) {
13898        if (!sUserManager.exists(userId)) return;
13899        setEnabledSetting(componentName.getPackageName(),
13900                componentName.getClassName(), newState, flags, userId, null);
13901    }
13902
13903    private void setEnabledSetting(final String packageName, String className, int newState,
13904            final int flags, int userId, String callingPackage) {
13905        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13906              || newState == COMPONENT_ENABLED_STATE_ENABLED
13907              || newState == COMPONENT_ENABLED_STATE_DISABLED
13908              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13909              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13910            throw new IllegalArgumentException("Invalid new component state: "
13911                    + newState);
13912        }
13913        PackageSetting pkgSetting;
13914        final int uid = Binder.getCallingUid();
13915        final int permission = mContext.checkCallingOrSelfPermission(
13916                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13917        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13918        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13919        boolean sendNow = false;
13920        boolean isApp = (className == null);
13921        String componentName = isApp ? packageName : className;
13922        int packageUid = -1;
13923        ArrayList<String> components;
13924
13925        // writer
13926        synchronized (mPackages) {
13927            pkgSetting = mSettings.mPackages.get(packageName);
13928            if (pkgSetting == null) {
13929                if (className == null) {
13930                    throw new IllegalArgumentException(
13931                            "Unknown package: " + packageName);
13932                }
13933                throw new IllegalArgumentException(
13934                        "Unknown component: " + packageName
13935                        + "/" + className);
13936            }
13937            // Allow root and verify that userId is not being specified by a different user
13938            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13939                throw new SecurityException(
13940                        "Permission Denial: attempt to change component state from pid="
13941                        + Binder.getCallingPid()
13942                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13943            }
13944            if (className == null) {
13945                // We're dealing with an application/package level state change
13946                if (pkgSetting.getEnabled(userId) == newState) {
13947                    // Nothing to do
13948                    return;
13949                }
13950                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13951                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13952                    // Don't care about who enables an app.
13953                    callingPackage = null;
13954                }
13955                pkgSetting.setEnabled(newState, userId, callingPackage);
13956                // pkgSetting.pkg.mSetEnabled = newState;
13957            } else {
13958                // We're dealing with a component level state change
13959                // First, verify that this is a valid class name.
13960                PackageParser.Package pkg = pkgSetting.pkg;
13961                if (pkg == null || !pkg.hasComponentClassName(className)) {
13962                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13963                        throw new IllegalArgumentException("Component class " + className
13964                                + " does not exist in " + packageName);
13965                    } else {
13966                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13967                                + className + " does not exist in " + packageName);
13968                    }
13969                }
13970                switch (newState) {
13971                case COMPONENT_ENABLED_STATE_ENABLED:
13972                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13973                        return;
13974                    }
13975                    break;
13976                case COMPONENT_ENABLED_STATE_DISABLED:
13977                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13978                        return;
13979                    }
13980                    break;
13981                case COMPONENT_ENABLED_STATE_DEFAULT:
13982                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13983                        return;
13984                    }
13985                    break;
13986                default:
13987                    Slog.e(TAG, "Invalid new component state: " + newState);
13988                    return;
13989                }
13990            }
13991            scheduleWritePackageRestrictionsLocked(userId);
13992            components = mPendingBroadcasts.get(userId, packageName);
13993            final boolean newPackage = components == null;
13994            if (newPackage) {
13995                components = new ArrayList<String>();
13996            }
13997            if (!components.contains(componentName)) {
13998                components.add(componentName);
13999            }
14000            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14001                sendNow = true;
14002                // Purge entry from pending broadcast list if another one exists already
14003                // since we are sending one right away.
14004                mPendingBroadcasts.remove(userId, packageName);
14005            } else {
14006                if (newPackage) {
14007                    mPendingBroadcasts.put(userId, packageName, components);
14008                }
14009                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14010                    // Schedule a message
14011                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14012                }
14013            }
14014        }
14015
14016        long callingId = Binder.clearCallingIdentity();
14017        try {
14018            if (sendNow) {
14019                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14020                sendPackageChangedBroadcast(packageName,
14021                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14022            }
14023        } finally {
14024            Binder.restoreCallingIdentity(callingId);
14025        }
14026    }
14027
14028    private void sendPackageChangedBroadcast(String packageName,
14029            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14030        if (DEBUG_INSTALL)
14031            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14032                    + componentNames);
14033        Bundle extras = new Bundle(4);
14034        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14035        String nameList[] = new String[componentNames.size()];
14036        componentNames.toArray(nameList);
14037        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14038        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14039        extras.putInt(Intent.EXTRA_UID, packageUid);
14040        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14041                new int[] {UserHandle.getUserId(packageUid)});
14042    }
14043
14044    @Override
14045    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14046        if (!sUserManager.exists(userId)) return;
14047        final int uid = Binder.getCallingUid();
14048        final int permission = mContext.checkCallingOrSelfPermission(
14049                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14050        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14051        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14052        // writer
14053        synchronized (mPackages) {
14054            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14055                    allowedByPermission, uid, userId)) {
14056                scheduleWritePackageRestrictionsLocked(userId);
14057            }
14058        }
14059    }
14060
14061    @Override
14062    public String getInstallerPackageName(String packageName) {
14063        // reader
14064        synchronized (mPackages) {
14065            return mSettings.getInstallerPackageNameLPr(packageName);
14066        }
14067    }
14068
14069    @Override
14070    public int getApplicationEnabledSetting(String packageName, int userId) {
14071        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14072        int uid = Binder.getCallingUid();
14073        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14074        // reader
14075        synchronized (mPackages) {
14076            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14077        }
14078    }
14079
14080    @Override
14081    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14082        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14083        int uid = Binder.getCallingUid();
14084        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14085        // reader
14086        synchronized (mPackages) {
14087            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14088        }
14089    }
14090
14091    @Override
14092    public void enterSafeMode() {
14093        enforceSystemOrRoot("Only the system can request entering safe mode");
14094
14095        if (!mSystemReady) {
14096            mSafeMode = true;
14097        }
14098    }
14099
14100    @Override
14101    public void systemReady() {
14102        mSystemReady = true;
14103
14104        // Read the compatibilty setting when the system is ready.
14105        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14106                mContext.getContentResolver(),
14107                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14108        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14109        if (DEBUG_SETTINGS) {
14110            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14111        }
14112
14113        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14114
14115        synchronized (mPackages) {
14116            // Verify that all of the preferred activity components actually
14117            // exist.  It is possible for applications to be updated and at
14118            // that point remove a previously declared activity component that
14119            // had been set as a preferred activity.  We try to clean this up
14120            // the next time we encounter that preferred activity, but it is
14121            // possible for the user flow to never be able to return to that
14122            // situation so here we do a sanity check to make sure we haven't
14123            // left any junk around.
14124            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14125            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14126                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14127                removed.clear();
14128                for (PreferredActivity pa : pir.filterSet()) {
14129                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14130                        removed.add(pa);
14131                    }
14132                }
14133                if (removed.size() > 0) {
14134                    for (int r=0; r<removed.size(); r++) {
14135                        PreferredActivity pa = removed.get(r);
14136                        Slog.w(TAG, "Removing dangling preferred activity: "
14137                                + pa.mPref.mComponent);
14138                        pir.removeFilter(pa);
14139                    }
14140                    mSettings.writePackageRestrictionsLPr(
14141                            mSettings.mPreferredActivities.keyAt(i));
14142                }
14143            }
14144
14145            for (int userId : UserManagerService.getInstance().getUserIds()) {
14146                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14147                    grantPermissionsUserIds = ArrayUtils.appendInt(
14148                            grantPermissionsUserIds, userId);
14149                }
14150            }
14151        }
14152        sUserManager.systemReady();
14153
14154        // If we upgraded grant all default permissions before kicking off.
14155        for (int userId : grantPermissionsUserIds) {
14156            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14157        }
14158
14159        // Kick off any messages waiting for system ready
14160        if (mPostSystemReadyMessages != null) {
14161            for (Message msg : mPostSystemReadyMessages) {
14162                msg.sendToTarget();
14163            }
14164            mPostSystemReadyMessages = null;
14165        }
14166
14167        // Watch for external volumes that come and go over time
14168        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14169        storage.registerListener(mStorageListener);
14170
14171        mInstallerService.systemReady();
14172        mPackageDexOptimizer.systemReady();
14173    }
14174
14175    @Override
14176    public boolean isSafeMode() {
14177        return mSafeMode;
14178    }
14179
14180    @Override
14181    public boolean hasSystemUidErrors() {
14182        return mHasSystemUidErrors;
14183    }
14184
14185    static String arrayToString(int[] array) {
14186        StringBuffer buf = new StringBuffer(128);
14187        buf.append('[');
14188        if (array != null) {
14189            for (int i=0; i<array.length; i++) {
14190                if (i > 0) buf.append(", ");
14191                buf.append(array[i]);
14192            }
14193        }
14194        buf.append(']');
14195        return buf.toString();
14196    }
14197
14198    static class DumpState {
14199        public static final int DUMP_LIBS = 1 << 0;
14200        public static final int DUMP_FEATURES = 1 << 1;
14201        public static final int DUMP_RESOLVERS = 1 << 2;
14202        public static final int DUMP_PERMISSIONS = 1 << 3;
14203        public static final int DUMP_PACKAGES = 1 << 4;
14204        public static final int DUMP_SHARED_USERS = 1 << 5;
14205        public static final int DUMP_MESSAGES = 1 << 6;
14206        public static final int DUMP_PROVIDERS = 1 << 7;
14207        public static final int DUMP_VERIFIERS = 1 << 8;
14208        public static final int DUMP_PREFERRED = 1 << 9;
14209        public static final int DUMP_PREFERRED_XML = 1 << 10;
14210        public static final int DUMP_KEYSETS = 1 << 11;
14211        public static final int DUMP_VERSION = 1 << 12;
14212        public static final int DUMP_INSTALLS = 1 << 13;
14213        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14214        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14215
14216        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14217
14218        private int mTypes;
14219
14220        private int mOptions;
14221
14222        private boolean mTitlePrinted;
14223
14224        private SharedUserSetting mSharedUser;
14225
14226        public boolean isDumping(int type) {
14227            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14228                return true;
14229            }
14230
14231            return (mTypes & type) != 0;
14232        }
14233
14234        public void setDump(int type) {
14235            mTypes |= type;
14236        }
14237
14238        public boolean isOptionEnabled(int option) {
14239            return (mOptions & option) != 0;
14240        }
14241
14242        public void setOptionEnabled(int option) {
14243            mOptions |= option;
14244        }
14245
14246        public boolean onTitlePrinted() {
14247            final boolean printed = mTitlePrinted;
14248            mTitlePrinted = true;
14249            return printed;
14250        }
14251
14252        public boolean getTitlePrinted() {
14253            return mTitlePrinted;
14254        }
14255
14256        public void setTitlePrinted(boolean enabled) {
14257            mTitlePrinted = enabled;
14258        }
14259
14260        public SharedUserSetting getSharedUser() {
14261            return mSharedUser;
14262        }
14263
14264        public void setSharedUser(SharedUserSetting user) {
14265            mSharedUser = user;
14266        }
14267    }
14268
14269    @Override
14270    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14271        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14272                != PackageManager.PERMISSION_GRANTED) {
14273            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14274                    + Binder.getCallingPid()
14275                    + ", uid=" + Binder.getCallingUid()
14276                    + " without permission "
14277                    + android.Manifest.permission.DUMP);
14278            return;
14279        }
14280
14281        DumpState dumpState = new DumpState();
14282        boolean fullPreferred = false;
14283        boolean checkin = false;
14284
14285        String packageName = null;
14286        ArraySet<String> permissionNames = null;
14287
14288        int opti = 0;
14289        while (opti < args.length) {
14290            String opt = args[opti];
14291            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14292                break;
14293            }
14294            opti++;
14295
14296            if ("-a".equals(opt)) {
14297                // Right now we only know how to print all.
14298            } else if ("-h".equals(opt)) {
14299                pw.println("Package manager dump options:");
14300                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14301                pw.println("    --checkin: dump for a checkin");
14302                pw.println("    -f: print details of intent filters");
14303                pw.println("    -h: print this help");
14304                pw.println("  cmd may be one of:");
14305                pw.println("    l[ibraries]: list known shared libraries");
14306                pw.println("    f[ibraries]: list device features");
14307                pw.println("    k[eysets]: print known keysets");
14308                pw.println("    r[esolvers]: dump intent resolvers");
14309                pw.println("    perm[issions]: dump permissions");
14310                pw.println("    permission [name ...]: dump declaration and use of given permission");
14311                pw.println("    pref[erred]: print preferred package settings");
14312                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14313                pw.println("    prov[iders]: dump content providers");
14314                pw.println("    p[ackages]: dump installed packages");
14315                pw.println("    s[hared-users]: dump shared user IDs");
14316                pw.println("    m[essages]: print collected runtime messages");
14317                pw.println("    v[erifiers]: print package verifier info");
14318                pw.println("    version: print database version info");
14319                pw.println("    write: write current settings now");
14320                pw.println("    <package.name>: info about given package");
14321                pw.println("    installs: details about install sessions");
14322                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14323                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14324                return;
14325            } else if ("--checkin".equals(opt)) {
14326                checkin = true;
14327            } else if ("-f".equals(opt)) {
14328                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14329            } else {
14330                pw.println("Unknown argument: " + opt + "; use -h for help");
14331            }
14332        }
14333
14334        // Is the caller requesting to dump a particular piece of data?
14335        if (opti < args.length) {
14336            String cmd = args[opti];
14337            opti++;
14338            // Is this a package name?
14339            if ("android".equals(cmd) || cmd.contains(".")) {
14340                packageName = cmd;
14341                // When dumping a single package, we always dump all of its
14342                // filter information since the amount of data will be reasonable.
14343                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14344            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14345                dumpState.setDump(DumpState.DUMP_LIBS);
14346            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14347                dumpState.setDump(DumpState.DUMP_FEATURES);
14348            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14349                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14350            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14351                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14352            } else if ("permission".equals(cmd)) {
14353                if (opti >= args.length) {
14354                    pw.println("Error: permission requires permission name");
14355                    return;
14356                }
14357                permissionNames = new ArraySet<>();
14358                while (opti < args.length) {
14359                    permissionNames.add(args[opti]);
14360                    opti++;
14361                }
14362                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14363                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14364            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14365                dumpState.setDump(DumpState.DUMP_PREFERRED);
14366            } else if ("preferred-xml".equals(cmd)) {
14367                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14368                if (opti < args.length && "--full".equals(args[opti])) {
14369                    fullPreferred = true;
14370                    opti++;
14371                }
14372            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14373                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14374            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14375                dumpState.setDump(DumpState.DUMP_PACKAGES);
14376            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14377                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14378            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14379                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14380            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14381                dumpState.setDump(DumpState.DUMP_MESSAGES);
14382            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14383                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14384            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14385                    || "intent-filter-verifiers".equals(cmd)) {
14386                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14387            } else if ("version".equals(cmd)) {
14388                dumpState.setDump(DumpState.DUMP_VERSION);
14389            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14390                dumpState.setDump(DumpState.DUMP_KEYSETS);
14391            } else if ("installs".equals(cmd)) {
14392                dumpState.setDump(DumpState.DUMP_INSTALLS);
14393            } else if ("write".equals(cmd)) {
14394                synchronized (mPackages) {
14395                    mSettings.writeLPr();
14396                    pw.println("Settings written.");
14397                    return;
14398                }
14399            }
14400        }
14401
14402        if (checkin) {
14403            pw.println("vers,1");
14404        }
14405
14406        // reader
14407        synchronized (mPackages) {
14408            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14409                if (!checkin) {
14410                    if (dumpState.onTitlePrinted())
14411                        pw.println();
14412                    pw.println("Database versions:");
14413                    pw.print("  SDK Version:");
14414                    pw.print(" internal=");
14415                    pw.print(mSettings.mInternalSdkPlatform);
14416                    pw.print(" external=");
14417                    pw.println(mSettings.mExternalSdkPlatform);
14418                    pw.print("  DB Version:");
14419                    pw.print(" internal=");
14420                    pw.print(mSettings.mInternalDatabaseVersion);
14421                    pw.print(" external=");
14422                    pw.println(mSettings.mExternalDatabaseVersion);
14423                }
14424            }
14425
14426            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14427                if (!checkin) {
14428                    if (dumpState.onTitlePrinted())
14429                        pw.println();
14430                    pw.println("Verifiers:");
14431                    pw.print("  Required: ");
14432                    pw.print(mRequiredVerifierPackage);
14433                    pw.print(" (uid=");
14434                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14435                    pw.println(")");
14436                } else if (mRequiredVerifierPackage != null) {
14437                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14438                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14439                }
14440            }
14441
14442            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14443                    packageName == null) {
14444                if (mIntentFilterVerifierComponent != null) {
14445                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14446                    if (!checkin) {
14447                        if (dumpState.onTitlePrinted())
14448                            pw.println();
14449                        pw.println("Intent Filter Verifier:");
14450                        pw.print("  Using: ");
14451                        pw.print(verifierPackageName);
14452                        pw.print(" (uid=");
14453                        pw.print(getPackageUid(verifierPackageName, 0));
14454                        pw.println(")");
14455                    } else if (verifierPackageName != null) {
14456                        pw.print("ifv,"); pw.print(verifierPackageName);
14457                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14458                    }
14459                } else {
14460                    pw.println();
14461                    pw.println("No Intent Filter Verifier available!");
14462                }
14463            }
14464
14465            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14466                boolean printedHeader = false;
14467                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14468                while (it.hasNext()) {
14469                    String name = it.next();
14470                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14471                    if (!checkin) {
14472                        if (!printedHeader) {
14473                            if (dumpState.onTitlePrinted())
14474                                pw.println();
14475                            pw.println("Libraries:");
14476                            printedHeader = true;
14477                        }
14478                        pw.print("  ");
14479                    } else {
14480                        pw.print("lib,");
14481                    }
14482                    pw.print(name);
14483                    if (!checkin) {
14484                        pw.print(" -> ");
14485                    }
14486                    if (ent.path != null) {
14487                        if (!checkin) {
14488                            pw.print("(jar) ");
14489                            pw.print(ent.path);
14490                        } else {
14491                            pw.print(",jar,");
14492                            pw.print(ent.path);
14493                        }
14494                    } else {
14495                        if (!checkin) {
14496                            pw.print("(apk) ");
14497                            pw.print(ent.apk);
14498                        } else {
14499                            pw.print(",apk,");
14500                            pw.print(ent.apk);
14501                        }
14502                    }
14503                    pw.println();
14504                }
14505            }
14506
14507            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14508                if (dumpState.onTitlePrinted())
14509                    pw.println();
14510                if (!checkin) {
14511                    pw.println("Features:");
14512                }
14513                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14514                while (it.hasNext()) {
14515                    String name = it.next();
14516                    if (!checkin) {
14517                        pw.print("  ");
14518                    } else {
14519                        pw.print("feat,");
14520                    }
14521                    pw.println(name);
14522                }
14523            }
14524
14525            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14526                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14527                        : "Activity Resolver Table:", "  ", packageName,
14528                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14529                    dumpState.setTitlePrinted(true);
14530                }
14531                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14532                        : "Receiver Resolver Table:", "  ", packageName,
14533                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14534                    dumpState.setTitlePrinted(true);
14535                }
14536                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14537                        : "Service Resolver Table:", "  ", packageName,
14538                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14539                    dumpState.setTitlePrinted(true);
14540                }
14541                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14542                        : "Provider Resolver Table:", "  ", packageName,
14543                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14544                    dumpState.setTitlePrinted(true);
14545                }
14546            }
14547
14548            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14549                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14550                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14551                    int user = mSettings.mPreferredActivities.keyAt(i);
14552                    if (pir.dump(pw,
14553                            dumpState.getTitlePrinted()
14554                                ? "\nPreferred Activities User " + user + ":"
14555                                : "Preferred Activities User " + user + ":", "  ",
14556                            packageName, true, false)) {
14557                        dumpState.setTitlePrinted(true);
14558                    }
14559                }
14560            }
14561
14562            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14563                pw.flush();
14564                FileOutputStream fout = new FileOutputStream(fd);
14565                BufferedOutputStream str = new BufferedOutputStream(fout);
14566                XmlSerializer serializer = new FastXmlSerializer();
14567                try {
14568                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14569                    serializer.startDocument(null, true);
14570                    serializer.setFeature(
14571                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14572                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14573                    serializer.endDocument();
14574                    serializer.flush();
14575                } catch (IllegalArgumentException e) {
14576                    pw.println("Failed writing: " + e);
14577                } catch (IllegalStateException e) {
14578                    pw.println("Failed writing: " + e);
14579                } catch (IOException e) {
14580                    pw.println("Failed writing: " + e);
14581                }
14582            }
14583
14584            if (!checkin
14585                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14586                    && packageName == null) {
14587                pw.println();
14588                int count = mSettings.mPackages.size();
14589                if (count == 0) {
14590                    pw.println("No domain preferred apps!");
14591                    pw.println();
14592                } else {
14593                    final String prefix = "  ";
14594                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14595                    if (allPackageSettings.size() == 0) {
14596                        pw.println("No domain preferred apps!");
14597                        pw.println();
14598                    } else {
14599                        pw.println("Domain preferred apps status:");
14600                        pw.println();
14601                        count = 0;
14602                        for (PackageSetting ps : allPackageSettings) {
14603                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14604                            if (ivi == null || ivi.getPackageName() == null) continue;
14605                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14606                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14607                            pw.println(prefix + "Status: " + ivi.getStatusString());
14608                            pw.println();
14609                            count++;
14610                        }
14611                        if (count == 0) {
14612                            pw.println(prefix + "No domain preferred app status!");
14613                            pw.println();
14614                        }
14615                        for (int userId : sUserManager.getUserIds()) {
14616                            pw.println("Domain preferred apps for User " + userId + ":");
14617                            pw.println();
14618                            count = 0;
14619                            for (PackageSetting ps : allPackageSettings) {
14620                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14621                                if (ivi == null || ivi.getPackageName() == null) {
14622                                    continue;
14623                                }
14624                                final int status = ps.getDomainVerificationStatusForUser(userId);
14625                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14626                                    continue;
14627                                }
14628                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14629                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14630                                String statusStr = IntentFilterVerificationInfo.
14631                                        getStatusStringFromValue(status);
14632                                pw.println(prefix + "Status: " + statusStr);
14633                                pw.println();
14634                                count++;
14635                            }
14636                            if (count == 0) {
14637                                pw.println(prefix + "No domain preferred apps!");
14638                                pw.println();
14639                            }
14640                        }
14641                    }
14642                }
14643            }
14644
14645            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14646                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14647                if (packageName == null && permissionNames == null) {
14648                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14649                        if (iperm == 0) {
14650                            if (dumpState.onTitlePrinted())
14651                                pw.println();
14652                            pw.println("AppOp Permissions:");
14653                        }
14654                        pw.print("  AppOp Permission ");
14655                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14656                        pw.println(":");
14657                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14658                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14659                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14660                        }
14661                    }
14662                }
14663            }
14664
14665            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14666                boolean printedSomething = false;
14667                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14668                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14669                        continue;
14670                    }
14671                    if (!printedSomething) {
14672                        if (dumpState.onTitlePrinted())
14673                            pw.println();
14674                        pw.println("Registered ContentProviders:");
14675                        printedSomething = true;
14676                    }
14677                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14678                    pw.print("    "); pw.println(p.toString());
14679                }
14680                printedSomething = false;
14681                for (Map.Entry<String, PackageParser.Provider> entry :
14682                        mProvidersByAuthority.entrySet()) {
14683                    PackageParser.Provider p = entry.getValue();
14684                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14685                        continue;
14686                    }
14687                    if (!printedSomething) {
14688                        if (dumpState.onTitlePrinted())
14689                            pw.println();
14690                        pw.println("ContentProvider Authorities:");
14691                        printedSomething = true;
14692                    }
14693                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14694                    pw.print("    "); pw.println(p.toString());
14695                    if (p.info != null && p.info.applicationInfo != null) {
14696                        final String appInfo = p.info.applicationInfo.toString();
14697                        pw.print("      applicationInfo="); pw.println(appInfo);
14698                    }
14699                }
14700            }
14701
14702            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14703                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14704            }
14705
14706            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14707                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
14708            }
14709
14710            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14711                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
14712            }
14713
14714            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14715                // XXX should handle packageName != null by dumping only install data that
14716                // the given package is involved with.
14717                if (dumpState.onTitlePrinted()) pw.println();
14718                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14719            }
14720
14721            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14722                if (dumpState.onTitlePrinted()) pw.println();
14723                mSettings.dumpReadMessagesLPr(pw, dumpState);
14724
14725                pw.println();
14726                pw.println("Package warning messages:");
14727                BufferedReader in = null;
14728                String line = null;
14729                try {
14730                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14731                    while ((line = in.readLine()) != null) {
14732                        if (line.contains("ignored: updated version")) continue;
14733                        pw.println(line);
14734                    }
14735                } catch (IOException ignored) {
14736                } finally {
14737                    IoUtils.closeQuietly(in);
14738                }
14739            }
14740
14741            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14742                BufferedReader in = null;
14743                String line = null;
14744                try {
14745                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14746                    while ((line = in.readLine()) != null) {
14747                        if (line.contains("ignored: updated version")) continue;
14748                        pw.print("msg,");
14749                        pw.println(line);
14750                    }
14751                } catch (IOException ignored) {
14752                } finally {
14753                    IoUtils.closeQuietly(in);
14754                }
14755            }
14756        }
14757    }
14758
14759    // ------- apps on sdcard specific code -------
14760    static final boolean DEBUG_SD_INSTALL = false;
14761
14762    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14763
14764    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14765
14766    private boolean mMediaMounted = false;
14767
14768    static String getEncryptKey() {
14769        try {
14770            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14771                    SD_ENCRYPTION_KEYSTORE_NAME);
14772            if (sdEncKey == null) {
14773                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14774                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14775                if (sdEncKey == null) {
14776                    Slog.e(TAG, "Failed to create encryption keys");
14777                    return null;
14778                }
14779            }
14780            return sdEncKey;
14781        } catch (NoSuchAlgorithmException nsae) {
14782            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14783            return null;
14784        } catch (IOException ioe) {
14785            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14786            return null;
14787        }
14788    }
14789
14790    /*
14791     * Update media status on PackageManager.
14792     */
14793    @Override
14794    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14795        int callingUid = Binder.getCallingUid();
14796        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14797            throw new SecurityException("Media status can only be updated by the system");
14798        }
14799        // reader; this apparently protects mMediaMounted, but should probably
14800        // be a different lock in that case.
14801        synchronized (mPackages) {
14802            Log.i(TAG, "Updating external media status from "
14803                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14804                    + (mediaStatus ? "mounted" : "unmounted"));
14805            if (DEBUG_SD_INSTALL)
14806                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14807                        + ", mMediaMounted=" + mMediaMounted);
14808            if (mediaStatus == mMediaMounted) {
14809                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14810                        : 0, -1);
14811                mHandler.sendMessage(msg);
14812                return;
14813            }
14814            mMediaMounted = mediaStatus;
14815        }
14816        // Queue up an async operation since the package installation may take a
14817        // little while.
14818        mHandler.post(new Runnable() {
14819            public void run() {
14820                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14821            }
14822        });
14823    }
14824
14825    /**
14826     * Called by MountService when the initial ASECs to scan are available.
14827     * Should block until all the ASEC containers are finished being scanned.
14828     */
14829    public void scanAvailableAsecs() {
14830        updateExternalMediaStatusInner(true, false, false);
14831        if (mShouldRestoreconData) {
14832            SELinuxMMAC.setRestoreconDone();
14833            mShouldRestoreconData = false;
14834        }
14835    }
14836
14837    /*
14838     * Collect information of applications on external media, map them against
14839     * existing containers and update information based on current mount status.
14840     * Please note that we always have to report status if reportStatus has been
14841     * set to true especially when unloading packages.
14842     */
14843    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14844            boolean externalStorage) {
14845        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14846        int[] uidArr = EmptyArray.INT;
14847
14848        final String[] list = PackageHelper.getSecureContainerList();
14849        if (ArrayUtils.isEmpty(list)) {
14850            Log.i(TAG, "No secure containers found");
14851        } else {
14852            // Process list of secure containers and categorize them
14853            // as active or stale based on their package internal state.
14854
14855            // reader
14856            synchronized (mPackages) {
14857                for (String cid : list) {
14858                    // Leave stages untouched for now; installer service owns them
14859                    if (PackageInstallerService.isStageName(cid)) continue;
14860
14861                    if (DEBUG_SD_INSTALL)
14862                        Log.i(TAG, "Processing container " + cid);
14863                    String pkgName = getAsecPackageName(cid);
14864                    if (pkgName == null) {
14865                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14866                        continue;
14867                    }
14868                    if (DEBUG_SD_INSTALL)
14869                        Log.i(TAG, "Looking for pkg : " + pkgName);
14870
14871                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14872                    if (ps == null) {
14873                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14874                        continue;
14875                    }
14876
14877                    /*
14878                     * Skip packages that are not external if we're unmounting
14879                     * external storage.
14880                     */
14881                    if (externalStorage && !isMounted && !isExternal(ps)) {
14882                        continue;
14883                    }
14884
14885                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14886                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14887                    // The package status is changed only if the code path
14888                    // matches between settings and the container id.
14889                    if (ps.codePathString != null
14890                            && ps.codePathString.startsWith(args.getCodePath())) {
14891                        if (DEBUG_SD_INSTALL) {
14892                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14893                                    + " at code path: " + ps.codePathString);
14894                        }
14895
14896                        // We do have a valid package installed on sdcard
14897                        processCids.put(args, ps.codePathString);
14898                        final int uid = ps.appId;
14899                        if (uid != -1) {
14900                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14901                        }
14902                    } else {
14903                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14904                                + ps.codePathString);
14905                    }
14906                }
14907            }
14908
14909            Arrays.sort(uidArr);
14910        }
14911
14912        // Process packages with valid entries.
14913        if (isMounted) {
14914            if (DEBUG_SD_INSTALL)
14915                Log.i(TAG, "Loading packages");
14916            loadMediaPackages(processCids, uidArr);
14917            startCleaningPackages();
14918            mInstallerService.onSecureContainersAvailable();
14919        } else {
14920            if (DEBUG_SD_INSTALL)
14921                Log.i(TAG, "Unloading packages");
14922            unloadMediaPackages(processCids, uidArr, reportStatus);
14923        }
14924    }
14925
14926    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14927            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14928        final int size = infos.size();
14929        final String[] packageNames = new String[size];
14930        final int[] packageUids = new int[size];
14931        for (int i = 0; i < size; i++) {
14932            final ApplicationInfo info = infos.get(i);
14933            packageNames[i] = info.packageName;
14934            packageUids[i] = info.uid;
14935        }
14936        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14937                finishedReceiver);
14938    }
14939
14940    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14941            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14942        sendResourcesChangedBroadcast(mediaStatus, replacing,
14943                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14944    }
14945
14946    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14947            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14948        int size = pkgList.length;
14949        if (size > 0) {
14950            // Send broadcasts here
14951            Bundle extras = new Bundle();
14952            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14953            if (uidArr != null) {
14954                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14955            }
14956            if (replacing) {
14957                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14958            }
14959            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14960                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14961            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14962        }
14963    }
14964
14965   /*
14966     * Look at potentially valid container ids from processCids If package
14967     * information doesn't match the one on record or package scanning fails,
14968     * the cid is added to list of removeCids. We currently don't delete stale
14969     * containers.
14970     */
14971    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14972        ArrayList<String> pkgList = new ArrayList<String>();
14973        Set<AsecInstallArgs> keys = processCids.keySet();
14974
14975        for (AsecInstallArgs args : keys) {
14976            String codePath = processCids.get(args);
14977            if (DEBUG_SD_INSTALL)
14978                Log.i(TAG, "Loading container : " + args.cid);
14979            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14980            try {
14981                // Make sure there are no container errors first.
14982                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14983                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14984                            + " when installing from sdcard");
14985                    continue;
14986                }
14987                // Check code path here.
14988                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14989                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14990                            + " does not match one in settings " + codePath);
14991                    continue;
14992                }
14993                // Parse package
14994                int parseFlags = mDefParseFlags;
14995                if (args.isExternalAsec()) {
14996                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
14997                }
14998                if (args.isFwdLocked()) {
14999                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15000                }
15001
15002                synchronized (mInstallLock) {
15003                    PackageParser.Package pkg = null;
15004                    try {
15005                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15006                    } catch (PackageManagerException e) {
15007                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15008                    }
15009                    // Scan the package
15010                    if (pkg != null) {
15011                        /*
15012                         * TODO why is the lock being held? doPostInstall is
15013                         * called in other places without the lock. This needs
15014                         * to be straightened out.
15015                         */
15016                        // writer
15017                        synchronized (mPackages) {
15018                            retCode = PackageManager.INSTALL_SUCCEEDED;
15019                            pkgList.add(pkg.packageName);
15020                            // Post process args
15021                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15022                                    pkg.applicationInfo.uid);
15023                        }
15024                    } else {
15025                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15026                    }
15027                }
15028
15029            } finally {
15030                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15031                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15032                }
15033            }
15034        }
15035        // writer
15036        synchronized (mPackages) {
15037            // If the platform SDK has changed since the last time we booted,
15038            // we need to re-grant app permission to catch any new ones that
15039            // appear. This is really a hack, and means that apps can in some
15040            // cases get permissions that the user didn't initially explicitly
15041            // allow... it would be nice to have some better way to handle
15042            // this situation.
15043            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15044            if (regrantPermissions)
15045                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15046                        + mSdkVersion + "; regranting permissions for external storage");
15047            mSettings.mExternalSdkPlatform = mSdkVersion;
15048
15049            // Make sure group IDs have been assigned, and any permission
15050            // changes in other apps are accounted for
15051            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15052                    | (regrantPermissions
15053                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15054                            : 0));
15055
15056            mSettings.updateExternalDatabaseVersion();
15057
15058            // can downgrade to reader
15059            // Persist settings
15060            mSettings.writeLPr();
15061        }
15062        // Send a broadcast to let everyone know we are done processing
15063        if (pkgList.size() > 0) {
15064            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15065        }
15066    }
15067
15068   /*
15069     * Utility method to unload a list of specified containers
15070     */
15071    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15072        // Just unmount all valid containers.
15073        for (AsecInstallArgs arg : cidArgs) {
15074            synchronized (mInstallLock) {
15075                arg.doPostDeleteLI(false);
15076           }
15077       }
15078   }
15079
15080    /*
15081     * Unload packages mounted on external media. This involves deleting package
15082     * data from internal structures, sending broadcasts about diabled packages,
15083     * gc'ing to free up references, unmounting all secure containers
15084     * corresponding to packages on external media, and posting a
15085     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15086     * that we always have to post this message if status has been requested no
15087     * matter what.
15088     */
15089    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15090            final boolean reportStatus) {
15091        if (DEBUG_SD_INSTALL)
15092            Log.i(TAG, "unloading media packages");
15093        ArrayList<String> pkgList = new ArrayList<String>();
15094        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15095        final Set<AsecInstallArgs> keys = processCids.keySet();
15096        for (AsecInstallArgs args : keys) {
15097            String pkgName = args.getPackageName();
15098            if (DEBUG_SD_INSTALL)
15099                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15100            // Delete package internally
15101            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15102            synchronized (mInstallLock) {
15103                boolean res = deletePackageLI(pkgName, null, false, null, null,
15104                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15105                if (res) {
15106                    pkgList.add(pkgName);
15107                } else {
15108                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15109                    failedList.add(args);
15110                }
15111            }
15112        }
15113
15114        // reader
15115        synchronized (mPackages) {
15116            // We didn't update the settings after removing each package;
15117            // write them now for all packages.
15118            mSettings.writeLPr();
15119        }
15120
15121        // We have to absolutely send UPDATED_MEDIA_STATUS only
15122        // after confirming that all the receivers processed the ordered
15123        // broadcast when packages get disabled, force a gc to clean things up.
15124        // and unload all the containers.
15125        if (pkgList.size() > 0) {
15126            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15127                    new IIntentReceiver.Stub() {
15128                public void performReceive(Intent intent, int resultCode, String data,
15129                        Bundle extras, boolean ordered, boolean sticky,
15130                        int sendingUser) throws RemoteException {
15131                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15132                            reportStatus ? 1 : 0, 1, keys);
15133                    mHandler.sendMessage(msg);
15134                }
15135            });
15136        } else {
15137            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15138                    keys);
15139            mHandler.sendMessage(msg);
15140        }
15141    }
15142
15143    private void loadPrivatePackages(VolumeInfo vol) {
15144        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15145        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15146        synchronized (mInstallLock) {
15147        synchronized (mPackages) {
15148            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15149            for (PackageSetting ps : packages) {
15150                final PackageParser.Package pkg;
15151                try {
15152                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15153                    loaded.add(pkg.applicationInfo);
15154                } catch (PackageManagerException e) {
15155                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15156                }
15157            }
15158
15159            // TODO: regrant any permissions that changed based since original install
15160
15161            mSettings.writeLPr();
15162        }
15163        }
15164
15165        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15166        sendResourcesChangedBroadcast(true, false, loaded, null);
15167    }
15168
15169    private void unloadPrivatePackages(VolumeInfo vol) {
15170        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15171        synchronized (mInstallLock) {
15172        synchronized (mPackages) {
15173            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15174            for (PackageSetting ps : packages) {
15175                if (ps.pkg == null) continue;
15176
15177                final ApplicationInfo info = ps.pkg.applicationInfo;
15178                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15179                if (deletePackageLI(ps.name, null, false, null, null,
15180                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15181                    unloaded.add(info);
15182                } else {
15183                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15184                }
15185            }
15186
15187            mSettings.writeLPr();
15188        }
15189        }
15190
15191        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15192        sendResourcesChangedBroadcast(false, false, unloaded, null);
15193    }
15194
15195    private void unfreezePackage(String packageName) {
15196        synchronized (mPackages) {
15197            final PackageSetting ps = mSettings.mPackages.get(packageName);
15198            if (ps != null) {
15199                ps.frozen = false;
15200            }
15201        }
15202    }
15203
15204    @Override
15205    public int movePackage(final String packageName, final String volumeUuid) {
15206        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15207
15208        final int moveId = mNextMoveId.getAndIncrement();
15209        try {
15210            movePackageInternal(packageName, volumeUuid, moveId);
15211        } catch (PackageManagerException e) {
15212            Slog.w(TAG, "Failed to move " + packageName, e);
15213            mMoveCallbacks.notifyStatusChanged(moveId,
15214                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15215        }
15216        return moveId;
15217    }
15218
15219    private void movePackageInternal(final String packageName, final String volumeUuid,
15220            final int moveId) throws PackageManagerException {
15221        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15222        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15223        final PackageManager pm = mContext.getPackageManager();
15224
15225        final boolean currentAsec;
15226        final String currentVolumeUuid;
15227        final File codeFile;
15228        final String installerPackageName;
15229        final String packageAbiOverride;
15230        final int appId;
15231        final String seinfo;
15232        final String label;
15233
15234        // reader
15235        synchronized (mPackages) {
15236            final PackageParser.Package pkg = mPackages.get(packageName);
15237            final PackageSetting ps = mSettings.mPackages.get(packageName);
15238            if (pkg == null || ps == null) {
15239                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15240            }
15241
15242            if (pkg.applicationInfo.isSystemApp()) {
15243                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15244                        "Cannot move system application");
15245            }
15246
15247            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15248                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15249                        "Package already moved to " + volumeUuid);
15250            }
15251
15252            final File probe = new File(pkg.codePath);
15253            final File probeOat = new File(probe, "oat");
15254            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15255                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15256                        "Move only supported for modern cluster style installs");
15257            }
15258
15259            if (ps.frozen) {
15260                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15261                        "Failed to move already frozen package");
15262            }
15263            ps.frozen = true;
15264
15265            currentAsec = pkg.applicationInfo.isForwardLocked()
15266                    || pkg.applicationInfo.isExternalAsec();
15267            currentVolumeUuid = ps.volumeUuid;
15268            codeFile = new File(pkg.codePath);
15269            installerPackageName = ps.installerPackageName;
15270            packageAbiOverride = ps.cpuAbiOverrideString;
15271            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15272            seinfo = pkg.applicationInfo.seinfo;
15273            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15274        }
15275
15276        // Now that we're guarded by frozen state, kill app during move
15277        killApplication(packageName, appId, "move pkg");
15278
15279        final Bundle extras = new Bundle();
15280        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15281        extras.putString(Intent.EXTRA_TITLE, label);
15282        mMoveCallbacks.notifyCreated(moveId, extras);
15283
15284        int installFlags;
15285        final boolean moveCompleteApp;
15286        final File measurePath;
15287
15288        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15289            installFlags = INSTALL_INTERNAL;
15290            moveCompleteApp = !currentAsec;
15291            measurePath = Environment.getDataAppDirectory(volumeUuid);
15292        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15293            installFlags = INSTALL_EXTERNAL;
15294            moveCompleteApp = false;
15295            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15296        } else {
15297            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15298            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15299                    || !volume.isMountedWritable()) {
15300                unfreezePackage(packageName);
15301                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15302                        "Move location not mounted private volume");
15303            }
15304
15305            Preconditions.checkState(!currentAsec);
15306
15307            installFlags = INSTALL_INTERNAL;
15308            moveCompleteApp = true;
15309            measurePath = Environment.getDataAppDirectory(volumeUuid);
15310        }
15311
15312        final PackageStats stats = new PackageStats(null, -1);
15313        synchronized (mInstaller) {
15314            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15315                unfreezePackage(packageName);
15316                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15317                        "Failed to measure package size");
15318            }
15319        }
15320
15321        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15322                + stats.dataSize);
15323
15324        final long startFreeBytes = measurePath.getFreeSpace();
15325        final long sizeBytes;
15326        if (moveCompleteApp) {
15327            sizeBytes = stats.codeSize + stats.dataSize;
15328        } else {
15329            sizeBytes = stats.codeSize;
15330        }
15331
15332        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15333            unfreezePackage(packageName);
15334            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15335                    "Not enough free space to move");
15336        }
15337
15338        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15339
15340        final CountDownLatch installedLatch = new CountDownLatch(1);
15341        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15342            @Override
15343            public void onUserActionRequired(Intent intent) throws RemoteException {
15344                throw new IllegalStateException();
15345            }
15346
15347            @Override
15348            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15349                    Bundle extras) throws RemoteException {
15350                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15351                        + PackageManager.installStatusToString(returnCode, msg));
15352
15353                installedLatch.countDown();
15354
15355                // Regardless of success or failure of the move operation,
15356                // always unfreeze the package
15357                unfreezePackage(packageName);
15358
15359                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15360                switch (status) {
15361                    case PackageInstaller.STATUS_SUCCESS:
15362                        mMoveCallbacks.notifyStatusChanged(moveId,
15363                                PackageManager.MOVE_SUCCEEDED);
15364                        break;
15365                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15366                        mMoveCallbacks.notifyStatusChanged(moveId,
15367                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15368                        break;
15369                    default:
15370                        mMoveCallbacks.notifyStatusChanged(moveId,
15371                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15372                        break;
15373                }
15374            }
15375        };
15376
15377        final MoveInfo move;
15378        if (moveCompleteApp) {
15379            // Kick off a thread to report progress estimates
15380            new Thread() {
15381                @Override
15382                public void run() {
15383                    while (true) {
15384                        try {
15385                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15386                                break;
15387                            }
15388                        } catch (InterruptedException ignored) {
15389                        }
15390
15391                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15392                        final int progress = 10 + (int) MathUtils.constrain(
15393                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15394                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15395                    }
15396                }
15397            }.start();
15398
15399            final String dataAppName = codeFile.getName();
15400            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15401                    dataAppName, appId, seinfo);
15402        } else {
15403            move = null;
15404        }
15405
15406        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15407
15408        final Message msg = mHandler.obtainMessage(INIT_COPY);
15409        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15410        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15411                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15412        mHandler.sendMessage(msg);
15413    }
15414
15415    @Override
15416    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15417        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15418
15419        final int realMoveId = mNextMoveId.getAndIncrement();
15420        final Bundle extras = new Bundle();
15421        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15422        mMoveCallbacks.notifyCreated(realMoveId, extras);
15423
15424        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15425            @Override
15426            public void onCreated(int moveId, Bundle extras) {
15427                // Ignored
15428            }
15429
15430            @Override
15431            public void onStatusChanged(int moveId, int status, long estMillis) {
15432                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15433            }
15434        };
15435
15436        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15437        storage.setPrimaryStorageUuid(volumeUuid, callback);
15438        return realMoveId;
15439    }
15440
15441    @Override
15442    public int getMoveStatus(int moveId) {
15443        mContext.enforceCallingOrSelfPermission(
15444                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15445        return mMoveCallbacks.mLastStatus.get(moveId);
15446    }
15447
15448    @Override
15449    public void registerMoveCallback(IPackageMoveObserver callback) {
15450        mContext.enforceCallingOrSelfPermission(
15451                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15452        mMoveCallbacks.register(callback);
15453    }
15454
15455    @Override
15456    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15457        mContext.enforceCallingOrSelfPermission(
15458                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15459        mMoveCallbacks.unregister(callback);
15460    }
15461
15462    @Override
15463    public boolean setInstallLocation(int loc) {
15464        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15465                null);
15466        if (getInstallLocation() == loc) {
15467            return true;
15468        }
15469        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15470                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15471            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15472                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15473            return true;
15474        }
15475        return false;
15476   }
15477
15478    @Override
15479    public int getInstallLocation() {
15480        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15481                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15482                PackageHelper.APP_INSTALL_AUTO);
15483    }
15484
15485    /** Called by UserManagerService */
15486    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15487        mDirtyUsers.remove(userHandle);
15488        mSettings.removeUserLPw(userHandle);
15489        mPendingBroadcasts.remove(userHandle);
15490        if (mInstaller != null) {
15491            // Technically, we shouldn't be doing this with the package lock
15492            // held.  However, this is very rare, and there is already so much
15493            // other disk I/O going on, that we'll let it slide for now.
15494            final StorageManager storage = StorageManager.from(mContext);
15495            final List<VolumeInfo> vols = storage.getVolumes();
15496            for (VolumeInfo vol : vols) {
15497                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
15498                    final String volumeUuid = vol.getFsUuid();
15499                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15500                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15501                }
15502            }
15503        }
15504        mUserNeedsBadging.delete(userHandle);
15505        removeUnusedPackagesLILPw(userManager, userHandle);
15506    }
15507
15508    /**
15509     * We're removing userHandle and would like to remove any downloaded packages
15510     * that are no longer in use by any other user.
15511     * @param userHandle the user being removed
15512     */
15513    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15514        final boolean DEBUG_CLEAN_APKS = false;
15515        int [] users = userManager.getUserIdsLPr();
15516        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15517        while (psit.hasNext()) {
15518            PackageSetting ps = psit.next();
15519            if (ps.pkg == null) {
15520                continue;
15521            }
15522            final String packageName = ps.pkg.packageName;
15523            // Skip over if system app
15524            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15525                continue;
15526            }
15527            if (DEBUG_CLEAN_APKS) {
15528                Slog.i(TAG, "Checking package " + packageName);
15529            }
15530            boolean keep = false;
15531            for (int i = 0; i < users.length; i++) {
15532                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15533                    keep = true;
15534                    if (DEBUG_CLEAN_APKS) {
15535                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15536                                + users[i]);
15537                    }
15538                    break;
15539                }
15540            }
15541            if (!keep) {
15542                if (DEBUG_CLEAN_APKS) {
15543                    Slog.i(TAG, "  Removing package " + packageName);
15544                }
15545                mHandler.post(new Runnable() {
15546                    public void run() {
15547                        deletePackageX(packageName, userHandle, 0);
15548                    } //end run
15549                });
15550            }
15551        }
15552    }
15553
15554    /** Called by UserManagerService */
15555    void createNewUserLILPw(int userHandle, File path) {
15556        if (mInstaller != null) {
15557            mInstaller.createUserConfig(userHandle);
15558            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
15559            applyFactoryDefaultBrowserLPw(userHandle);
15560        }
15561    }
15562
15563    void newUserCreatedLILPw(final int userHandle) {
15564        // We cannot grant the default permissions with a lock held as
15565        // we query providers from other components for default handlers
15566        // such as enabled IMEs, etc.
15567        mHandler.post(new Runnable() {
15568            @Override
15569            public void run() {
15570                mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15571            }
15572        });
15573    }
15574
15575    @Override
15576    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15577        mContext.enforceCallingOrSelfPermission(
15578                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15579                "Only package verification agents can read the verifier device identity");
15580
15581        synchronized (mPackages) {
15582            return mSettings.getVerifierDeviceIdentityLPw();
15583        }
15584    }
15585
15586    @Override
15587    public void setPermissionEnforced(String permission, boolean enforced) {
15588        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15589        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15590            synchronized (mPackages) {
15591                if (mSettings.mReadExternalStorageEnforced == null
15592                        || mSettings.mReadExternalStorageEnforced != enforced) {
15593                    mSettings.mReadExternalStorageEnforced = enforced;
15594                    mSettings.writeLPr();
15595                }
15596            }
15597            // kill any non-foreground processes so we restart them and
15598            // grant/revoke the GID.
15599            final IActivityManager am = ActivityManagerNative.getDefault();
15600            if (am != null) {
15601                final long token = Binder.clearCallingIdentity();
15602                try {
15603                    am.killProcessesBelowForeground("setPermissionEnforcement");
15604                } catch (RemoteException e) {
15605                } finally {
15606                    Binder.restoreCallingIdentity(token);
15607                }
15608            }
15609        } else {
15610            throw new IllegalArgumentException("No selective enforcement for " + permission);
15611        }
15612    }
15613
15614    @Override
15615    @Deprecated
15616    public boolean isPermissionEnforced(String permission) {
15617        return true;
15618    }
15619
15620    @Override
15621    public boolean isStorageLow() {
15622        final long token = Binder.clearCallingIdentity();
15623        try {
15624            final DeviceStorageMonitorInternal
15625                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15626            if (dsm != null) {
15627                return dsm.isMemoryLow();
15628            } else {
15629                return false;
15630            }
15631        } finally {
15632            Binder.restoreCallingIdentity(token);
15633        }
15634    }
15635
15636    @Override
15637    public IPackageInstaller getPackageInstaller() {
15638        return mInstallerService;
15639    }
15640
15641    private boolean userNeedsBadging(int userId) {
15642        int index = mUserNeedsBadging.indexOfKey(userId);
15643        if (index < 0) {
15644            final UserInfo userInfo;
15645            final long token = Binder.clearCallingIdentity();
15646            try {
15647                userInfo = sUserManager.getUserInfo(userId);
15648            } finally {
15649                Binder.restoreCallingIdentity(token);
15650            }
15651            final boolean b;
15652            if (userInfo != null && userInfo.isManagedProfile()) {
15653                b = true;
15654            } else {
15655                b = false;
15656            }
15657            mUserNeedsBadging.put(userId, b);
15658            return b;
15659        }
15660        return mUserNeedsBadging.valueAt(index);
15661    }
15662
15663    @Override
15664    public KeySet getKeySetByAlias(String packageName, String alias) {
15665        if (packageName == null || alias == null) {
15666            return null;
15667        }
15668        synchronized(mPackages) {
15669            final PackageParser.Package pkg = mPackages.get(packageName);
15670            if (pkg == null) {
15671                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15672                throw new IllegalArgumentException("Unknown package: " + packageName);
15673            }
15674            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15675            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15676        }
15677    }
15678
15679    @Override
15680    public KeySet getSigningKeySet(String packageName) {
15681        if (packageName == null) {
15682            return null;
15683        }
15684        synchronized(mPackages) {
15685            final PackageParser.Package pkg = mPackages.get(packageName);
15686            if (pkg == null) {
15687                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15688                throw new IllegalArgumentException("Unknown package: " + packageName);
15689            }
15690            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15691                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15692                throw new SecurityException("May not access signing KeySet of other apps.");
15693            }
15694            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15695            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15696        }
15697    }
15698
15699    @Override
15700    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15701        if (packageName == null || ks == null) {
15702            return false;
15703        }
15704        synchronized(mPackages) {
15705            final PackageParser.Package pkg = mPackages.get(packageName);
15706            if (pkg == null) {
15707                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15708                throw new IllegalArgumentException("Unknown package: " + packageName);
15709            }
15710            IBinder ksh = ks.getToken();
15711            if (ksh instanceof KeySetHandle) {
15712                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15713                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15714            }
15715            return false;
15716        }
15717    }
15718
15719    @Override
15720    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15721        if (packageName == null || ks == null) {
15722            return false;
15723        }
15724        synchronized(mPackages) {
15725            final PackageParser.Package pkg = mPackages.get(packageName);
15726            if (pkg == null) {
15727                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15728                throw new IllegalArgumentException("Unknown package: " + packageName);
15729            }
15730            IBinder ksh = ks.getToken();
15731            if (ksh instanceof KeySetHandle) {
15732                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15733                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15734            }
15735            return false;
15736        }
15737    }
15738
15739    public void getUsageStatsIfNoPackageUsageInfo() {
15740        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15741            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15742            if (usm == null) {
15743                throw new IllegalStateException("UsageStatsManager must be initialized");
15744            }
15745            long now = System.currentTimeMillis();
15746            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15747            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15748                String packageName = entry.getKey();
15749                PackageParser.Package pkg = mPackages.get(packageName);
15750                if (pkg == null) {
15751                    continue;
15752                }
15753                UsageStats usage = entry.getValue();
15754                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15755                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15756            }
15757        }
15758    }
15759
15760    /**
15761     * Check and throw if the given before/after packages would be considered a
15762     * downgrade.
15763     */
15764    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15765            throws PackageManagerException {
15766        if (after.versionCode < before.mVersionCode) {
15767            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15768                    "Update version code " + after.versionCode + " is older than current "
15769                    + before.mVersionCode);
15770        } else if (after.versionCode == before.mVersionCode) {
15771            if (after.baseRevisionCode < before.baseRevisionCode) {
15772                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15773                        "Update base revision code " + after.baseRevisionCode
15774                        + " is older than current " + before.baseRevisionCode);
15775            }
15776
15777            if (!ArrayUtils.isEmpty(after.splitNames)) {
15778                for (int i = 0; i < after.splitNames.length; i++) {
15779                    final String splitName = after.splitNames[i];
15780                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15781                    if (j != -1) {
15782                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15783                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15784                                    "Update split " + splitName + " revision code "
15785                                    + after.splitRevisionCodes[i] + " is older than current "
15786                                    + before.splitRevisionCodes[j]);
15787                        }
15788                    }
15789                }
15790            }
15791        }
15792    }
15793
15794    private static class MoveCallbacks extends Handler {
15795        private static final int MSG_CREATED = 1;
15796        private static final int MSG_STATUS_CHANGED = 2;
15797
15798        private final RemoteCallbackList<IPackageMoveObserver>
15799                mCallbacks = new RemoteCallbackList<>();
15800
15801        private final SparseIntArray mLastStatus = new SparseIntArray();
15802
15803        public MoveCallbacks(Looper looper) {
15804            super(looper);
15805        }
15806
15807        public void register(IPackageMoveObserver callback) {
15808            mCallbacks.register(callback);
15809        }
15810
15811        public void unregister(IPackageMoveObserver callback) {
15812            mCallbacks.unregister(callback);
15813        }
15814
15815        @Override
15816        public void handleMessage(Message msg) {
15817            final SomeArgs args = (SomeArgs) msg.obj;
15818            final int n = mCallbacks.beginBroadcast();
15819            for (int i = 0; i < n; i++) {
15820                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15821                try {
15822                    invokeCallback(callback, msg.what, args);
15823                } catch (RemoteException ignored) {
15824                }
15825            }
15826            mCallbacks.finishBroadcast();
15827            args.recycle();
15828        }
15829
15830        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15831                throws RemoteException {
15832            switch (what) {
15833                case MSG_CREATED: {
15834                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15835                    break;
15836                }
15837                case MSG_STATUS_CHANGED: {
15838                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15839                    break;
15840                }
15841            }
15842        }
15843
15844        private void notifyCreated(int moveId, Bundle extras) {
15845            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15846
15847            final SomeArgs args = SomeArgs.obtain();
15848            args.argi1 = moveId;
15849            args.arg2 = extras;
15850            obtainMessage(MSG_CREATED, args).sendToTarget();
15851        }
15852
15853        private void notifyStatusChanged(int moveId, int status) {
15854            notifyStatusChanged(moveId, status, -1);
15855        }
15856
15857        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15858            Slog.v(TAG, "Move " + moveId + " status " + status);
15859
15860            final SomeArgs args = SomeArgs.obtain();
15861            args.argi1 = moveId;
15862            args.argi2 = status;
15863            args.arg3 = estMillis;
15864            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15865
15866            synchronized (mLastStatus) {
15867                mLastStatus.put(moveId, status);
15868            }
15869        }
15870    }
15871
15872    private final class OnPermissionChangeListeners extends Handler {
15873        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
15874
15875        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
15876                new RemoteCallbackList<>();
15877
15878        public OnPermissionChangeListeners(Looper looper) {
15879            super(looper);
15880        }
15881
15882        @Override
15883        public void handleMessage(Message msg) {
15884            switch (msg.what) {
15885                case MSG_ON_PERMISSIONS_CHANGED: {
15886                    final int uid = msg.arg1;
15887                    handleOnPermissionsChanged(uid);
15888                } break;
15889            }
15890        }
15891
15892        public void addListenerLocked(IOnPermissionsChangeListener listener) {
15893            mPermissionListeners.register(listener);
15894
15895        }
15896
15897        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
15898            mPermissionListeners.unregister(listener);
15899        }
15900
15901        public void onPermissionsChanged(int uid) {
15902            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
15903                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
15904            }
15905        }
15906
15907        private void handleOnPermissionsChanged(int uid) {
15908            final int count = mPermissionListeners.beginBroadcast();
15909            try {
15910                for (int i = 0; i < count; i++) {
15911                    IOnPermissionsChangeListener callback = mPermissionListeners
15912                            .getBroadcastItem(i);
15913                    try {
15914                        callback.onPermissionsChanged(uid);
15915                    } catch (RemoteException e) {
15916                        Log.e(TAG, "Permission listener is dead", e);
15917                    }
15918                }
15919            } finally {
15920                mPermissionListeners.finishBroadcast();
15921            }
15922        }
15923    }
15924
15925    private class PackageManagerInternalImpl extends PackageManagerInternal {
15926        @Override
15927        public void setLocationPackagesProvider(PackagesProvider provider) {
15928            synchronized (mPackages) {
15929                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
15930            }
15931        }
15932
15933        @Override
15934        public void setImePackagesProvider(PackagesProvider provider) {
15935            synchronized (mPackages) {
15936                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
15937            }
15938        }
15939
15940        @Override
15941        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
15942            synchronized (mPackages) {
15943                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
15944            }
15945        }
15946    }
15947
15948    @Override
15949    public void grantDefaultPermissions(final int userId) {
15950        enforceSystemOrPhoneCaller("grantDefaultPermissions");
15951        long token = Binder.clearCallingIdentity();
15952        try {
15953            // We cannot grant the default permissions with a lock held as
15954            // we query providers from other components for default handlers
15955            // such as enabled IMEs, etc.
15956            mHandler.post(new Runnable() {
15957                @Override
15958                public void run() {
15959                    mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15960                }
15961            });
15962        } finally {
15963            Binder.restoreCallingIdentity(token);
15964        }
15965    }
15966
15967    @Override
15968    public void setCarrierAppPackagesProvider(final IPackagesProvider provider) {
15969        enforceSystemOrPhoneCaller("setCarrierAppPackagesProvider");
15970        long token = Binder.clearCallingIdentity();
15971        try {
15972            PackageManagerInternal.PackagesProvider wrapper =
15973                    new PackageManagerInternal.PackagesProvider() {
15974                @Override
15975                public String[] getPackages(int userId) {
15976                    try {
15977                        return provider.getPackages(userId);
15978                    } catch (RemoteException e) {
15979                        return null;
15980                    }
15981                }
15982            };
15983            synchronized (mPackages) {
15984                mDefaultPermissionPolicy.setCarrierAppPackagesProviderLPw(wrapper);
15985            }
15986        } finally {
15987            Binder.restoreCallingIdentity(token);
15988        }
15989    }
15990
15991    private static void enforceSystemOrPhoneCaller(String tag) {
15992        int callingUid = Binder.getCallingUid();
15993        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
15994            throw new SecurityException(
15995                    "Cannot call " + tag + " from UID " + callingUid);
15996        }
15997    }
15998}
15999