PackageManagerService.java revision 9527b223a9d4a4d149bb005afc77148dbeeff785
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.readDefaultPreferredAppsLPw(this, 0);
2195            }
2196
2197            // If this is first boot after an OTA, and a normal boot, then
2198            // we need to clear code cache directories.
2199            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2200            if (mIsUpgrade && !onlyCore) {
2201                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2202                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2203                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2204                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2205                }
2206                mSettings.mFingerprint = Build.FINGERPRINT;
2207            }
2208
2209            primeDomainVerificationsLPw();
2210            checkDefaultBrowser();
2211
2212            // All the changes are done during package scanning.
2213            mSettings.updateInternalDatabaseVersion();
2214
2215            // can downgrade to reader
2216            mSettings.writeLPr();
2217
2218            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2219                    SystemClock.uptimeMillis());
2220
2221            mRequiredVerifierPackage = getRequiredVerifierLPr();
2222
2223            mInstallerService = new PackageInstallerService(context, this);
2224
2225            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2226            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2227                    mIntentFilterVerifierComponent);
2228
2229        } // synchronized (mPackages)
2230        } // synchronized (mInstallLock)
2231
2232        // Now after opening every single application zip, make sure they
2233        // are all flushed.  Not really needed, but keeps things nice and
2234        // tidy.
2235        Runtime.getRuntime().gc();
2236
2237        // Expose private service for system components to use.
2238        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2239    }
2240
2241    @Override
2242    public boolean isFirstBoot() {
2243        return !mRestoredSettings;
2244    }
2245
2246    @Override
2247    public boolean isOnlyCoreApps() {
2248        return mOnlyCore;
2249    }
2250
2251    @Override
2252    public boolean isUpgrade() {
2253        return mIsUpgrade;
2254    }
2255
2256    private String getRequiredVerifierLPr() {
2257        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2258        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2259                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2260
2261        String requiredVerifier = null;
2262
2263        final int N = receivers.size();
2264        for (int i = 0; i < N; i++) {
2265            final ResolveInfo info = receivers.get(i);
2266
2267            if (info.activityInfo == null) {
2268                continue;
2269            }
2270
2271            final String packageName = info.activityInfo.packageName;
2272
2273            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2274                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2275                continue;
2276            }
2277
2278            if (requiredVerifier != null) {
2279                throw new RuntimeException("There can be only one required verifier");
2280            }
2281
2282            requiredVerifier = packageName;
2283        }
2284
2285        return requiredVerifier;
2286    }
2287
2288    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2289        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2290        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2291                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2292
2293        ComponentName verifierComponentName = null;
2294
2295        int priority = -1000;
2296        final int N = receivers.size();
2297        for (int i = 0; i < N; i++) {
2298            final ResolveInfo info = receivers.get(i);
2299
2300            if (info.activityInfo == null) {
2301                continue;
2302            }
2303
2304            final String packageName = info.activityInfo.packageName;
2305
2306            final PackageSetting ps = mSettings.mPackages.get(packageName);
2307            if (ps == null) {
2308                continue;
2309            }
2310
2311            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2312                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2313                continue;
2314            }
2315
2316            // Select the IntentFilterVerifier with the highest priority
2317            if (priority < info.priority) {
2318                priority = info.priority;
2319                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2320                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2321                        + verifierComponentName + " with priority: " + info.priority);
2322            }
2323        }
2324
2325        return verifierComponentName;
2326    }
2327
2328    private void primeDomainVerificationsLPw() {
2329        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2330        boolean updated = false;
2331        ArraySet<String> allHostsSet = new ArraySet<>();
2332        for (PackageParser.Package pkg : mPackages.values()) {
2333            final String packageName = pkg.packageName;
2334            if (!hasDomainURLs(pkg)) {
2335                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2336                            "package with no domain URLs: " + packageName);
2337                continue;
2338            }
2339            if (!pkg.isSystemApp()) {
2340                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2341                        "No priming domain verifications for a non system package : " +
2342                                packageName);
2343                continue;
2344            }
2345            for (PackageParser.Activity a : pkg.activities) {
2346                for (ActivityIntentInfo filter : a.intents) {
2347                    if (hasValidDomains(filter)) {
2348                        allHostsSet.addAll(filter.getHostsList());
2349                    }
2350                }
2351            }
2352            if (allHostsSet.size() == 0) {
2353                allHostsSet.add("*");
2354            }
2355            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2356            IntentFilterVerificationInfo ivi =
2357                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2358            if (ivi != null) {
2359                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2360                        "Priming domain verifications for package: " + packageName +
2361                        " with hosts:" + ivi.getDomainsString());
2362                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2363                updated = true;
2364            }
2365            else {
2366                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2367                        "No priming domain verifications for package: " + packageName);
2368            }
2369            allHostsSet.clear();
2370        }
2371        if (updated) {
2372            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2373                    "Will need to write primed domain verifications");
2374        }
2375        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2376    }
2377
2378    private void checkDefaultBrowser() {
2379        final int myUserId = UserHandle.myUserId();
2380        final String packageName = getDefaultBrowserPackageName(myUserId);
2381        PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2382        if (info == null) {
2383            Slog.w(TAG, "Default browser no longer installed: " + packageName);
2384            setDefaultBrowserPackageName(null, myUserId);
2385        }
2386    }
2387
2388    @Override
2389    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2390            throws RemoteException {
2391        try {
2392            return super.onTransact(code, data, reply, flags);
2393        } catch (RuntimeException e) {
2394            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2395                Slog.wtf(TAG, "Package Manager Crash", e);
2396            }
2397            throw e;
2398        }
2399    }
2400
2401    void cleanupInstallFailedPackage(PackageSetting ps) {
2402        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2403
2404        removeDataDirsLI(ps.volumeUuid, ps.name);
2405        if (ps.codePath != null) {
2406            if (ps.codePath.isDirectory()) {
2407                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2408            } else {
2409                ps.codePath.delete();
2410            }
2411        }
2412        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2413            if (ps.resourcePath.isDirectory()) {
2414                FileUtils.deleteContents(ps.resourcePath);
2415            }
2416            ps.resourcePath.delete();
2417        }
2418        mSettings.removePackageLPw(ps.name);
2419    }
2420
2421    static int[] appendInts(int[] cur, int[] add) {
2422        if (add == null) return cur;
2423        if (cur == null) return add;
2424        final int N = add.length;
2425        for (int i=0; i<N; i++) {
2426            cur = appendInt(cur, add[i]);
2427        }
2428        return cur;
2429    }
2430
2431    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2432        if (!sUserManager.exists(userId)) return null;
2433        final PackageSetting ps = (PackageSetting) p.mExtras;
2434        if (ps == null) {
2435            return null;
2436        }
2437
2438        final PermissionsState permissionsState = ps.getPermissionsState();
2439
2440        final int[] gids = permissionsState.computeGids(userId);
2441        final Set<String> permissions = permissionsState.getPermissions(userId);
2442        final PackageUserState state = ps.readUserState(userId);
2443
2444        return PackageParser.generatePackageInfo(p, gids, flags,
2445                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2446    }
2447
2448    @Override
2449    public boolean isPackageFrozen(String packageName) {
2450        synchronized (mPackages) {
2451            final PackageSetting ps = mSettings.mPackages.get(packageName);
2452            if (ps != null) {
2453                return ps.frozen;
2454            }
2455        }
2456        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2457        return true;
2458    }
2459
2460    @Override
2461    public boolean isPackageAvailable(String packageName, int userId) {
2462        if (!sUserManager.exists(userId)) return false;
2463        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2464        synchronized (mPackages) {
2465            PackageParser.Package p = mPackages.get(packageName);
2466            if (p != null) {
2467                final PackageSetting ps = (PackageSetting) p.mExtras;
2468                if (ps != null) {
2469                    final PackageUserState state = ps.readUserState(userId);
2470                    if (state != null) {
2471                        return PackageParser.isAvailable(state);
2472                    }
2473                }
2474            }
2475        }
2476        return false;
2477    }
2478
2479    @Override
2480    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2481        if (!sUserManager.exists(userId)) return null;
2482        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2483        // reader
2484        synchronized (mPackages) {
2485            PackageParser.Package p = mPackages.get(packageName);
2486            if (DEBUG_PACKAGE_INFO)
2487                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2488            if (p != null) {
2489                return generatePackageInfo(p, flags, userId);
2490            }
2491            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2492                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2493            }
2494        }
2495        return null;
2496    }
2497
2498    @Override
2499    public String[] currentToCanonicalPackageNames(String[] names) {
2500        String[] out = new String[names.length];
2501        // reader
2502        synchronized (mPackages) {
2503            for (int i=names.length-1; i>=0; i--) {
2504                PackageSetting ps = mSettings.mPackages.get(names[i]);
2505                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2506            }
2507        }
2508        return out;
2509    }
2510
2511    @Override
2512    public String[] canonicalToCurrentPackageNames(String[] names) {
2513        String[] out = new String[names.length];
2514        // reader
2515        synchronized (mPackages) {
2516            for (int i=names.length-1; i>=0; i--) {
2517                String cur = mSettings.mRenamedPackages.get(names[i]);
2518                out[i] = cur != null ? cur : names[i];
2519            }
2520        }
2521        return out;
2522    }
2523
2524    @Override
2525    public int getPackageUid(String packageName, int userId) {
2526        if (!sUserManager.exists(userId)) return -1;
2527        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2528
2529        // reader
2530        synchronized (mPackages) {
2531            PackageParser.Package p = mPackages.get(packageName);
2532            if(p != null) {
2533                return UserHandle.getUid(userId, p.applicationInfo.uid);
2534            }
2535            PackageSetting ps = mSettings.mPackages.get(packageName);
2536            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2537                return -1;
2538            }
2539            p = ps.pkg;
2540            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2541        }
2542    }
2543
2544    @Override
2545    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2546        if (!sUserManager.exists(userId)) {
2547            return null;
2548        }
2549
2550        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2551                "getPackageGids");
2552
2553        // reader
2554        synchronized (mPackages) {
2555            PackageParser.Package p = mPackages.get(packageName);
2556            if (DEBUG_PACKAGE_INFO) {
2557                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2558            }
2559            if (p != null) {
2560                PackageSetting ps = (PackageSetting) p.mExtras;
2561                return ps.getPermissionsState().computeGids(userId);
2562            }
2563        }
2564
2565        return null;
2566    }
2567
2568    @Override
2569    public int getMountExternalMode(int uid) {
2570        if (Process.isIsolated(uid)) {
2571            return Zygote.MOUNT_EXTERNAL_NONE;
2572        } else {
2573            if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2574                return Zygote.MOUNT_EXTERNAL_WRITE;
2575            } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2576                return Zygote.MOUNT_EXTERNAL_READ;
2577            } else {
2578                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2579            }
2580        }
2581    }
2582
2583    static PermissionInfo generatePermissionInfo(
2584            BasePermission bp, int flags) {
2585        if (bp.perm != null) {
2586            return PackageParser.generatePermissionInfo(bp.perm, flags);
2587        }
2588        PermissionInfo pi = new PermissionInfo();
2589        pi.name = bp.name;
2590        pi.packageName = bp.sourcePackage;
2591        pi.nonLocalizedLabel = bp.name;
2592        pi.protectionLevel = bp.protectionLevel;
2593        return pi;
2594    }
2595
2596    @Override
2597    public PermissionInfo getPermissionInfo(String name, int flags) {
2598        // reader
2599        synchronized (mPackages) {
2600            final BasePermission p = mSettings.mPermissions.get(name);
2601            if (p != null) {
2602                return generatePermissionInfo(p, flags);
2603            }
2604            return null;
2605        }
2606    }
2607
2608    @Override
2609    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2610        // reader
2611        synchronized (mPackages) {
2612            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2613            for (BasePermission p : mSettings.mPermissions.values()) {
2614                if (group == null) {
2615                    if (p.perm == null || p.perm.info.group == null) {
2616                        out.add(generatePermissionInfo(p, flags));
2617                    }
2618                } else {
2619                    if (p.perm != null && group.equals(p.perm.info.group)) {
2620                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2621                    }
2622                }
2623            }
2624
2625            if (out.size() > 0) {
2626                return out;
2627            }
2628            return mPermissionGroups.containsKey(group) ? out : null;
2629        }
2630    }
2631
2632    @Override
2633    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2634        // reader
2635        synchronized (mPackages) {
2636            return PackageParser.generatePermissionGroupInfo(
2637                    mPermissionGroups.get(name), flags);
2638        }
2639    }
2640
2641    @Override
2642    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2643        // reader
2644        synchronized (mPackages) {
2645            final int N = mPermissionGroups.size();
2646            ArrayList<PermissionGroupInfo> out
2647                    = new ArrayList<PermissionGroupInfo>(N);
2648            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2649                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2650            }
2651            return out;
2652        }
2653    }
2654
2655    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2656            int userId) {
2657        if (!sUserManager.exists(userId)) return null;
2658        PackageSetting ps = mSettings.mPackages.get(packageName);
2659        if (ps != null) {
2660            if (ps.pkg == null) {
2661                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2662                        flags, userId);
2663                if (pInfo != null) {
2664                    return pInfo.applicationInfo;
2665                }
2666                return null;
2667            }
2668            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2669                    ps.readUserState(userId), userId);
2670        }
2671        return null;
2672    }
2673
2674    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2675            int userId) {
2676        if (!sUserManager.exists(userId)) return null;
2677        PackageSetting ps = mSettings.mPackages.get(packageName);
2678        if (ps != null) {
2679            PackageParser.Package pkg = ps.pkg;
2680            if (pkg == null) {
2681                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2682                    return null;
2683                }
2684                // Only data remains, so we aren't worried about code paths
2685                pkg = new PackageParser.Package(packageName);
2686                pkg.applicationInfo.packageName = packageName;
2687                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2688                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2689                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2690                        packageName, userId).getAbsolutePath();
2691                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2692                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2693            }
2694            return generatePackageInfo(pkg, flags, userId);
2695        }
2696        return null;
2697    }
2698
2699    @Override
2700    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2701        if (!sUserManager.exists(userId)) return null;
2702        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2703        // writer
2704        synchronized (mPackages) {
2705            PackageParser.Package p = mPackages.get(packageName);
2706            if (DEBUG_PACKAGE_INFO) Log.v(
2707                    TAG, "getApplicationInfo " + packageName
2708                    + ": " + p);
2709            if (p != null) {
2710                PackageSetting ps = mSettings.mPackages.get(packageName);
2711                if (ps == null) return null;
2712                // Note: isEnabledLP() does not apply here - always return info
2713                return PackageParser.generateApplicationInfo(
2714                        p, flags, ps.readUserState(userId), userId);
2715            }
2716            if ("android".equals(packageName)||"system".equals(packageName)) {
2717                return mAndroidApplication;
2718            }
2719            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2720                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2721            }
2722        }
2723        return null;
2724    }
2725
2726    @Override
2727    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2728            final IPackageDataObserver observer) {
2729        mContext.enforceCallingOrSelfPermission(
2730                android.Manifest.permission.CLEAR_APP_CACHE, null);
2731        // Queue up an async operation since clearing cache may take a little while.
2732        mHandler.post(new Runnable() {
2733            public void run() {
2734                mHandler.removeCallbacks(this);
2735                int retCode = -1;
2736                synchronized (mInstallLock) {
2737                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2738                    if (retCode < 0) {
2739                        Slog.w(TAG, "Couldn't clear application caches");
2740                    }
2741                }
2742                if (observer != null) {
2743                    try {
2744                        observer.onRemoveCompleted(null, (retCode >= 0));
2745                    } catch (RemoteException e) {
2746                        Slog.w(TAG, "RemoveException when invoking call back");
2747                    }
2748                }
2749            }
2750        });
2751    }
2752
2753    @Override
2754    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2755            final IntentSender pi) {
2756        mContext.enforceCallingOrSelfPermission(
2757                android.Manifest.permission.CLEAR_APP_CACHE, null);
2758        // Queue up an async operation since clearing cache may take a little while.
2759        mHandler.post(new Runnable() {
2760            public void run() {
2761                mHandler.removeCallbacks(this);
2762                int retCode = -1;
2763                synchronized (mInstallLock) {
2764                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2765                    if (retCode < 0) {
2766                        Slog.w(TAG, "Couldn't clear application caches");
2767                    }
2768                }
2769                if(pi != null) {
2770                    try {
2771                        // Callback via pending intent
2772                        int code = (retCode >= 0) ? 1 : 0;
2773                        pi.sendIntent(null, code, null,
2774                                null, null);
2775                    } catch (SendIntentException e1) {
2776                        Slog.i(TAG, "Failed to send pending intent");
2777                    }
2778                }
2779            }
2780        });
2781    }
2782
2783    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2784        synchronized (mInstallLock) {
2785            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2786                throw new IOException("Failed to free enough space");
2787            }
2788        }
2789    }
2790
2791    @Override
2792    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2793        if (!sUserManager.exists(userId)) return null;
2794        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2795        synchronized (mPackages) {
2796            PackageParser.Activity a = mActivities.mActivities.get(component);
2797
2798            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2799            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2800                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2801                if (ps == null) return null;
2802                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2803                        userId);
2804            }
2805            if (mResolveComponentName.equals(component)) {
2806                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2807                        new PackageUserState(), userId);
2808            }
2809        }
2810        return null;
2811    }
2812
2813    @Override
2814    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2815            String resolvedType) {
2816        synchronized (mPackages) {
2817            PackageParser.Activity a = mActivities.mActivities.get(component);
2818            if (a == null) {
2819                return false;
2820            }
2821            for (int i=0; i<a.intents.size(); i++) {
2822                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2823                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2824                    return true;
2825                }
2826            }
2827            return false;
2828        }
2829    }
2830
2831    @Override
2832    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2833        if (!sUserManager.exists(userId)) return null;
2834        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2835        synchronized (mPackages) {
2836            PackageParser.Activity a = mReceivers.mActivities.get(component);
2837            if (DEBUG_PACKAGE_INFO) Log.v(
2838                TAG, "getReceiverInfo " + component + ": " + a);
2839            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2840                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2841                if (ps == null) return null;
2842                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2843                        userId);
2844            }
2845        }
2846        return null;
2847    }
2848
2849    @Override
2850    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2851        if (!sUserManager.exists(userId)) return null;
2852        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2853        synchronized (mPackages) {
2854            PackageParser.Service s = mServices.mServices.get(component);
2855            if (DEBUG_PACKAGE_INFO) Log.v(
2856                TAG, "getServiceInfo " + component + ": " + s);
2857            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2858                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2859                if (ps == null) return null;
2860                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2861                        userId);
2862            }
2863        }
2864        return null;
2865    }
2866
2867    @Override
2868    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2869        if (!sUserManager.exists(userId)) return null;
2870        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2871        synchronized (mPackages) {
2872            PackageParser.Provider p = mProviders.mProviders.get(component);
2873            if (DEBUG_PACKAGE_INFO) Log.v(
2874                TAG, "getProviderInfo " + component + ": " + p);
2875            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2876                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2877                if (ps == null) return null;
2878                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2879                        userId);
2880            }
2881        }
2882        return null;
2883    }
2884
2885    @Override
2886    public String[] getSystemSharedLibraryNames() {
2887        Set<String> libSet;
2888        synchronized (mPackages) {
2889            libSet = mSharedLibraries.keySet();
2890            int size = libSet.size();
2891            if (size > 0) {
2892                String[] libs = new String[size];
2893                libSet.toArray(libs);
2894                return libs;
2895            }
2896        }
2897        return null;
2898    }
2899
2900    /**
2901     * @hide
2902     */
2903    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2904        synchronized (mPackages) {
2905            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2906            if (lib != null && lib.apk != null) {
2907                return mPackages.get(lib.apk);
2908            }
2909        }
2910        return null;
2911    }
2912
2913    @Override
2914    public FeatureInfo[] getSystemAvailableFeatures() {
2915        Collection<FeatureInfo> featSet;
2916        synchronized (mPackages) {
2917            featSet = mAvailableFeatures.values();
2918            int size = featSet.size();
2919            if (size > 0) {
2920                FeatureInfo[] features = new FeatureInfo[size+1];
2921                featSet.toArray(features);
2922                FeatureInfo fi = new FeatureInfo();
2923                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2924                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2925                features[size] = fi;
2926                return features;
2927            }
2928        }
2929        return null;
2930    }
2931
2932    @Override
2933    public boolean hasSystemFeature(String name) {
2934        synchronized (mPackages) {
2935            return mAvailableFeatures.containsKey(name);
2936        }
2937    }
2938
2939    private void checkValidCaller(int uid, int userId) {
2940        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2941            return;
2942
2943        throw new SecurityException("Caller uid=" + uid
2944                + " is not privileged to communicate with user=" + userId);
2945    }
2946
2947    @Override
2948    public int checkPermission(String permName, String pkgName, int userId) {
2949        if (!sUserManager.exists(userId)) {
2950            return PackageManager.PERMISSION_DENIED;
2951        }
2952
2953        synchronized (mPackages) {
2954            final PackageParser.Package p = mPackages.get(pkgName);
2955            if (p != null && p.mExtras != null) {
2956                final PackageSetting ps = (PackageSetting) p.mExtras;
2957                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2958                    return PackageManager.PERMISSION_GRANTED;
2959                }
2960            }
2961        }
2962
2963        return PackageManager.PERMISSION_DENIED;
2964    }
2965
2966    @Override
2967    public int checkUidPermission(String permName, int uid) {
2968        final int userId = UserHandle.getUserId(uid);
2969
2970        if (!sUserManager.exists(userId)) {
2971            return PackageManager.PERMISSION_DENIED;
2972        }
2973
2974        synchronized (mPackages) {
2975            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2976            if (obj != null) {
2977                final SettingBase ps = (SettingBase) obj;
2978                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2979                    return PackageManager.PERMISSION_GRANTED;
2980                }
2981            } else {
2982                ArraySet<String> perms = mSystemPermissions.get(uid);
2983                if (perms != null && perms.contains(permName)) {
2984                    return PackageManager.PERMISSION_GRANTED;
2985                }
2986            }
2987        }
2988
2989        return PackageManager.PERMISSION_DENIED;
2990    }
2991
2992    /**
2993     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2994     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2995     * @param checkShell TODO(yamasani):
2996     * @param message the message to log on security exception
2997     */
2998    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2999            boolean checkShell, String message) {
3000        if (userId < 0) {
3001            throw new IllegalArgumentException("Invalid userId " + userId);
3002        }
3003        if (checkShell) {
3004            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3005        }
3006        if (userId == UserHandle.getUserId(callingUid)) return;
3007        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3008            if (requireFullPermission) {
3009                mContext.enforceCallingOrSelfPermission(
3010                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3011            } else {
3012                try {
3013                    mContext.enforceCallingOrSelfPermission(
3014                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3015                } catch (SecurityException se) {
3016                    mContext.enforceCallingOrSelfPermission(
3017                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3018                }
3019            }
3020        }
3021    }
3022
3023    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3024        if (callingUid == Process.SHELL_UID) {
3025            if (userHandle >= 0
3026                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3027                throw new SecurityException("Shell does not have permission to access user "
3028                        + userHandle);
3029            } else if (userHandle < 0) {
3030                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3031                        + Debug.getCallers(3));
3032            }
3033        }
3034    }
3035
3036    private BasePermission findPermissionTreeLP(String permName) {
3037        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3038            if (permName.startsWith(bp.name) &&
3039                    permName.length() > bp.name.length() &&
3040                    permName.charAt(bp.name.length()) == '.') {
3041                return bp;
3042            }
3043        }
3044        return null;
3045    }
3046
3047    private BasePermission checkPermissionTreeLP(String permName) {
3048        if (permName != null) {
3049            BasePermission bp = findPermissionTreeLP(permName);
3050            if (bp != null) {
3051                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3052                    return bp;
3053                }
3054                throw new SecurityException("Calling uid "
3055                        + Binder.getCallingUid()
3056                        + " is not allowed to add to permission tree "
3057                        + bp.name + " owned by uid " + bp.uid);
3058            }
3059        }
3060        throw new SecurityException("No permission tree found for " + permName);
3061    }
3062
3063    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3064        if (s1 == null) {
3065            return s2 == null;
3066        }
3067        if (s2 == null) {
3068            return false;
3069        }
3070        if (s1.getClass() != s2.getClass()) {
3071            return false;
3072        }
3073        return s1.equals(s2);
3074    }
3075
3076    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3077        if (pi1.icon != pi2.icon) return false;
3078        if (pi1.logo != pi2.logo) return false;
3079        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3080        if (!compareStrings(pi1.name, pi2.name)) return false;
3081        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3082        // We'll take care of setting this one.
3083        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3084        // These are not currently stored in settings.
3085        //if (!compareStrings(pi1.group, pi2.group)) return false;
3086        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3087        //if (pi1.labelRes != pi2.labelRes) return false;
3088        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3089        return true;
3090    }
3091
3092    int permissionInfoFootprint(PermissionInfo info) {
3093        int size = info.name.length();
3094        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3095        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3096        return size;
3097    }
3098
3099    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3100        int size = 0;
3101        for (BasePermission perm : mSettings.mPermissions.values()) {
3102            if (perm.uid == tree.uid) {
3103                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3104            }
3105        }
3106        return size;
3107    }
3108
3109    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3110        // We calculate the max size of permissions defined by this uid and throw
3111        // if that plus the size of 'info' would exceed our stated maximum.
3112        if (tree.uid != Process.SYSTEM_UID) {
3113            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3114            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3115                throw new SecurityException("Permission tree size cap exceeded");
3116            }
3117        }
3118    }
3119
3120    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3121        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3122            throw new SecurityException("Label must be specified in permission");
3123        }
3124        BasePermission tree = checkPermissionTreeLP(info.name);
3125        BasePermission bp = mSettings.mPermissions.get(info.name);
3126        boolean added = bp == null;
3127        boolean changed = true;
3128        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3129        if (added) {
3130            enforcePermissionCapLocked(info, tree);
3131            bp = new BasePermission(info.name, tree.sourcePackage,
3132                    BasePermission.TYPE_DYNAMIC);
3133        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3134            throw new SecurityException(
3135                    "Not allowed to modify non-dynamic permission "
3136                    + info.name);
3137        } else {
3138            if (bp.protectionLevel == fixedLevel
3139                    && bp.perm.owner.equals(tree.perm.owner)
3140                    && bp.uid == tree.uid
3141                    && comparePermissionInfos(bp.perm.info, info)) {
3142                changed = false;
3143            }
3144        }
3145        bp.protectionLevel = fixedLevel;
3146        info = new PermissionInfo(info);
3147        info.protectionLevel = fixedLevel;
3148        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3149        bp.perm.info.packageName = tree.perm.info.packageName;
3150        bp.uid = tree.uid;
3151        if (added) {
3152            mSettings.mPermissions.put(info.name, bp);
3153        }
3154        if (changed) {
3155            if (!async) {
3156                mSettings.writeLPr();
3157            } else {
3158                scheduleWriteSettingsLocked();
3159            }
3160        }
3161        return added;
3162    }
3163
3164    @Override
3165    public boolean addPermission(PermissionInfo info) {
3166        synchronized (mPackages) {
3167            return addPermissionLocked(info, false);
3168        }
3169    }
3170
3171    @Override
3172    public boolean addPermissionAsync(PermissionInfo info) {
3173        synchronized (mPackages) {
3174            return addPermissionLocked(info, true);
3175        }
3176    }
3177
3178    @Override
3179    public void removePermission(String name) {
3180        synchronized (mPackages) {
3181            checkPermissionTreeLP(name);
3182            BasePermission bp = mSettings.mPermissions.get(name);
3183            if (bp != null) {
3184                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3185                    throw new SecurityException(
3186                            "Not allowed to modify non-dynamic permission "
3187                            + name);
3188                }
3189                mSettings.mPermissions.remove(name);
3190                mSettings.writeLPr();
3191            }
3192        }
3193    }
3194
3195    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3196            BasePermission bp) {
3197        int index = pkg.requestedPermissions.indexOf(bp.name);
3198        if (index == -1) {
3199            throw new SecurityException("Package " + pkg.packageName
3200                    + " has not requested permission " + bp.name);
3201        }
3202        if (!bp.isRuntime()) {
3203            throw new SecurityException("Permission " + bp.name
3204                    + " is not a changeable permission type");
3205        }
3206    }
3207
3208    @Override
3209    public void grantRuntimePermission(String packageName, String name, final int userId) {
3210        if (!sUserManager.exists(userId)) {
3211            Log.e(TAG, "No such user:" + userId);
3212            return;
3213        }
3214
3215        mContext.enforceCallingOrSelfPermission(
3216                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3217                "grantRuntimePermission");
3218
3219        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3220                "grantRuntimePermission");
3221
3222        final int uid;
3223        final SettingBase sb;
3224
3225        synchronized (mPackages) {
3226            final PackageParser.Package pkg = mPackages.get(packageName);
3227            if (pkg == null) {
3228                throw new IllegalArgumentException("Unknown package: " + packageName);
3229            }
3230
3231            final BasePermission bp = mSettings.mPermissions.get(name);
3232            if (bp == null) {
3233                throw new IllegalArgumentException("Unknown permission: " + name);
3234            }
3235
3236            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3237
3238            uid = pkg.applicationInfo.uid;
3239            sb = (SettingBase) pkg.mExtras;
3240            if (sb == null) {
3241                throw new IllegalArgumentException("Unknown package: " + packageName);
3242            }
3243
3244            final PermissionsState permissionsState = sb.getPermissionsState();
3245
3246            final int flags = permissionsState.getPermissionFlags(name, userId);
3247            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3248                throw new SecurityException("Cannot grant system fixed permission: "
3249                        + name + " for package: " + packageName);
3250            }
3251
3252            final int result = permissionsState.grantRuntimePermission(bp, userId);
3253            switch (result) {
3254                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3255                    return;
3256                }
3257
3258                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3259                    mHandler.post(new Runnable() {
3260                        @Override
3261                        public void run() {
3262                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3263                        }
3264                    });
3265                } break;
3266            }
3267
3268            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3269
3270            // Not critical if that is lost - app has to request again.
3271            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3272        }
3273
3274        if (READ_EXTERNAL_STORAGE.equals(name)
3275                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3276            final long token = Binder.clearCallingIdentity();
3277            try {
3278                final StorageManager storage = mContext.getSystemService(StorageManager.class);
3279                storage.remountUid(uid);
3280            } finally {
3281                Binder.restoreCallingIdentity(token);
3282            }
3283        }
3284    }
3285
3286    @Override
3287    public void revokeRuntimePermission(String packageName, String name, int userId) {
3288        if (!sUserManager.exists(userId)) {
3289            Log.e(TAG, "No such user:" + userId);
3290            return;
3291        }
3292
3293        mContext.enforceCallingOrSelfPermission(
3294                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3295                "revokeRuntimePermission");
3296
3297        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3298                "revokeRuntimePermission");
3299
3300        final SettingBase sb;
3301
3302        synchronized (mPackages) {
3303            final PackageParser.Package pkg = mPackages.get(packageName);
3304            if (pkg == null) {
3305                throw new IllegalArgumentException("Unknown package: " + packageName);
3306            }
3307
3308            final BasePermission bp = mSettings.mPermissions.get(name);
3309            if (bp == null) {
3310                throw new IllegalArgumentException("Unknown permission: " + name);
3311            }
3312
3313            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3314
3315            sb = (SettingBase) pkg.mExtras;
3316            if (sb == null) {
3317                throw new IllegalArgumentException("Unknown package: " + packageName);
3318            }
3319
3320            final PermissionsState permissionsState = sb.getPermissionsState();
3321
3322            final int flags = permissionsState.getPermissionFlags(name, userId);
3323            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3324                throw new SecurityException("Cannot revoke system fixed permission: "
3325                        + name + " for package: " + packageName);
3326            }
3327
3328            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3329                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3330                return;
3331            }
3332
3333            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3334
3335            // Critical, after this call app should never have the permission.
3336            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3337        }
3338
3339        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3340    }
3341
3342    @Override
3343    public int getPermissionFlags(String name, String packageName, int userId) {
3344        if (!sUserManager.exists(userId)) {
3345            return 0;
3346        }
3347
3348        mContext.enforceCallingOrSelfPermission(
3349                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3350                "getPermissionFlags");
3351
3352        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3353                "getPermissionFlags");
3354
3355        synchronized (mPackages) {
3356            final PackageParser.Package pkg = mPackages.get(packageName);
3357            if (pkg == null) {
3358                throw new IllegalArgumentException("Unknown package: " + packageName);
3359            }
3360
3361            final BasePermission bp = mSettings.mPermissions.get(name);
3362            if (bp == null) {
3363                throw new IllegalArgumentException("Unknown permission: " + name);
3364            }
3365
3366            SettingBase sb = (SettingBase) pkg.mExtras;
3367            if (sb == null) {
3368                throw new IllegalArgumentException("Unknown package: " + packageName);
3369            }
3370
3371            PermissionsState permissionsState = sb.getPermissionsState();
3372            return permissionsState.getPermissionFlags(name, userId);
3373        }
3374    }
3375
3376    @Override
3377    public void updatePermissionFlags(String name, String packageName, int flagMask,
3378            int flagValues, int userId) {
3379        if (!sUserManager.exists(userId)) {
3380            return;
3381        }
3382
3383        mContext.enforceCallingOrSelfPermission(
3384                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3385                "updatePermissionFlags");
3386
3387        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3388                "updatePermissionFlags");
3389
3390        // Only the system can change system fixed flags.
3391        if (getCallingUid() != Process.SYSTEM_UID) {
3392            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3393            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3394        }
3395
3396        synchronized (mPackages) {
3397            final PackageParser.Package pkg = mPackages.get(packageName);
3398            if (pkg == null) {
3399                throw new IllegalArgumentException("Unknown package: " + packageName);
3400            }
3401
3402            final BasePermission bp = mSettings.mPermissions.get(name);
3403            if (bp == null) {
3404                throw new IllegalArgumentException("Unknown permission: " + name);
3405            }
3406
3407            SettingBase sb = (SettingBase) pkg.mExtras;
3408            if (sb == null) {
3409                throw new IllegalArgumentException("Unknown package: " + packageName);
3410            }
3411
3412            PermissionsState permissionsState = sb.getPermissionsState();
3413
3414            // Only the package manager can change flags for system component permissions.
3415            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3416            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3417                return;
3418            }
3419
3420            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3421
3422            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3423                // Install and runtime permissions are stored in different places,
3424                // so figure out what permission changed and persist the change.
3425                if (permissionsState.getInstallPermissionState(name) != null) {
3426                    scheduleWriteSettingsLocked();
3427                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3428                        || hadState) {
3429                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3430                }
3431            }
3432        }
3433    }
3434
3435    /**
3436     * Update the permission flags for all packages and runtime permissions of a user in order
3437     * to allow device or profile owner to remove POLICY_FIXED.
3438     */
3439    @Override
3440    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3441        if (!sUserManager.exists(userId)) {
3442            return;
3443        }
3444
3445        mContext.enforceCallingOrSelfPermission(
3446                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3447                "updatePermissionFlagsForAllApps");
3448
3449        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3450                "updatePermissionFlagsForAllApps");
3451
3452        // Only the system can change system fixed flags.
3453        if (getCallingUid() != Process.SYSTEM_UID) {
3454            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3455            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3456        }
3457
3458        synchronized (mPackages) {
3459            boolean changed = false;
3460            final int packageCount = mPackages.size();
3461            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3462                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3463                SettingBase sb = (SettingBase) pkg.mExtras;
3464                if (sb == null) {
3465                    continue;
3466                }
3467                PermissionsState permissionsState = sb.getPermissionsState();
3468                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3469                        userId, flagMask, flagValues);
3470            }
3471            if (changed) {
3472                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3473            }
3474        }
3475    }
3476
3477    @Override
3478    public boolean shouldShowRequestPermissionRationale(String permissionName,
3479            String packageName, int userId) {
3480        if (UserHandle.getCallingUserId() != userId) {
3481            mContext.enforceCallingPermission(
3482                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3483                    "canShowRequestPermissionRationale for user " + userId);
3484        }
3485
3486        final int uid = getPackageUid(packageName, userId);
3487        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3488            return false;
3489        }
3490
3491        if (checkPermission(permissionName, packageName, userId)
3492                == PackageManager.PERMISSION_GRANTED) {
3493            return false;
3494        }
3495
3496        final int flags;
3497
3498        final long identity = Binder.clearCallingIdentity();
3499        try {
3500            flags = getPermissionFlags(permissionName,
3501                    packageName, userId);
3502        } finally {
3503            Binder.restoreCallingIdentity(identity);
3504        }
3505
3506        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3507                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3508                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3509
3510        if ((flags & fixedFlags) != 0) {
3511            return false;
3512        }
3513
3514        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3515    }
3516
3517    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3518        BasePermission bp = mSettings.mPermissions.get(permission);
3519        if (bp == null) {
3520            throw new SecurityException("Missing " + permission + " permission");
3521        }
3522
3523        SettingBase sb = (SettingBase) pkg.mExtras;
3524        PermissionsState permissionsState = sb.getPermissionsState();
3525
3526        if (permissionsState.grantInstallPermission(bp) !=
3527                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3528            scheduleWriteSettingsLocked();
3529        }
3530    }
3531
3532    @Override
3533    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3534        mContext.enforceCallingOrSelfPermission(
3535                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3536                "addOnPermissionsChangeListener");
3537
3538        synchronized (mPackages) {
3539            mOnPermissionChangeListeners.addListenerLocked(listener);
3540        }
3541    }
3542
3543    @Override
3544    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3545        synchronized (mPackages) {
3546            mOnPermissionChangeListeners.removeListenerLocked(listener);
3547        }
3548    }
3549
3550    @Override
3551    public boolean isProtectedBroadcast(String actionName) {
3552        synchronized (mPackages) {
3553            return mProtectedBroadcasts.contains(actionName);
3554        }
3555    }
3556
3557    @Override
3558    public int checkSignatures(String pkg1, String pkg2) {
3559        synchronized (mPackages) {
3560            final PackageParser.Package p1 = mPackages.get(pkg1);
3561            final PackageParser.Package p2 = mPackages.get(pkg2);
3562            if (p1 == null || p1.mExtras == null
3563                    || p2 == null || p2.mExtras == null) {
3564                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3565            }
3566            return compareSignatures(p1.mSignatures, p2.mSignatures);
3567        }
3568    }
3569
3570    @Override
3571    public int checkUidSignatures(int uid1, int uid2) {
3572        // Map to base uids.
3573        uid1 = UserHandle.getAppId(uid1);
3574        uid2 = UserHandle.getAppId(uid2);
3575        // reader
3576        synchronized (mPackages) {
3577            Signature[] s1;
3578            Signature[] s2;
3579            Object obj = mSettings.getUserIdLPr(uid1);
3580            if (obj != null) {
3581                if (obj instanceof SharedUserSetting) {
3582                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3583                } else if (obj instanceof PackageSetting) {
3584                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3585                } else {
3586                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3587                }
3588            } else {
3589                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3590            }
3591            obj = mSettings.getUserIdLPr(uid2);
3592            if (obj != null) {
3593                if (obj instanceof SharedUserSetting) {
3594                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3595                } else if (obj instanceof PackageSetting) {
3596                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3597                } else {
3598                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3599                }
3600            } else {
3601                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3602            }
3603            return compareSignatures(s1, s2);
3604        }
3605    }
3606
3607    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3608        final long identity = Binder.clearCallingIdentity();
3609        try {
3610            if (sb instanceof SharedUserSetting) {
3611                SharedUserSetting sus = (SharedUserSetting) sb;
3612                final int packageCount = sus.packages.size();
3613                for (int i = 0; i < packageCount; i++) {
3614                    PackageSetting susPs = sus.packages.valueAt(i);
3615                    if (userId == UserHandle.USER_ALL) {
3616                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3617                    } else {
3618                        final int uid = UserHandle.getUid(userId, susPs.appId);
3619                        killUid(uid, reason);
3620                    }
3621                }
3622            } else if (sb instanceof PackageSetting) {
3623                PackageSetting ps = (PackageSetting) sb;
3624                if (userId == UserHandle.USER_ALL) {
3625                    killApplication(ps.pkg.packageName, ps.appId, reason);
3626                } else {
3627                    final int uid = UserHandle.getUid(userId, ps.appId);
3628                    killUid(uid, reason);
3629                }
3630            }
3631        } finally {
3632            Binder.restoreCallingIdentity(identity);
3633        }
3634    }
3635
3636    private static void killUid(int uid, String reason) {
3637        IActivityManager am = ActivityManagerNative.getDefault();
3638        if (am != null) {
3639            try {
3640                am.killUid(uid, reason);
3641            } catch (RemoteException e) {
3642                /* ignore - same process */
3643            }
3644        }
3645    }
3646
3647    /**
3648     * Compares two sets of signatures. Returns:
3649     * <br />
3650     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3651     * <br />
3652     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3653     * <br />
3654     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3655     * <br />
3656     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3657     * <br />
3658     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3659     */
3660    static int compareSignatures(Signature[] s1, Signature[] s2) {
3661        if (s1 == null) {
3662            return s2 == null
3663                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3664                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3665        }
3666
3667        if (s2 == null) {
3668            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3669        }
3670
3671        if (s1.length != s2.length) {
3672            return PackageManager.SIGNATURE_NO_MATCH;
3673        }
3674
3675        // Since both signature sets are of size 1, we can compare without HashSets.
3676        if (s1.length == 1) {
3677            return s1[0].equals(s2[0]) ?
3678                    PackageManager.SIGNATURE_MATCH :
3679                    PackageManager.SIGNATURE_NO_MATCH;
3680        }
3681
3682        ArraySet<Signature> set1 = new ArraySet<Signature>();
3683        for (Signature sig : s1) {
3684            set1.add(sig);
3685        }
3686        ArraySet<Signature> set2 = new ArraySet<Signature>();
3687        for (Signature sig : s2) {
3688            set2.add(sig);
3689        }
3690        // Make sure s2 contains all signatures in s1.
3691        if (set1.equals(set2)) {
3692            return PackageManager.SIGNATURE_MATCH;
3693        }
3694        return PackageManager.SIGNATURE_NO_MATCH;
3695    }
3696
3697    /**
3698     * If the database version for this type of package (internal storage or
3699     * external storage) is less than the version where package signatures
3700     * were updated, return true.
3701     */
3702    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3703        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3704                DatabaseVersion.SIGNATURE_END_ENTITY))
3705                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3706                        DatabaseVersion.SIGNATURE_END_ENTITY));
3707    }
3708
3709    /**
3710     * Used for backward compatibility to make sure any packages with
3711     * certificate chains get upgraded to the new style. {@code existingSigs}
3712     * will be in the old format (since they were stored on disk from before the
3713     * system upgrade) and {@code scannedSigs} will be in the newer format.
3714     */
3715    private int compareSignaturesCompat(PackageSignatures existingSigs,
3716            PackageParser.Package scannedPkg) {
3717        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3718            return PackageManager.SIGNATURE_NO_MATCH;
3719        }
3720
3721        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3722        for (Signature sig : existingSigs.mSignatures) {
3723            existingSet.add(sig);
3724        }
3725        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3726        for (Signature sig : scannedPkg.mSignatures) {
3727            try {
3728                Signature[] chainSignatures = sig.getChainSignatures();
3729                for (Signature chainSig : chainSignatures) {
3730                    scannedCompatSet.add(chainSig);
3731                }
3732            } catch (CertificateEncodingException e) {
3733                scannedCompatSet.add(sig);
3734            }
3735        }
3736        /*
3737         * Make sure the expanded scanned set contains all signatures in the
3738         * existing one.
3739         */
3740        if (scannedCompatSet.equals(existingSet)) {
3741            // Migrate the old signatures to the new scheme.
3742            existingSigs.assignSignatures(scannedPkg.mSignatures);
3743            // The new KeySets will be re-added later in the scanning process.
3744            synchronized (mPackages) {
3745                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3746            }
3747            return PackageManager.SIGNATURE_MATCH;
3748        }
3749        return PackageManager.SIGNATURE_NO_MATCH;
3750    }
3751
3752    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3753        if (isExternal(scannedPkg)) {
3754            return mSettings.isExternalDatabaseVersionOlderThan(
3755                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3756        } else {
3757            return mSettings.isInternalDatabaseVersionOlderThan(
3758                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3759        }
3760    }
3761
3762    private int compareSignaturesRecover(PackageSignatures existingSigs,
3763            PackageParser.Package scannedPkg) {
3764        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3765            return PackageManager.SIGNATURE_NO_MATCH;
3766        }
3767
3768        String msg = null;
3769        try {
3770            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3771                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3772                        + scannedPkg.packageName);
3773                return PackageManager.SIGNATURE_MATCH;
3774            }
3775        } catch (CertificateException e) {
3776            msg = e.getMessage();
3777        }
3778
3779        logCriticalInfo(Log.INFO,
3780                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3781        return PackageManager.SIGNATURE_NO_MATCH;
3782    }
3783
3784    @Override
3785    public String[] getPackagesForUid(int uid) {
3786        uid = UserHandle.getAppId(uid);
3787        // reader
3788        synchronized (mPackages) {
3789            Object obj = mSettings.getUserIdLPr(uid);
3790            if (obj instanceof SharedUserSetting) {
3791                final SharedUserSetting sus = (SharedUserSetting) obj;
3792                final int N = sus.packages.size();
3793                final String[] res = new String[N];
3794                final Iterator<PackageSetting> it = sus.packages.iterator();
3795                int i = 0;
3796                while (it.hasNext()) {
3797                    res[i++] = it.next().name;
3798                }
3799                return res;
3800            } else if (obj instanceof PackageSetting) {
3801                final PackageSetting ps = (PackageSetting) obj;
3802                return new String[] { ps.name };
3803            }
3804        }
3805        return null;
3806    }
3807
3808    @Override
3809    public String getNameForUid(int uid) {
3810        // reader
3811        synchronized (mPackages) {
3812            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3813            if (obj instanceof SharedUserSetting) {
3814                final SharedUserSetting sus = (SharedUserSetting) obj;
3815                return sus.name + ":" + sus.userId;
3816            } else if (obj instanceof PackageSetting) {
3817                final PackageSetting ps = (PackageSetting) obj;
3818                return ps.name;
3819            }
3820        }
3821        return null;
3822    }
3823
3824    @Override
3825    public int getUidForSharedUser(String sharedUserName) {
3826        if(sharedUserName == null) {
3827            return -1;
3828        }
3829        // reader
3830        synchronized (mPackages) {
3831            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3832            if (suid == null) {
3833                return -1;
3834            }
3835            return suid.userId;
3836        }
3837    }
3838
3839    @Override
3840    public int getFlagsForUid(int uid) {
3841        synchronized (mPackages) {
3842            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3843            if (obj instanceof SharedUserSetting) {
3844                final SharedUserSetting sus = (SharedUserSetting) obj;
3845                return sus.pkgFlags;
3846            } else if (obj instanceof PackageSetting) {
3847                final PackageSetting ps = (PackageSetting) obj;
3848                return ps.pkgFlags;
3849            }
3850        }
3851        return 0;
3852    }
3853
3854    @Override
3855    public int getPrivateFlagsForUid(int uid) {
3856        synchronized (mPackages) {
3857            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3858            if (obj instanceof SharedUserSetting) {
3859                final SharedUserSetting sus = (SharedUserSetting) obj;
3860                return sus.pkgPrivateFlags;
3861            } else if (obj instanceof PackageSetting) {
3862                final PackageSetting ps = (PackageSetting) obj;
3863                return ps.pkgPrivateFlags;
3864            }
3865        }
3866        return 0;
3867    }
3868
3869    @Override
3870    public boolean isUidPrivileged(int uid) {
3871        uid = UserHandle.getAppId(uid);
3872        // reader
3873        synchronized (mPackages) {
3874            Object obj = mSettings.getUserIdLPr(uid);
3875            if (obj instanceof SharedUserSetting) {
3876                final SharedUserSetting sus = (SharedUserSetting) obj;
3877                final Iterator<PackageSetting> it = sus.packages.iterator();
3878                while (it.hasNext()) {
3879                    if (it.next().isPrivileged()) {
3880                        return true;
3881                    }
3882                }
3883            } else if (obj instanceof PackageSetting) {
3884                final PackageSetting ps = (PackageSetting) obj;
3885                return ps.isPrivileged();
3886            }
3887        }
3888        return false;
3889    }
3890
3891    @Override
3892    public String[] getAppOpPermissionPackages(String permissionName) {
3893        synchronized (mPackages) {
3894            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3895            if (pkgs == null) {
3896                return null;
3897            }
3898            return pkgs.toArray(new String[pkgs.size()]);
3899        }
3900    }
3901
3902    @Override
3903    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3904            int flags, int userId) {
3905        if (!sUserManager.exists(userId)) return null;
3906        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3907        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3908        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3909    }
3910
3911    @Override
3912    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3913            IntentFilter filter, int match, ComponentName activity) {
3914        final int userId = UserHandle.getCallingUserId();
3915        if (DEBUG_PREFERRED) {
3916            Log.v(TAG, "setLastChosenActivity intent=" + intent
3917                + " resolvedType=" + resolvedType
3918                + " flags=" + flags
3919                + " filter=" + filter
3920                + " match=" + match
3921                + " activity=" + activity);
3922            filter.dump(new PrintStreamPrinter(System.out), "    ");
3923        }
3924        intent.setComponent(null);
3925        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3926        // Find any earlier preferred or last chosen entries and nuke them
3927        findPreferredActivity(intent, resolvedType,
3928                flags, query, 0, false, true, false, userId);
3929        // Add the new activity as the last chosen for this filter
3930        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3931                "Setting last chosen");
3932    }
3933
3934    @Override
3935    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3936        final int userId = UserHandle.getCallingUserId();
3937        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3938        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3939        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3940                false, false, false, userId);
3941    }
3942
3943    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3944            int flags, List<ResolveInfo> query, int userId) {
3945        if (query != null) {
3946            final int N = query.size();
3947            if (N == 1) {
3948                return query.get(0);
3949            } else if (N > 1) {
3950                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3951                // If there is more than one activity with the same priority,
3952                // then let the user decide between them.
3953                ResolveInfo r0 = query.get(0);
3954                ResolveInfo r1 = query.get(1);
3955                if (DEBUG_INTENT_MATCHING || debug) {
3956                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3957                            + r1.activityInfo.name + "=" + r1.priority);
3958                }
3959                // If the first activity has a higher priority, or a different
3960                // default, then it is always desireable to pick it.
3961                if (r0.priority != r1.priority
3962                        || r0.preferredOrder != r1.preferredOrder
3963                        || r0.isDefault != r1.isDefault) {
3964                    return query.get(0);
3965                }
3966                // If we have saved a preference for a preferred activity for
3967                // this Intent, use that.
3968                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3969                        flags, query, r0.priority, true, false, debug, userId);
3970                if (ri != null) {
3971                    return ri;
3972                }
3973                if (userId != 0) {
3974                    ri = new ResolveInfo(mResolveInfo);
3975                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3976                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3977                            ri.activityInfo.applicationInfo);
3978                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3979                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3980                    return ri;
3981                }
3982                return mResolveInfo;
3983            }
3984        }
3985        return null;
3986    }
3987
3988    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3989            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3990        final int N = query.size();
3991        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3992                .get(userId);
3993        // Get the list of persistent preferred activities that handle the intent
3994        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3995        List<PersistentPreferredActivity> pprefs = ppir != null
3996                ? ppir.queryIntent(intent, resolvedType,
3997                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3998                : null;
3999        if (pprefs != null && pprefs.size() > 0) {
4000            final int M = pprefs.size();
4001            for (int i=0; i<M; i++) {
4002                final PersistentPreferredActivity ppa = pprefs.get(i);
4003                if (DEBUG_PREFERRED || debug) {
4004                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4005                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4006                            + "\n  component=" + ppa.mComponent);
4007                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4008                }
4009                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4010                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4011                if (DEBUG_PREFERRED || debug) {
4012                    Slog.v(TAG, "Found persistent preferred activity:");
4013                    if (ai != null) {
4014                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4015                    } else {
4016                        Slog.v(TAG, "  null");
4017                    }
4018                }
4019                if (ai == null) {
4020                    // This previously registered persistent preferred activity
4021                    // component is no longer known. Ignore it and do NOT remove it.
4022                    continue;
4023                }
4024                for (int j=0; j<N; j++) {
4025                    final ResolveInfo ri = query.get(j);
4026                    if (!ri.activityInfo.applicationInfo.packageName
4027                            .equals(ai.applicationInfo.packageName)) {
4028                        continue;
4029                    }
4030                    if (!ri.activityInfo.name.equals(ai.name)) {
4031                        continue;
4032                    }
4033                    //  Found a persistent preference that can handle the intent.
4034                    if (DEBUG_PREFERRED || debug) {
4035                        Slog.v(TAG, "Returning persistent preferred activity: " +
4036                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4037                    }
4038                    return ri;
4039                }
4040            }
4041        }
4042        return null;
4043    }
4044
4045    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4046            List<ResolveInfo> query, int priority, boolean always,
4047            boolean removeMatches, boolean debug, int userId) {
4048        if (!sUserManager.exists(userId)) return null;
4049        // writer
4050        synchronized (mPackages) {
4051            if (intent.getSelector() != null) {
4052                intent = intent.getSelector();
4053            }
4054            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4055
4056            // Try to find a matching persistent preferred activity.
4057            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4058                    debug, userId);
4059
4060            // If a persistent preferred activity matched, use it.
4061            if (pri != null) {
4062                return pri;
4063            }
4064
4065            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4066            // Get the list of preferred activities that handle the intent
4067            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4068            List<PreferredActivity> prefs = pir != null
4069                    ? pir.queryIntent(intent, resolvedType,
4070                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4071                    : null;
4072            if (prefs != null && prefs.size() > 0) {
4073                boolean changed = false;
4074                try {
4075                    // First figure out how good the original match set is.
4076                    // We will only allow preferred activities that came
4077                    // from the same match quality.
4078                    int match = 0;
4079
4080                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4081
4082                    final int N = query.size();
4083                    for (int j=0; j<N; j++) {
4084                        final ResolveInfo ri = query.get(j);
4085                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4086                                + ": 0x" + Integer.toHexString(match));
4087                        if (ri.match > match) {
4088                            match = ri.match;
4089                        }
4090                    }
4091
4092                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4093                            + Integer.toHexString(match));
4094
4095                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4096                    final int M = prefs.size();
4097                    for (int i=0; i<M; i++) {
4098                        final PreferredActivity pa = prefs.get(i);
4099                        if (DEBUG_PREFERRED || debug) {
4100                            Slog.v(TAG, "Checking PreferredActivity ds="
4101                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4102                                    + "\n  component=" + pa.mPref.mComponent);
4103                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4104                        }
4105                        if (pa.mPref.mMatch != match) {
4106                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4107                                    + Integer.toHexString(pa.mPref.mMatch));
4108                            continue;
4109                        }
4110                        // If it's not an "always" type preferred activity and that's what we're
4111                        // looking for, skip it.
4112                        if (always && !pa.mPref.mAlways) {
4113                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4114                            continue;
4115                        }
4116                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4117                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4118                        if (DEBUG_PREFERRED || debug) {
4119                            Slog.v(TAG, "Found preferred activity:");
4120                            if (ai != null) {
4121                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4122                            } else {
4123                                Slog.v(TAG, "  null");
4124                            }
4125                        }
4126                        if (ai == null) {
4127                            // This previously registered preferred activity
4128                            // component is no longer known.  Most likely an update
4129                            // to the app was installed and in the new version this
4130                            // component no longer exists.  Clean it up by removing
4131                            // it from the preferred activities list, and skip it.
4132                            Slog.w(TAG, "Removing dangling preferred activity: "
4133                                    + pa.mPref.mComponent);
4134                            pir.removeFilter(pa);
4135                            changed = true;
4136                            continue;
4137                        }
4138                        for (int j=0; j<N; j++) {
4139                            final ResolveInfo ri = query.get(j);
4140                            if (!ri.activityInfo.applicationInfo.packageName
4141                                    .equals(ai.applicationInfo.packageName)) {
4142                                continue;
4143                            }
4144                            if (!ri.activityInfo.name.equals(ai.name)) {
4145                                continue;
4146                            }
4147
4148                            if (removeMatches) {
4149                                pir.removeFilter(pa);
4150                                changed = true;
4151                                if (DEBUG_PREFERRED) {
4152                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4153                                }
4154                                break;
4155                            }
4156
4157                            // Okay we found a previously set preferred or last chosen app.
4158                            // If the result set is different from when this
4159                            // was created, we need to clear it and re-ask the
4160                            // user their preference, if we're looking for an "always" type entry.
4161                            if (always && !pa.mPref.sameSet(query)) {
4162                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4163                                        + intent + " type " + resolvedType);
4164                                if (DEBUG_PREFERRED) {
4165                                    Slog.v(TAG, "Removing preferred activity since set changed "
4166                                            + pa.mPref.mComponent);
4167                                }
4168                                pir.removeFilter(pa);
4169                                // Re-add the filter as a "last chosen" entry (!always)
4170                                PreferredActivity lastChosen = new PreferredActivity(
4171                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4172                                pir.addFilter(lastChosen);
4173                                changed = true;
4174                                return null;
4175                            }
4176
4177                            // Yay! Either the set matched or we're looking for the last chosen
4178                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4179                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4180                            return ri;
4181                        }
4182                    }
4183                } finally {
4184                    if (changed) {
4185                        if (DEBUG_PREFERRED) {
4186                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4187                        }
4188                        scheduleWritePackageRestrictionsLocked(userId);
4189                    }
4190                }
4191            }
4192        }
4193        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4194        return null;
4195    }
4196
4197    /*
4198     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4199     */
4200    @Override
4201    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4202            int targetUserId) {
4203        mContext.enforceCallingOrSelfPermission(
4204                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4205        List<CrossProfileIntentFilter> matches =
4206                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4207        if (matches != null) {
4208            int size = matches.size();
4209            for (int i = 0; i < size; i++) {
4210                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4211            }
4212        }
4213        if (hasWebURI(intent)) {
4214            // cross-profile app linking works only towards the parent.
4215            final UserInfo parent = getProfileParent(sourceUserId);
4216            synchronized(mPackages) {
4217                return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId,
4218                        parent.id) != null;
4219            }
4220        }
4221        return false;
4222    }
4223
4224    private UserInfo getProfileParent(int userId) {
4225        final long identity = Binder.clearCallingIdentity();
4226        try {
4227            return sUserManager.getProfileParent(userId);
4228        } finally {
4229            Binder.restoreCallingIdentity(identity);
4230        }
4231    }
4232
4233    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4234            String resolvedType, int userId) {
4235        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4236        if (resolver != null) {
4237            return resolver.queryIntent(intent, resolvedType, false, userId);
4238        }
4239        return null;
4240    }
4241
4242    @Override
4243    public List<ResolveInfo> queryIntentActivities(Intent intent,
4244            String resolvedType, int flags, int userId) {
4245        if (!sUserManager.exists(userId)) return Collections.emptyList();
4246        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4247        ComponentName comp = intent.getComponent();
4248        if (comp == null) {
4249            if (intent.getSelector() != null) {
4250                intent = intent.getSelector();
4251                comp = intent.getComponent();
4252            }
4253        }
4254
4255        if (comp != null) {
4256            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4257            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4258            if (ai != null) {
4259                final ResolveInfo ri = new ResolveInfo();
4260                ri.activityInfo = ai;
4261                list.add(ri);
4262            }
4263            return list;
4264        }
4265
4266        // reader
4267        synchronized (mPackages) {
4268            final String pkgName = intent.getPackage();
4269            if (pkgName == null) {
4270                List<CrossProfileIntentFilter> matchingFilters =
4271                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4272                // Check for results that need to skip the current profile.
4273                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4274                        resolvedType, flags, userId);
4275                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4276                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4277                    result.add(xpResolveInfo);
4278                    return filterIfNotPrimaryUser(result, userId);
4279                }
4280
4281                // Check for results in the current profile.
4282                List<ResolveInfo> result = mActivities.queryIntent(
4283                        intent, resolvedType, flags, userId);
4284
4285                // Check for cross profile results.
4286                xpResolveInfo = queryCrossProfileIntents(
4287                        matchingFilters, intent, resolvedType, flags, userId);
4288                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4289                    result.add(xpResolveInfo);
4290                    Collections.sort(result, mResolvePrioritySorter);
4291                }
4292                result = filterIfNotPrimaryUser(result, userId);
4293                if (hasWebURI(intent)) {
4294                    CrossProfileDomainInfo xpDomainInfo = null;
4295                    final UserInfo parent = getProfileParent(userId);
4296                    if (parent != null) {
4297                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4298                                flags, userId, parent.id);
4299                    }
4300                    if (xpDomainInfo != null) {
4301                        if (xpResolveInfo != null) {
4302                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4303                            // in the result.
4304                            result.remove(xpResolveInfo);
4305                        }
4306                        if (result.size() == 0) {
4307                            result.add(xpDomainInfo.resolveInfo);
4308                            return result;
4309                        }
4310                    } else if (result.size() <= 1) {
4311                        return result;
4312                    }
4313                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4314                            xpDomainInfo);
4315                    Collections.sort(result, mResolvePrioritySorter);
4316                }
4317                return result;
4318            }
4319            final PackageParser.Package pkg = mPackages.get(pkgName);
4320            if (pkg != null) {
4321                return filterIfNotPrimaryUser(
4322                        mActivities.queryIntentForPackage(
4323                                intent, resolvedType, flags, pkg.activities, userId),
4324                        userId);
4325            }
4326            return new ArrayList<ResolveInfo>();
4327        }
4328    }
4329
4330    private static class CrossProfileDomainInfo {
4331        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4332        ResolveInfo resolveInfo;
4333        /* Best domain verification status of the activities found in the other profile */
4334        int bestDomainVerificationStatus;
4335    }
4336
4337    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4338            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4339        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_APP_LINKING,
4340                sourceUserId)) {
4341            return null;
4342        }
4343        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4344                resolvedType, flags, parentUserId);
4345
4346        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4347            return null;
4348        }
4349        CrossProfileDomainInfo result = null;
4350        int size = resultTargetUser.size();
4351        for (int i = 0; i < size; i++) {
4352            ResolveInfo riTargetUser = resultTargetUser.get(i);
4353            // Intent filter verification is only for filters that specify a host. So don't return
4354            // those that handle all web uris.
4355            if (riTargetUser.handleAllWebDataURI) {
4356                continue;
4357            }
4358            String packageName = riTargetUser.activityInfo.packageName;
4359            PackageSetting ps = mSettings.mPackages.get(packageName);
4360            if (ps == null) {
4361                continue;
4362            }
4363            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4364            if (result == null) {
4365                result = new CrossProfileDomainInfo();
4366                result.resolveInfo =
4367                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4368                result.bestDomainVerificationStatus = status;
4369            } else {
4370                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4371                        result.bestDomainVerificationStatus);
4372            }
4373        }
4374        return result;
4375    }
4376
4377    /**
4378     * Verification statuses are ordered from the worse to the best, except for
4379     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4380     */
4381    private int bestDomainVerificationStatus(int status1, int status2) {
4382        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4383            return status2;
4384        }
4385        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4386            return status1;
4387        }
4388        return (int) MathUtils.max(status1, status2);
4389    }
4390
4391    private boolean isUserEnabled(int userId) {
4392        long callingId = Binder.clearCallingIdentity();
4393        try {
4394            UserInfo userInfo = sUserManager.getUserInfo(userId);
4395            return userInfo != null && userInfo.isEnabled();
4396        } finally {
4397            Binder.restoreCallingIdentity(callingId);
4398        }
4399    }
4400
4401    /**
4402     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4403     *
4404     * @return filtered list
4405     */
4406    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4407        if (userId == UserHandle.USER_OWNER) {
4408            return resolveInfos;
4409        }
4410        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4411            ResolveInfo info = resolveInfos.get(i);
4412            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4413                resolveInfos.remove(i);
4414            }
4415        }
4416        return resolveInfos;
4417    }
4418
4419    private static boolean hasWebURI(Intent intent) {
4420        if (intent.getData() == null) {
4421            return false;
4422        }
4423        final String scheme = intent.getScheme();
4424        if (TextUtils.isEmpty(scheme)) {
4425            return false;
4426        }
4427        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4428    }
4429
4430    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4431            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4432        if (DEBUG_PREFERRED) {
4433            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4434                    candidates.size());
4435        }
4436
4437        final int userId = UserHandle.getCallingUserId();
4438        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4439        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4440        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4441        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4442        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4443
4444        synchronized (mPackages) {
4445            final int count = candidates.size();
4446            // First, try to use the domain prefered App. Partition the candidates into four lists:
4447            // one for the final results, one for the "do not use ever", one for "undefined status"
4448            // and finally one for "Browser App type".
4449            for (int n=0; n<count; n++) {
4450                ResolveInfo info = candidates.get(n);
4451                String packageName = info.activityInfo.packageName;
4452                PackageSetting ps = mSettings.mPackages.get(packageName);
4453                if (ps != null) {
4454                    // Add to the special match all list (Browser use case)
4455                    if (info.handleAllWebDataURI) {
4456                        matchAllList.add(info);
4457                        continue;
4458                    }
4459                    // Try to get the status from User settings first
4460                    int status = getDomainVerificationStatusLPr(ps, userId);
4461                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4462                        alwaysList.add(info);
4463                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4464                        neverList.add(info);
4465                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4466                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4467                        undefinedList.add(info);
4468                    }
4469                }
4470            }
4471            // First try to add the "always" resolution for the current user if there is any
4472            if (alwaysList.size() > 0) {
4473                result.addAll(alwaysList);
4474            // if there is an "always" for the parent user, add it.
4475            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4476                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4477                result.add(xpDomainInfo.resolveInfo);
4478            } else {
4479                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4480                result.addAll(undefinedList);
4481                if (xpDomainInfo != null && (
4482                        xpDomainInfo.bestDomainVerificationStatus
4483                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4484                        || xpDomainInfo.bestDomainVerificationStatus
4485                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4486                    result.add(xpDomainInfo.resolveInfo);
4487                }
4488                // Also add Browsers (all of them or only the default one)
4489                if ((flags & MATCH_ALL) != 0) {
4490                    result.addAll(matchAllList);
4491                } else {
4492                    // Try to add the Default Browser if we can
4493                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4494                            UserHandle.myUserId());
4495                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4496                        boolean defaultBrowserFound = false;
4497                        final int browserCount = matchAllList.size();
4498                        for (int n=0; n<browserCount; n++) {
4499                            ResolveInfo browser = matchAllList.get(n);
4500                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4501                                result.add(browser);
4502                                defaultBrowserFound = true;
4503                                break;
4504                            }
4505                        }
4506                        if (!defaultBrowserFound) {
4507                            result.addAll(matchAllList);
4508                        }
4509                    } else {
4510                        result.addAll(matchAllList);
4511                    }
4512                }
4513
4514                // If there is nothing selected, add all candidates and remove the ones that the User
4515                // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4516                if (result.size() == 0) {
4517                    result.addAll(candidates);
4518                    result.removeAll(neverList);
4519                }
4520            }
4521        }
4522        if (DEBUG_PREFERRED) {
4523            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4524                    result.size());
4525        }
4526        return result;
4527    }
4528
4529    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4530        int status = ps.getDomainVerificationStatusForUser(userId);
4531        // if none available, get the master status
4532        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4533            if (ps.getIntentFilterVerificationInfo() != null) {
4534                status = ps.getIntentFilterVerificationInfo().getStatus();
4535            }
4536        }
4537        return status;
4538    }
4539
4540    private ResolveInfo querySkipCurrentProfileIntents(
4541            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4542            int flags, int sourceUserId) {
4543        if (matchingFilters != null) {
4544            int size = matchingFilters.size();
4545            for (int i = 0; i < size; i ++) {
4546                CrossProfileIntentFilter filter = matchingFilters.get(i);
4547                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4548                    // Checking if there are activities in the target user that can handle the
4549                    // intent.
4550                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4551                            flags, sourceUserId);
4552                    if (resolveInfo != null) {
4553                        return resolveInfo;
4554                    }
4555                }
4556            }
4557        }
4558        return null;
4559    }
4560
4561    // Return matching ResolveInfo if any for skip current profile intent filters.
4562    private ResolveInfo queryCrossProfileIntents(
4563            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4564            int flags, int sourceUserId) {
4565        if (matchingFilters != null) {
4566            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4567            // match the same intent. For performance reasons, it is better not to
4568            // run queryIntent twice for the same userId
4569            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4570            int size = matchingFilters.size();
4571            for (int i = 0; i < size; i++) {
4572                CrossProfileIntentFilter filter = matchingFilters.get(i);
4573                int targetUserId = filter.getTargetUserId();
4574                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4575                        && !alreadyTriedUserIds.get(targetUserId)) {
4576                    // Checking if there are activities in the target user that can handle the
4577                    // intent.
4578                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4579                            flags, sourceUserId);
4580                    if (resolveInfo != null) return resolveInfo;
4581                    alreadyTriedUserIds.put(targetUserId, true);
4582                }
4583            }
4584        }
4585        return null;
4586    }
4587
4588    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4589            String resolvedType, int flags, int sourceUserId) {
4590        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4591                resolvedType, flags, filter.getTargetUserId());
4592        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4593            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4594        }
4595        return null;
4596    }
4597
4598    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4599            int sourceUserId, int targetUserId) {
4600        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4601        String className;
4602        if (targetUserId == UserHandle.USER_OWNER) {
4603            className = FORWARD_INTENT_TO_USER_OWNER;
4604        } else {
4605            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4606        }
4607        ComponentName forwardingActivityComponentName = new ComponentName(
4608                mAndroidApplication.packageName, className);
4609        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4610                sourceUserId);
4611        if (targetUserId == UserHandle.USER_OWNER) {
4612            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4613            forwardingResolveInfo.noResourceId = true;
4614        }
4615        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4616        forwardingResolveInfo.priority = 0;
4617        forwardingResolveInfo.preferredOrder = 0;
4618        forwardingResolveInfo.match = 0;
4619        forwardingResolveInfo.isDefault = true;
4620        forwardingResolveInfo.filter = filter;
4621        forwardingResolveInfo.targetUserId = targetUserId;
4622        return forwardingResolveInfo;
4623    }
4624
4625    @Override
4626    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4627            Intent[] specifics, String[] specificTypes, Intent intent,
4628            String resolvedType, int flags, int userId) {
4629        if (!sUserManager.exists(userId)) return Collections.emptyList();
4630        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4631                false, "query intent activity options");
4632        final String resultsAction = intent.getAction();
4633
4634        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4635                | PackageManager.GET_RESOLVED_FILTER, userId);
4636
4637        if (DEBUG_INTENT_MATCHING) {
4638            Log.v(TAG, "Query " + intent + ": " + results);
4639        }
4640
4641        int specificsPos = 0;
4642        int N;
4643
4644        // todo: note that the algorithm used here is O(N^2).  This
4645        // isn't a problem in our current environment, but if we start running
4646        // into situations where we have more than 5 or 10 matches then this
4647        // should probably be changed to something smarter...
4648
4649        // First we go through and resolve each of the specific items
4650        // that were supplied, taking care of removing any corresponding
4651        // duplicate items in the generic resolve list.
4652        if (specifics != null) {
4653            for (int i=0; i<specifics.length; i++) {
4654                final Intent sintent = specifics[i];
4655                if (sintent == null) {
4656                    continue;
4657                }
4658
4659                if (DEBUG_INTENT_MATCHING) {
4660                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4661                }
4662
4663                String action = sintent.getAction();
4664                if (resultsAction != null && resultsAction.equals(action)) {
4665                    // If this action was explicitly requested, then don't
4666                    // remove things that have it.
4667                    action = null;
4668                }
4669
4670                ResolveInfo ri = null;
4671                ActivityInfo ai = null;
4672
4673                ComponentName comp = sintent.getComponent();
4674                if (comp == null) {
4675                    ri = resolveIntent(
4676                        sintent,
4677                        specificTypes != null ? specificTypes[i] : null,
4678                            flags, userId);
4679                    if (ri == null) {
4680                        continue;
4681                    }
4682                    if (ri == mResolveInfo) {
4683                        // ACK!  Must do something better with this.
4684                    }
4685                    ai = ri.activityInfo;
4686                    comp = new ComponentName(ai.applicationInfo.packageName,
4687                            ai.name);
4688                } else {
4689                    ai = getActivityInfo(comp, flags, userId);
4690                    if (ai == null) {
4691                        continue;
4692                    }
4693                }
4694
4695                // Look for any generic query activities that are duplicates
4696                // of this specific one, and remove them from the results.
4697                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4698                N = results.size();
4699                int j;
4700                for (j=specificsPos; j<N; j++) {
4701                    ResolveInfo sri = results.get(j);
4702                    if ((sri.activityInfo.name.equals(comp.getClassName())
4703                            && sri.activityInfo.applicationInfo.packageName.equals(
4704                                    comp.getPackageName()))
4705                        || (action != null && sri.filter.matchAction(action))) {
4706                        results.remove(j);
4707                        if (DEBUG_INTENT_MATCHING) Log.v(
4708                            TAG, "Removing duplicate item from " + j
4709                            + " due to specific " + specificsPos);
4710                        if (ri == null) {
4711                            ri = sri;
4712                        }
4713                        j--;
4714                        N--;
4715                    }
4716                }
4717
4718                // Add this specific item to its proper place.
4719                if (ri == null) {
4720                    ri = new ResolveInfo();
4721                    ri.activityInfo = ai;
4722                }
4723                results.add(specificsPos, ri);
4724                ri.specificIndex = i;
4725                specificsPos++;
4726            }
4727        }
4728
4729        // Now we go through the remaining generic results and remove any
4730        // duplicate actions that are found here.
4731        N = results.size();
4732        for (int i=specificsPos; i<N-1; i++) {
4733            final ResolveInfo rii = results.get(i);
4734            if (rii.filter == null) {
4735                continue;
4736            }
4737
4738            // Iterate over all of the actions of this result's intent
4739            // filter...  typically this should be just one.
4740            final Iterator<String> it = rii.filter.actionsIterator();
4741            if (it == null) {
4742                continue;
4743            }
4744            while (it.hasNext()) {
4745                final String action = it.next();
4746                if (resultsAction != null && resultsAction.equals(action)) {
4747                    // If this action was explicitly requested, then don't
4748                    // remove things that have it.
4749                    continue;
4750                }
4751                for (int j=i+1; j<N; j++) {
4752                    final ResolveInfo rij = results.get(j);
4753                    if (rij.filter != null && rij.filter.hasAction(action)) {
4754                        results.remove(j);
4755                        if (DEBUG_INTENT_MATCHING) Log.v(
4756                            TAG, "Removing duplicate item from " + j
4757                            + " due to action " + action + " at " + i);
4758                        j--;
4759                        N--;
4760                    }
4761                }
4762            }
4763
4764            // If the caller didn't request filter information, drop it now
4765            // so we don't have to marshall/unmarshall it.
4766            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4767                rii.filter = null;
4768            }
4769        }
4770
4771        // Filter out the caller activity if so requested.
4772        if (caller != null) {
4773            N = results.size();
4774            for (int i=0; i<N; i++) {
4775                ActivityInfo ainfo = results.get(i).activityInfo;
4776                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4777                        && caller.getClassName().equals(ainfo.name)) {
4778                    results.remove(i);
4779                    break;
4780                }
4781            }
4782        }
4783
4784        // If the caller didn't request filter information,
4785        // drop them now so we don't have to
4786        // marshall/unmarshall it.
4787        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4788            N = results.size();
4789            for (int i=0; i<N; i++) {
4790                results.get(i).filter = null;
4791            }
4792        }
4793
4794        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4795        return results;
4796    }
4797
4798    @Override
4799    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4800            int userId) {
4801        if (!sUserManager.exists(userId)) return Collections.emptyList();
4802        ComponentName comp = intent.getComponent();
4803        if (comp == null) {
4804            if (intent.getSelector() != null) {
4805                intent = intent.getSelector();
4806                comp = intent.getComponent();
4807            }
4808        }
4809        if (comp != null) {
4810            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4811            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4812            if (ai != null) {
4813                ResolveInfo ri = new ResolveInfo();
4814                ri.activityInfo = ai;
4815                list.add(ri);
4816            }
4817            return list;
4818        }
4819
4820        // reader
4821        synchronized (mPackages) {
4822            String pkgName = intent.getPackage();
4823            if (pkgName == null) {
4824                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4825            }
4826            final PackageParser.Package pkg = mPackages.get(pkgName);
4827            if (pkg != null) {
4828                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4829                        userId);
4830            }
4831            return null;
4832        }
4833    }
4834
4835    @Override
4836    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4837        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4838        if (!sUserManager.exists(userId)) return null;
4839        if (query != null) {
4840            if (query.size() >= 1) {
4841                // If there is more than one service with the same priority,
4842                // just arbitrarily pick the first one.
4843                return query.get(0);
4844            }
4845        }
4846        return null;
4847    }
4848
4849    @Override
4850    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4851            int userId) {
4852        if (!sUserManager.exists(userId)) return Collections.emptyList();
4853        ComponentName comp = intent.getComponent();
4854        if (comp == null) {
4855            if (intent.getSelector() != null) {
4856                intent = intent.getSelector();
4857                comp = intent.getComponent();
4858            }
4859        }
4860        if (comp != null) {
4861            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4862            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4863            if (si != null) {
4864                final ResolveInfo ri = new ResolveInfo();
4865                ri.serviceInfo = si;
4866                list.add(ri);
4867            }
4868            return list;
4869        }
4870
4871        // reader
4872        synchronized (mPackages) {
4873            String pkgName = intent.getPackage();
4874            if (pkgName == null) {
4875                return mServices.queryIntent(intent, resolvedType, flags, userId);
4876            }
4877            final PackageParser.Package pkg = mPackages.get(pkgName);
4878            if (pkg != null) {
4879                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4880                        userId);
4881            }
4882            return null;
4883        }
4884    }
4885
4886    @Override
4887    public List<ResolveInfo> queryIntentContentProviders(
4888            Intent intent, String resolvedType, int flags, int userId) {
4889        if (!sUserManager.exists(userId)) return Collections.emptyList();
4890        ComponentName comp = intent.getComponent();
4891        if (comp == null) {
4892            if (intent.getSelector() != null) {
4893                intent = intent.getSelector();
4894                comp = intent.getComponent();
4895            }
4896        }
4897        if (comp != null) {
4898            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4899            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4900            if (pi != null) {
4901                final ResolveInfo ri = new ResolveInfo();
4902                ri.providerInfo = pi;
4903                list.add(ri);
4904            }
4905            return list;
4906        }
4907
4908        // reader
4909        synchronized (mPackages) {
4910            String pkgName = intent.getPackage();
4911            if (pkgName == null) {
4912                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4913            }
4914            final PackageParser.Package pkg = mPackages.get(pkgName);
4915            if (pkg != null) {
4916                return mProviders.queryIntentForPackage(
4917                        intent, resolvedType, flags, pkg.providers, userId);
4918            }
4919            return null;
4920        }
4921    }
4922
4923    @Override
4924    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4925        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4926
4927        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4928
4929        // writer
4930        synchronized (mPackages) {
4931            ArrayList<PackageInfo> list;
4932            if (listUninstalled) {
4933                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4934                for (PackageSetting ps : mSettings.mPackages.values()) {
4935                    PackageInfo pi;
4936                    if (ps.pkg != null) {
4937                        pi = generatePackageInfo(ps.pkg, flags, userId);
4938                    } else {
4939                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4940                    }
4941                    if (pi != null) {
4942                        list.add(pi);
4943                    }
4944                }
4945            } else {
4946                list = new ArrayList<PackageInfo>(mPackages.size());
4947                for (PackageParser.Package p : mPackages.values()) {
4948                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4949                    if (pi != null) {
4950                        list.add(pi);
4951                    }
4952                }
4953            }
4954
4955            return new ParceledListSlice<PackageInfo>(list);
4956        }
4957    }
4958
4959    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4960            String[] permissions, boolean[] tmp, int flags, int userId) {
4961        int numMatch = 0;
4962        final PermissionsState permissionsState = ps.getPermissionsState();
4963        for (int i=0; i<permissions.length; i++) {
4964            final String permission = permissions[i];
4965            if (permissionsState.hasPermission(permission, userId)) {
4966                tmp[i] = true;
4967                numMatch++;
4968            } else {
4969                tmp[i] = false;
4970            }
4971        }
4972        if (numMatch == 0) {
4973            return;
4974        }
4975        PackageInfo pi;
4976        if (ps.pkg != null) {
4977            pi = generatePackageInfo(ps.pkg, flags, userId);
4978        } else {
4979            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4980        }
4981        // The above might return null in cases of uninstalled apps or install-state
4982        // skew across users/profiles.
4983        if (pi != null) {
4984            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4985                if (numMatch == permissions.length) {
4986                    pi.requestedPermissions = permissions;
4987                } else {
4988                    pi.requestedPermissions = new String[numMatch];
4989                    numMatch = 0;
4990                    for (int i=0; i<permissions.length; i++) {
4991                        if (tmp[i]) {
4992                            pi.requestedPermissions[numMatch] = permissions[i];
4993                            numMatch++;
4994                        }
4995                    }
4996                }
4997            }
4998            list.add(pi);
4999        }
5000    }
5001
5002    @Override
5003    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5004            String[] permissions, int flags, int userId) {
5005        if (!sUserManager.exists(userId)) return null;
5006        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5007
5008        // writer
5009        synchronized (mPackages) {
5010            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5011            boolean[] tmpBools = new boolean[permissions.length];
5012            if (listUninstalled) {
5013                for (PackageSetting ps : mSettings.mPackages.values()) {
5014                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5015                }
5016            } else {
5017                for (PackageParser.Package pkg : mPackages.values()) {
5018                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5019                    if (ps != null) {
5020                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5021                                userId);
5022                    }
5023                }
5024            }
5025
5026            return new ParceledListSlice<PackageInfo>(list);
5027        }
5028    }
5029
5030    @Override
5031    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5032        if (!sUserManager.exists(userId)) return null;
5033        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5034
5035        // writer
5036        synchronized (mPackages) {
5037            ArrayList<ApplicationInfo> list;
5038            if (listUninstalled) {
5039                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5040                for (PackageSetting ps : mSettings.mPackages.values()) {
5041                    ApplicationInfo ai;
5042                    if (ps.pkg != null) {
5043                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5044                                ps.readUserState(userId), userId);
5045                    } else {
5046                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5047                    }
5048                    if (ai != null) {
5049                        list.add(ai);
5050                    }
5051                }
5052            } else {
5053                list = new ArrayList<ApplicationInfo>(mPackages.size());
5054                for (PackageParser.Package p : mPackages.values()) {
5055                    if (p.mExtras != null) {
5056                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5057                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5058                        if (ai != null) {
5059                            list.add(ai);
5060                        }
5061                    }
5062                }
5063            }
5064
5065            return new ParceledListSlice<ApplicationInfo>(list);
5066        }
5067    }
5068
5069    public List<ApplicationInfo> getPersistentApplications(int flags) {
5070        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5071
5072        // reader
5073        synchronized (mPackages) {
5074            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5075            final int userId = UserHandle.getCallingUserId();
5076            while (i.hasNext()) {
5077                final PackageParser.Package p = i.next();
5078                if (p.applicationInfo != null
5079                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5080                        && (!mSafeMode || isSystemApp(p))) {
5081                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5082                    if (ps != null) {
5083                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5084                                ps.readUserState(userId), userId);
5085                        if (ai != null) {
5086                            finalList.add(ai);
5087                        }
5088                    }
5089                }
5090            }
5091        }
5092
5093        return finalList;
5094    }
5095
5096    @Override
5097    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5098        if (!sUserManager.exists(userId)) return null;
5099        // reader
5100        synchronized (mPackages) {
5101            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5102            PackageSetting ps = provider != null
5103                    ? mSettings.mPackages.get(provider.owner.packageName)
5104                    : null;
5105            return ps != null
5106                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5107                    && (!mSafeMode || (provider.info.applicationInfo.flags
5108                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5109                    ? PackageParser.generateProviderInfo(provider, flags,
5110                            ps.readUserState(userId), userId)
5111                    : null;
5112        }
5113    }
5114
5115    /**
5116     * @deprecated
5117     */
5118    @Deprecated
5119    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5120        // reader
5121        synchronized (mPackages) {
5122            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5123                    .entrySet().iterator();
5124            final int userId = UserHandle.getCallingUserId();
5125            while (i.hasNext()) {
5126                Map.Entry<String, PackageParser.Provider> entry = i.next();
5127                PackageParser.Provider p = entry.getValue();
5128                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5129
5130                if (ps != null && p.syncable
5131                        && (!mSafeMode || (p.info.applicationInfo.flags
5132                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5133                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5134                            ps.readUserState(userId), userId);
5135                    if (info != null) {
5136                        outNames.add(entry.getKey());
5137                        outInfo.add(info);
5138                    }
5139                }
5140            }
5141        }
5142    }
5143
5144    @Override
5145    public List<ProviderInfo> queryContentProviders(String processName,
5146            int uid, int flags) {
5147        ArrayList<ProviderInfo> finalList = null;
5148        // reader
5149        synchronized (mPackages) {
5150            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5151            final int userId = processName != null ?
5152                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5153            while (i.hasNext()) {
5154                final PackageParser.Provider p = i.next();
5155                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5156                if (ps != null && p.info.authority != null
5157                        && (processName == null
5158                                || (p.info.processName.equals(processName)
5159                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5160                        && mSettings.isEnabledLPr(p.info, flags, userId)
5161                        && (!mSafeMode
5162                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5163                    if (finalList == null) {
5164                        finalList = new ArrayList<ProviderInfo>(3);
5165                    }
5166                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5167                            ps.readUserState(userId), userId);
5168                    if (info != null) {
5169                        finalList.add(info);
5170                    }
5171                }
5172            }
5173        }
5174
5175        if (finalList != null) {
5176            Collections.sort(finalList, mProviderInitOrderSorter);
5177        }
5178
5179        return finalList;
5180    }
5181
5182    @Override
5183    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5184            int flags) {
5185        // reader
5186        synchronized (mPackages) {
5187            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5188            return PackageParser.generateInstrumentationInfo(i, flags);
5189        }
5190    }
5191
5192    @Override
5193    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5194            int flags) {
5195        ArrayList<InstrumentationInfo> finalList =
5196            new ArrayList<InstrumentationInfo>();
5197
5198        // reader
5199        synchronized (mPackages) {
5200            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5201            while (i.hasNext()) {
5202                final PackageParser.Instrumentation p = i.next();
5203                if (targetPackage == null
5204                        || targetPackage.equals(p.info.targetPackage)) {
5205                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5206                            flags);
5207                    if (ii != null) {
5208                        finalList.add(ii);
5209                    }
5210                }
5211            }
5212        }
5213
5214        return finalList;
5215    }
5216
5217    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5218        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5219        if (overlays == null) {
5220            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5221            return;
5222        }
5223        for (PackageParser.Package opkg : overlays.values()) {
5224            // Not much to do if idmap fails: we already logged the error
5225            // and we certainly don't want to abort installation of pkg simply
5226            // because an overlay didn't fit properly. For these reasons,
5227            // ignore the return value of createIdmapForPackagePairLI.
5228            createIdmapForPackagePairLI(pkg, opkg);
5229        }
5230    }
5231
5232    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5233            PackageParser.Package opkg) {
5234        if (!opkg.mTrustedOverlay) {
5235            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5236                    opkg.baseCodePath + ": overlay not trusted");
5237            return false;
5238        }
5239        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5240        if (overlaySet == null) {
5241            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5242                    opkg.baseCodePath + " but target package has no known overlays");
5243            return false;
5244        }
5245        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5246        // TODO: generate idmap for split APKs
5247        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5248            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5249                    + opkg.baseCodePath);
5250            return false;
5251        }
5252        PackageParser.Package[] overlayArray =
5253            overlaySet.values().toArray(new PackageParser.Package[0]);
5254        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5255            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5256                return p1.mOverlayPriority - p2.mOverlayPriority;
5257            }
5258        };
5259        Arrays.sort(overlayArray, cmp);
5260
5261        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5262        int i = 0;
5263        for (PackageParser.Package p : overlayArray) {
5264            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5265        }
5266        return true;
5267    }
5268
5269    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5270        final File[] files = dir.listFiles();
5271        if (ArrayUtils.isEmpty(files)) {
5272            Log.d(TAG, "No files in app dir " + dir);
5273            return;
5274        }
5275
5276        if (DEBUG_PACKAGE_SCANNING) {
5277            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5278                    + " flags=0x" + Integer.toHexString(parseFlags));
5279        }
5280
5281        for (File file : files) {
5282            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5283                    && !PackageInstallerService.isStageName(file.getName());
5284            if (!isPackage) {
5285                // Ignore entries which are not packages
5286                continue;
5287            }
5288            try {
5289                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5290                        scanFlags, currentTime, null);
5291            } catch (PackageManagerException e) {
5292                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5293
5294                // Delete invalid userdata apps
5295                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5296                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5297                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5298                    if (file.isDirectory()) {
5299                        mInstaller.rmPackageDir(file.getAbsolutePath());
5300                    } else {
5301                        file.delete();
5302                    }
5303                }
5304            }
5305        }
5306    }
5307
5308    private static File getSettingsProblemFile() {
5309        File dataDir = Environment.getDataDirectory();
5310        File systemDir = new File(dataDir, "system");
5311        File fname = new File(systemDir, "uiderrors.txt");
5312        return fname;
5313    }
5314
5315    static void reportSettingsProblem(int priority, String msg) {
5316        logCriticalInfo(priority, msg);
5317    }
5318
5319    static void logCriticalInfo(int priority, String msg) {
5320        Slog.println(priority, TAG, msg);
5321        EventLogTags.writePmCriticalInfo(msg);
5322        try {
5323            File fname = getSettingsProblemFile();
5324            FileOutputStream out = new FileOutputStream(fname, true);
5325            PrintWriter pw = new FastPrintWriter(out);
5326            SimpleDateFormat formatter = new SimpleDateFormat();
5327            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5328            pw.println(dateString + ": " + msg);
5329            pw.close();
5330            FileUtils.setPermissions(
5331                    fname.toString(),
5332                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5333                    -1, -1);
5334        } catch (java.io.IOException e) {
5335        }
5336    }
5337
5338    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5339            PackageParser.Package pkg, File srcFile, int parseFlags)
5340            throws PackageManagerException {
5341        if (ps != null
5342                && ps.codePath.equals(srcFile)
5343                && ps.timeStamp == srcFile.lastModified()
5344                && !isCompatSignatureUpdateNeeded(pkg)
5345                && !isRecoverSignatureUpdateNeeded(pkg)) {
5346            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5347            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5348            ArraySet<PublicKey> signingKs;
5349            synchronized (mPackages) {
5350                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5351            }
5352            if (ps.signatures.mSignatures != null
5353                    && ps.signatures.mSignatures.length != 0
5354                    && signingKs != null) {
5355                // Optimization: reuse the existing cached certificates
5356                // if the package appears to be unchanged.
5357                pkg.mSignatures = ps.signatures.mSignatures;
5358                pkg.mSigningKeys = signingKs;
5359                return;
5360            }
5361
5362            Slog.w(TAG, "PackageSetting for " + ps.name
5363                    + " is missing signatures.  Collecting certs again to recover them.");
5364        } else {
5365            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5366        }
5367
5368        try {
5369            pp.collectCertificates(pkg, parseFlags);
5370            pp.collectManifestDigest(pkg);
5371        } catch (PackageParserException e) {
5372            throw PackageManagerException.from(e);
5373        }
5374    }
5375
5376    /*
5377     *  Scan a package and return the newly parsed package.
5378     *  Returns null in case of errors and the error code is stored in mLastScanError
5379     */
5380    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5381            long currentTime, UserHandle user) throws PackageManagerException {
5382        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5383        parseFlags |= mDefParseFlags;
5384        PackageParser pp = new PackageParser();
5385        pp.setSeparateProcesses(mSeparateProcesses);
5386        pp.setOnlyCoreApps(mOnlyCore);
5387        pp.setDisplayMetrics(mMetrics);
5388
5389        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5390            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5391        }
5392
5393        final PackageParser.Package pkg;
5394        try {
5395            pkg = pp.parsePackage(scanFile, parseFlags);
5396        } catch (PackageParserException e) {
5397            throw PackageManagerException.from(e);
5398        }
5399
5400        PackageSetting ps = null;
5401        PackageSetting updatedPkg;
5402        // reader
5403        synchronized (mPackages) {
5404            // Look to see if we already know about this package.
5405            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5406            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5407                // This package has been renamed to its original name.  Let's
5408                // use that.
5409                ps = mSettings.peekPackageLPr(oldName);
5410            }
5411            // If there was no original package, see one for the real package name.
5412            if (ps == null) {
5413                ps = mSettings.peekPackageLPr(pkg.packageName);
5414            }
5415            // Check to see if this package could be hiding/updating a system
5416            // package.  Must look for it either under the original or real
5417            // package name depending on our state.
5418            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5419            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5420        }
5421        boolean updatedPkgBetter = false;
5422        // First check if this is a system package that may involve an update
5423        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5424            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5425            // it needs to drop FLAG_PRIVILEGED.
5426            if (locationIsPrivileged(scanFile)) {
5427                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5428            } else {
5429                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5430            }
5431
5432            if (ps != null && !ps.codePath.equals(scanFile)) {
5433                // The path has changed from what was last scanned...  check the
5434                // version of the new path against what we have stored to determine
5435                // what to do.
5436                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5437                if (pkg.mVersionCode <= ps.versionCode) {
5438                    // The system package has been updated and the code path does not match
5439                    // Ignore entry. Skip it.
5440                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5441                            + " ignored: updated version " + ps.versionCode
5442                            + " better than this " + pkg.mVersionCode);
5443                    if (!updatedPkg.codePath.equals(scanFile)) {
5444                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5445                                + ps.name + " changing from " + updatedPkg.codePathString
5446                                + " to " + scanFile);
5447                        updatedPkg.codePath = scanFile;
5448                        updatedPkg.codePathString = scanFile.toString();
5449                        updatedPkg.resourcePath = scanFile;
5450                        updatedPkg.resourcePathString = scanFile.toString();
5451                    }
5452                    updatedPkg.pkg = pkg;
5453                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5454                } else {
5455                    // The current app on the system partition is better than
5456                    // what we have updated to on the data partition; switch
5457                    // back to the system partition version.
5458                    // At this point, its safely assumed that package installation for
5459                    // apps in system partition will go through. If not there won't be a working
5460                    // version of the app
5461                    // writer
5462                    synchronized (mPackages) {
5463                        // Just remove the loaded entries from package lists.
5464                        mPackages.remove(ps.name);
5465                    }
5466
5467                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5468                            + " reverting from " + ps.codePathString
5469                            + ": new version " + pkg.mVersionCode
5470                            + " better than installed " + ps.versionCode);
5471
5472                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5473                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5474                    synchronized (mInstallLock) {
5475                        args.cleanUpResourcesLI();
5476                    }
5477                    synchronized (mPackages) {
5478                        mSettings.enableSystemPackageLPw(ps.name);
5479                    }
5480                    updatedPkgBetter = true;
5481                }
5482            }
5483        }
5484
5485        if (updatedPkg != null) {
5486            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5487            // initially
5488            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5489
5490            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5491            // flag set initially
5492            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5493                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5494            }
5495        }
5496
5497        // Verify certificates against what was last scanned
5498        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5499
5500        /*
5501         * A new system app appeared, but we already had a non-system one of the
5502         * same name installed earlier.
5503         */
5504        boolean shouldHideSystemApp = false;
5505        if (updatedPkg == null && ps != null
5506                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5507            /*
5508             * Check to make sure the signatures match first. If they don't,
5509             * wipe the installed application and its data.
5510             */
5511            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5512                    != PackageManager.SIGNATURE_MATCH) {
5513                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5514                        + " signatures don't match existing userdata copy; removing");
5515                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5516                ps = null;
5517            } else {
5518                /*
5519                 * If the newly-added system app is an older version than the
5520                 * already installed version, hide it. It will be scanned later
5521                 * and re-added like an update.
5522                 */
5523                if (pkg.mVersionCode <= ps.versionCode) {
5524                    shouldHideSystemApp = true;
5525                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5526                            + " but new version " + pkg.mVersionCode + " better than installed "
5527                            + ps.versionCode + "; hiding system");
5528                } else {
5529                    /*
5530                     * The newly found system app is a newer version that the
5531                     * one previously installed. Simply remove the
5532                     * already-installed application and replace it with our own
5533                     * while keeping the application data.
5534                     */
5535                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5536                            + " reverting from " + ps.codePathString + ": new version "
5537                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5538                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5539                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5540                    synchronized (mInstallLock) {
5541                        args.cleanUpResourcesLI();
5542                    }
5543                }
5544            }
5545        }
5546
5547        // The apk is forward locked (not public) if its code and resources
5548        // are kept in different files. (except for app in either system or
5549        // vendor path).
5550        // TODO grab this value from PackageSettings
5551        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5552            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5553                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5554            }
5555        }
5556
5557        // TODO: extend to support forward-locked splits
5558        String resourcePath = null;
5559        String baseResourcePath = null;
5560        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5561            if (ps != null && ps.resourcePathString != null) {
5562                resourcePath = ps.resourcePathString;
5563                baseResourcePath = ps.resourcePathString;
5564            } else {
5565                // Should not happen at all. Just log an error.
5566                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5567            }
5568        } else {
5569            resourcePath = pkg.codePath;
5570            baseResourcePath = pkg.baseCodePath;
5571        }
5572
5573        // Set application objects path explicitly.
5574        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5575        pkg.applicationInfo.setCodePath(pkg.codePath);
5576        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5577        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5578        pkg.applicationInfo.setResourcePath(resourcePath);
5579        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5580        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5581
5582        // Note that we invoke the following method only if we are about to unpack an application
5583        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5584                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5585
5586        /*
5587         * If the system app should be overridden by a previously installed
5588         * data, hide the system app now and let the /data/app scan pick it up
5589         * again.
5590         */
5591        if (shouldHideSystemApp) {
5592            synchronized (mPackages) {
5593                /*
5594                 * We have to grant systems permissions before we hide, because
5595                 * grantPermissions will assume the package update is trying to
5596                 * expand its permissions.
5597                 */
5598                grantPermissionsLPw(pkg, true, pkg.packageName);
5599                mSettings.disableSystemPackageLPw(pkg.packageName);
5600            }
5601        }
5602
5603        return scannedPkg;
5604    }
5605
5606    private static String fixProcessName(String defProcessName,
5607            String processName, int uid) {
5608        if (processName == null) {
5609            return defProcessName;
5610        }
5611        return processName;
5612    }
5613
5614    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5615            throws PackageManagerException {
5616        if (pkgSetting.signatures.mSignatures != null) {
5617            // Already existing package. Make sure signatures match
5618            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5619                    == PackageManager.SIGNATURE_MATCH;
5620            if (!match) {
5621                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5622                        == PackageManager.SIGNATURE_MATCH;
5623            }
5624            if (!match) {
5625                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5626                        == PackageManager.SIGNATURE_MATCH;
5627            }
5628            if (!match) {
5629                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5630                        + pkg.packageName + " signatures do not match the "
5631                        + "previously installed version; ignoring!");
5632            }
5633        }
5634
5635        // Check for shared user signatures
5636        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5637            // Already existing package. Make sure signatures match
5638            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5639                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5640            if (!match) {
5641                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5642                        == PackageManager.SIGNATURE_MATCH;
5643            }
5644            if (!match) {
5645                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5646                        == PackageManager.SIGNATURE_MATCH;
5647            }
5648            if (!match) {
5649                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5650                        "Package " + pkg.packageName
5651                        + " has no signatures that match those in shared user "
5652                        + pkgSetting.sharedUser.name + "; ignoring!");
5653            }
5654        }
5655    }
5656
5657    /**
5658     * Enforces that only the system UID or root's UID can call a method exposed
5659     * via Binder.
5660     *
5661     * @param message used as message if SecurityException is thrown
5662     * @throws SecurityException if the caller is not system or root
5663     */
5664    private static final void enforceSystemOrRoot(String message) {
5665        final int uid = Binder.getCallingUid();
5666        if (uid != Process.SYSTEM_UID && uid != 0) {
5667            throw new SecurityException(message);
5668        }
5669    }
5670
5671    @Override
5672    public void performBootDexOpt() {
5673        enforceSystemOrRoot("Only the system can request dexopt be performed");
5674
5675        // Before everything else, see whether we need to fstrim.
5676        try {
5677            IMountService ms = PackageHelper.getMountService();
5678            if (ms != null) {
5679                final boolean isUpgrade = isUpgrade();
5680                boolean doTrim = isUpgrade;
5681                if (doTrim) {
5682                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5683                } else {
5684                    final long interval = android.provider.Settings.Global.getLong(
5685                            mContext.getContentResolver(),
5686                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5687                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5688                    if (interval > 0) {
5689                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5690                        if (timeSinceLast > interval) {
5691                            doTrim = true;
5692                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5693                                    + "; running immediately");
5694                        }
5695                    }
5696                }
5697                if (doTrim) {
5698                    if (!isFirstBoot()) {
5699                        try {
5700                            ActivityManagerNative.getDefault().showBootMessage(
5701                                    mContext.getResources().getString(
5702                                            R.string.android_upgrading_fstrim), true);
5703                        } catch (RemoteException e) {
5704                        }
5705                    }
5706                    ms.runMaintenance();
5707                }
5708            } else {
5709                Slog.e(TAG, "Mount service unavailable!");
5710            }
5711        } catch (RemoteException e) {
5712            // Can't happen; MountService is local
5713        }
5714
5715        final ArraySet<PackageParser.Package> pkgs;
5716        synchronized (mPackages) {
5717            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5718        }
5719
5720        if (pkgs != null) {
5721            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5722            // in case the device runs out of space.
5723            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5724            // Give priority to core apps.
5725            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5726                PackageParser.Package pkg = it.next();
5727                if (pkg.coreApp) {
5728                    if (DEBUG_DEXOPT) {
5729                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5730                    }
5731                    sortedPkgs.add(pkg);
5732                    it.remove();
5733                }
5734            }
5735            // Give priority to system apps that listen for pre boot complete.
5736            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5737            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5738            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5739                PackageParser.Package pkg = it.next();
5740                if (pkgNames.contains(pkg.packageName)) {
5741                    if (DEBUG_DEXOPT) {
5742                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5743                    }
5744                    sortedPkgs.add(pkg);
5745                    it.remove();
5746                }
5747            }
5748            // Give priority to system apps.
5749            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5750                PackageParser.Package pkg = it.next();
5751                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5752                    if (DEBUG_DEXOPT) {
5753                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5754                    }
5755                    sortedPkgs.add(pkg);
5756                    it.remove();
5757                }
5758            }
5759            // Give priority to updated system apps.
5760            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5761                PackageParser.Package pkg = it.next();
5762                if (pkg.isUpdatedSystemApp()) {
5763                    if (DEBUG_DEXOPT) {
5764                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5765                    }
5766                    sortedPkgs.add(pkg);
5767                    it.remove();
5768                }
5769            }
5770            // Give priority to apps that listen for boot complete.
5771            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5772            pkgNames = getPackageNamesForIntent(intent);
5773            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5774                PackageParser.Package pkg = it.next();
5775                if (pkgNames.contains(pkg.packageName)) {
5776                    if (DEBUG_DEXOPT) {
5777                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5778                    }
5779                    sortedPkgs.add(pkg);
5780                    it.remove();
5781                }
5782            }
5783            // Filter out packages that aren't recently used.
5784            filterRecentlyUsedApps(pkgs);
5785            // Add all remaining apps.
5786            for (PackageParser.Package pkg : pkgs) {
5787                if (DEBUG_DEXOPT) {
5788                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5789                }
5790                sortedPkgs.add(pkg);
5791            }
5792
5793            // If we want to be lazy, filter everything that wasn't recently used.
5794            if (mLazyDexOpt) {
5795                filterRecentlyUsedApps(sortedPkgs);
5796            }
5797
5798            int i = 0;
5799            int total = sortedPkgs.size();
5800            File dataDir = Environment.getDataDirectory();
5801            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5802            if (lowThreshold == 0) {
5803                throw new IllegalStateException("Invalid low memory threshold");
5804            }
5805            for (PackageParser.Package pkg : sortedPkgs) {
5806                long usableSpace = dataDir.getUsableSpace();
5807                if (usableSpace < lowThreshold) {
5808                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5809                    break;
5810                }
5811                performBootDexOpt(pkg, ++i, total);
5812            }
5813        }
5814    }
5815
5816    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5817        // Filter out packages that aren't recently used.
5818        //
5819        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5820        // should do a full dexopt.
5821        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5822            int total = pkgs.size();
5823            int skipped = 0;
5824            long now = System.currentTimeMillis();
5825            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5826                PackageParser.Package pkg = i.next();
5827                long then = pkg.mLastPackageUsageTimeInMills;
5828                if (then + mDexOptLRUThresholdInMills < now) {
5829                    if (DEBUG_DEXOPT) {
5830                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5831                              ((then == 0) ? "never" : new Date(then)));
5832                    }
5833                    i.remove();
5834                    skipped++;
5835                }
5836            }
5837            if (DEBUG_DEXOPT) {
5838                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5839            }
5840        }
5841    }
5842
5843    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5844        List<ResolveInfo> ris = null;
5845        try {
5846            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5847                    intent, null, 0, UserHandle.USER_OWNER);
5848        } catch (RemoteException e) {
5849        }
5850        ArraySet<String> pkgNames = new ArraySet<String>();
5851        if (ris != null) {
5852            for (ResolveInfo ri : ris) {
5853                pkgNames.add(ri.activityInfo.packageName);
5854            }
5855        }
5856        return pkgNames;
5857    }
5858
5859    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5860        if (DEBUG_DEXOPT) {
5861            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5862        }
5863        if (!isFirstBoot()) {
5864            try {
5865                ActivityManagerNative.getDefault().showBootMessage(
5866                        mContext.getResources().getString(R.string.android_upgrading_apk,
5867                                curr, total), true);
5868            } catch (RemoteException e) {
5869            }
5870        }
5871        PackageParser.Package p = pkg;
5872        synchronized (mInstallLock) {
5873            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5874                    false /* force dex */, false /* defer */, true /* include dependencies */);
5875        }
5876    }
5877
5878    @Override
5879    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5880        return performDexOpt(packageName, instructionSet, false);
5881    }
5882
5883    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5884        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5885        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5886        if (!dexopt && !updateUsage) {
5887            // We aren't going to dexopt or update usage, so bail early.
5888            return false;
5889        }
5890        PackageParser.Package p;
5891        final String targetInstructionSet;
5892        synchronized (mPackages) {
5893            p = mPackages.get(packageName);
5894            if (p == null) {
5895                return false;
5896            }
5897            if (updateUsage) {
5898                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5899            }
5900            mPackageUsage.write(false);
5901            if (!dexopt) {
5902                // We aren't going to dexopt, so bail early.
5903                return false;
5904            }
5905
5906            targetInstructionSet = instructionSet != null ? instructionSet :
5907                    getPrimaryInstructionSet(p.applicationInfo);
5908            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5909                return false;
5910            }
5911        }
5912
5913        synchronized (mInstallLock) {
5914            final String[] instructionSets = new String[] { targetInstructionSet };
5915            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5916                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5917            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5918        }
5919    }
5920
5921    public ArraySet<String> getPackagesThatNeedDexOpt() {
5922        ArraySet<String> pkgs = null;
5923        synchronized (mPackages) {
5924            for (PackageParser.Package p : mPackages.values()) {
5925                if (DEBUG_DEXOPT) {
5926                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5927                }
5928                if (!p.mDexOptPerformed.isEmpty()) {
5929                    continue;
5930                }
5931                if (pkgs == null) {
5932                    pkgs = new ArraySet<String>();
5933                }
5934                pkgs.add(p.packageName);
5935            }
5936        }
5937        return pkgs;
5938    }
5939
5940    public void shutdown() {
5941        mPackageUsage.write(true);
5942    }
5943
5944    @Override
5945    public void forceDexOpt(String packageName) {
5946        enforceSystemOrRoot("forceDexOpt");
5947
5948        PackageParser.Package pkg;
5949        synchronized (mPackages) {
5950            pkg = mPackages.get(packageName);
5951            if (pkg == null) {
5952                throw new IllegalArgumentException("Missing package: " + packageName);
5953            }
5954        }
5955
5956        synchronized (mInstallLock) {
5957            final String[] instructionSets = new String[] {
5958                    getPrimaryInstructionSet(pkg.applicationInfo) };
5959            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5960                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5961            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5962                throw new IllegalStateException("Failed to dexopt: " + res);
5963            }
5964        }
5965    }
5966
5967    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5968        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5969            Slog.w(TAG, "Unable to update from " + oldPkg.name
5970                    + " to " + newPkg.packageName
5971                    + ": old package not in system partition");
5972            return false;
5973        } else if (mPackages.get(oldPkg.name) != null) {
5974            Slog.w(TAG, "Unable to update from " + oldPkg.name
5975                    + " to " + newPkg.packageName
5976                    + ": old package still exists");
5977            return false;
5978        }
5979        return true;
5980    }
5981
5982    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
5983        int[] users = sUserManager.getUserIds();
5984        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
5985        if (res < 0) {
5986            return res;
5987        }
5988        for (int user : users) {
5989            if (user != 0) {
5990                res = mInstaller.createUserData(volumeUuid, packageName,
5991                        UserHandle.getUid(user, uid), user, seinfo);
5992                if (res < 0) {
5993                    return res;
5994                }
5995            }
5996        }
5997        return res;
5998    }
5999
6000    private int removeDataDirsLI(String volumeUuid, String packageName) {
6001        int[] users = sUserManager.getUserIds();
6002        int res = 0;
6003        for (int user : users) {
6004            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6005            if (resInner < 0) {
6006                res = resInner;
6007            }
6008        }
6009
6010        return res;
6011    }
6012
6013    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6014        int[] users = sUserManager.getUserIds();
6015        int res = 0;
6016        for (int user : users) {
6017            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6018            if (resInner < 0) {
6019                res = resInner;
6020            }
6021        }
6022        return res;
6023    }
6024
6025    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6026            PackageParser.Package changingLib) {
6027        if (file.path != null) {
6028            usesLibraryFiles.add(file.path);
6029            return;
6030        }
6031        PackageParser.Package p = mPackages.get(file.apk);
6032        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6033            // If we are doing this while in the middle of updating a library apk,
6034            // then we need to make sure to use that new apk for determining the
6035            // dependencies here.  (We haven't yet finished committing the new apk
6036            // to the package manager state.)
6037            if (p == null || p.packageName.equals(changingLib.packageName)) {
6038                p = changingLib;
6039            }
6040        }
6041        if (p != null) {
6042            usesLibraryFiles.addAll(p.getAllCodePaths());
6043        }
6044    }
6045
6046    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6047            PackageParser.Package changingLib) throws PackageManagerException {
6048        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6049            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6050            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6051            for (int i=0; i<N; i++) {
6052                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6053                if (file == null) {
6054                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6055                            "Package " + pkg.packageName + " requires unavailable shared library "
6056                            + pkg.usesLibraries.get(i) + "; failing!");
6057                }
6058                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6059            }
6060            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6061            for (int i=0; i<N; i++) {
6062                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6063                if (file == null) {
6064                    Slog.w(TAG, "Package " + pkg.packageName
6065                            + " desires unavailable shared library "
6066                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6067                } else {
6068                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6069                }
6070            }
6071            N = usesLibraryFiles.size();
6072            if (N > 0) {
6073                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6074            } else {
6075                pkg.usesLibraryFiles = null;
6076            }
6077        }
6078    }
6079
6080    private static boolean hasString(List<String> list, List<String> which) {
6081        if (list == null) {
6082            return false;
6083        }
6084        for (int i=list.size()-1; i>=0; i--) {
6085            for (int j=which.size()-1; j>=0; j--) {
6086                if (which.get(j).equals(list.get(i))) {
6087                    return true;
6088                }
6089            }
6090        }
6091        return false;
6092    }
6093
6094    private void updateAllSharedLibrariesLPw() {
6095        for (PackageParser.Package pkg : mPackages.values()) {
6096            try {
6097                updateSharedLibrariesLPw(pkg, null);
6098            } catch (PackageManagerException e) {
6099                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6100            }
6101        }
6102    }
6103
6104    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6105            PackageParser.Package changingPkg) {
6106        ArrayList<PackageParser.Package> res = null;
6107        for (PackageParser.Package pkg : mPackages.values()) {
6108            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6109                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6110                if (res == null) {
6111                    res = new ArrayList<PackageParser.Package>();
6112                }
6113                res.add(pkg);
6114                try {
6115                    updateSharedLibrariesLPw(pkg, changingPkg);
6116                } catch (PackageManagerException e) {
6117                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6118                }
6119            }
6120        }
6121        return res;
6122    }
6123
6124    /**
6125     * Derive the value of the {@code cpuAbiOverride} based on the provided
6126     * value and an optional stored value from the package settings.
6127     */
6128    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6129        String cpuAbiOverride = null;
6130
6131        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6132            cpuAbiOverride = null;
6133        } else if (abiOverride != null) {
6134            cpuAbiOverride = abiOverride;
6135        } else if (settings != null) {
6136            cpuAbiOverride = settings.cpuAbiOverrideString;
6137        }
6138
6139        return cpuAbiOverride;
6140    }
6141
6142    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6143            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6144        boolean success = false;
6145        try {
6146            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6147                    currentTime, user);
6148            success = true;
6149            return res;
6150        } finally {
6151            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6152                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6153            }
6154        }
6155    }
6156
6157    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6158            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6159        final File scanFile = new File(pkg.codePath);
6160        if (pkg.applicationInfo.getCodePath() == null ||
6161                pkg.applicationInfo.getResourcePath() == null) {
6162            // Bail out. The resource and code paths haven't been set.
6163            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6164                    "Code and resource paths haven't been set correctly");
6165        }
6166
6167        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6168            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6169        } else {
6170            // Only allow system apps to be flagged as core apps.
6171            pkg.coreApp = false;
6172        }
6173
6174        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6175            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6176        }
6177
6178        if (mCustomResolverComponentName != null &&
6179                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6180            setUpCustomResolverActivity(pkg);
6181        }
6182
6183        if (pkg.packageName.equals("android")) {
6184            synchronized (mPackages) {
6185                if (mAndroidApplication != null) {
6186                    Slog.w(TAG, "*************************************************");
6187                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6188                    Slog.w(TAG, " file=" + scanFile);
6189                    Slog.w(TAG, "*************************************************");
6190                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6191                            "Core android package being redefined.  Skipping.");
6192                }
6193
6194                // Set up information for our fall-back user intent resolution activity.
6195                mPlatformPackage = pkg;
6196                pkg.mVersionCode = mSdkVersion;
6197                mAndroidApplication = pkg.applicationInfo;
6198
6199                if (!mResolverReplaced) {
6200                    mResolveActivity.applicationInfo = mAndroidApplication;
6201                    mResolveActivity.name = ResolverActivity.class.getName();
6202                    mResolveActivity.packageName = mAndroidApplication.packageName;
6203                    mResolveActivity.processName = "system:ui";
6204                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6205                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6206                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6207                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6208                    mResolveActivity.exported = true;
6209                    mResolveActivity.enabled = true;
6210                    mResolveInfo.activityInfo = mResolveActivity;
6211                    mResolveInfo.priority = 0;
6212                    mResolveInfo.preferredOrder = 0;
6213                    mResolveInfo.match = 0;
6214                    mResolveComponentName = new ComponentName(
6215                            mAndroidApplication.packageName, mResolveActivity.name);
6216                }
6217            }
6218        }
6219
6220        if (DEBUG_PACKAGE_SCANNING) {
6221            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6222                Log.d(TAG, "Scanning package " + pkg.packageName);
6223        }
6224
6225        if (mPackages.containsKey(pkg.packageName)
6226                || mSharedLibraries.containsKey(pkg.packageName)) {
6227            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6228                    "Application package " + pkg.packageName
6229                    + " already installed.  Skipping duplicate.");
6230        }
6231
6232        // If we're only installing presumed-existing packages, require that the
6233        // scanned APK is both already known and at the path previously established
6234        // for it.  Previously unknown packages we pick up normally, but if we have an
6235        // a priori expectation about this package's install presence, enforce it.
6236        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6237            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6238            if (known != null) {
6239                if (DEBUG_PACKAGE_SCANNING) {
6240                    Log.d(TAG, "Examining " + pkg.codePath
6241                            + " and requiring known paths " + known.codePathString
6242                            + " & " + known.resourcePathString);
6243                }
6244                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6245                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6246                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6247                            "Application package " + pkg.packageName
6248                            + " found at " + pkg.applicationInfo.getCodePath()
6249                            + " but expected at " + known.codePathString + "; ignoring.");
6250                }
6251            }
6252        }
6253
6254        // Initialize package source and resource directories
6255        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6256        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6257
6258        SharedUserSetting suid = null;
6259        PackageSetting pkgSetting = null;
6260
6261        if (!isSystemApp(pkg)) {
6262            // Only system apps can use these features.
6263            pkg.mOriginalPackages = null;
6264            pkg.mRealPackage = null;
6265            pkg.mAdoptPermissions = null;
6266        }
6267
6268        // writer
6269        synchronized (mPackages) {
6270            if (pkg.mSharedUserId != null) {
6271                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6272                if (suid == null) {
6273                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6274                            "Creating application package " + pkg.packageName
6275                            + " for shared user failed");
6276                }
6277                if (DEBUG_PACKAGE_SCANNING) {
6278                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6279                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6280                                + "): packages=" + suid.packages);
6281                }
6282            }
6283
6284            // Check if we are renaming from an original package name.
6285            PackageSetting origPackage = null;
6286            String realName = null;
6287            if (pkg.mOriginalPackages != null) {
6288                // This package may need to be renamed to a previously
6289                // installed name.  Let's check on that...
6290                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6291                if (pkg.mOriginalPackages.contains(renamed)) {
6292                    // This package had originally been installed as the
6293                    // original name, and we have already taken care of
6294                    // transitioning to the new one.  Just update the new
6295                    // one to continue using the old name.
6296                    realName = pkg.mRealPackage;
6297                    if (!pkg.packageName.equals(renamed)) {
6298                        // Callers into this function may have already taken
6299                        // care of renaming the package; only do it here if
6300                        // it is not already done.
6301                        pkg.setPackageName(renamed);
6302                    }
6303
6304                } else {
6305                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6306                        if ((origPackage = mSettings.peekPackageLPr(
6307                                pkg.mOriginalPackages.get(i))) != null) {
6308                            // We do have the package already installed under its
6309                            // original name...  should we use it?
6310                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6311                                // New package is not compatible with original.
6312                                origPackage = null;
6313                                continue;
6314                            } else if (origPackage.sharedUser != null) {
6315                                // Make sure uid is compatible between packages.
6316                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6317                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6318                                            + " to " + pkg.packageName + ": old uid "
6319                                            + origPackage.sharedUser.name
6320                                            + " differs from " + pkg.mSharedUserId);
6321                                    origPackage = null;
6322                                    continue;
6323                                }
6324                            } else {
6325                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6326                                        + pkg.packageName + " to old name " + origPackage.name);
6327                            }
6328                            break;
6329                        }
6330                    }
6331                }
6332            }
6333
6334            if (mTransferedPackages.contains(pkg.packageName)) {
6335                Slog.w(TAG, "Package " + pkg.packageName
6336                        + " was transferred to another, but its .apk remains");
6337            }
6338
6339            // Just create the setting, don't add it yet. For already existing packages
6340            // the PkgSetting exists already and doesn't have to be created.
6341            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6342                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6343                    pkg.applicationInfo.primaryCpuAbi,
6344                    pkg.applicationInfo.secondaryCpuAbi,
6345                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6346                    user, false);
6347            if (pkgSetting == null) {
6348                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6349                        "Creating application package " + pkg.packageName + " failed");
6350            }
6351
6352            if (pkgSetting.origPackage != null) {
6353                // If we are first transitioning from an original package,
6354                // fix up the new package's name now.  We need to do this after
6355                // looking up the package under its new name, so getPackageLP
6356                // can take care of fiddling things correctly.
6357                pkg.setPackageName(origPackage.name);
6358
6359                // File a report about this.
6360                String msg = "New package " + pkgSetting.realName
6361                        + " renamed to replace old package " + pkgSetting.name;
6362                reportSettingsProblem(Log.WARN, msg);
6363
6364                // Make a note of it.
6365                mTransferedPackages.add(origPackage.name);
6366
6367                // No longer need to retain this.
6368                pkgSetting.origPackage = null;
6369            }
6370
6371            if (realName != null) {
6372                // Make a note of it.
6373                mTransferedPackages.add(pkg.packageName);
6374            }
6375
6376            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6377                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6378            }
6379
6380            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6381                // Check all shared libraries and map to their actual file path.
6382                // We only do this here for apps not on a system dir, because those
6383                // are the only ones that can fail an install due to this.  We
6384                // will take care of the system apps by updating all of their
6385                // library paths after the scan is done.
6386                updateSharedLibrariesLPw(pkg, null);
6387            }
6388
6389            if (mFoundPolicyFile) {
6390                SELinuxMMAC.assignSeinfoValue(pkg);
6391            }
6392
6393            pkg.applicationInfo.uid = pkgSetting.appId;
6394            pkg.mExtras = pkgSetting;
6395            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6396                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6397                    // We just determined the app is signed correctly, so bring
6398                    // over the latest parsed certs.
6399                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6400                } else {
6401                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6402                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6403                                "Package " + pkg.packageName + " upgrade keys do not match the "
6404                                + "previously installed version");
6405                    } else {
6406                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6407                        String msg = "System package " + pkg.packageName
6408                            + " signature changed; retaining data.";
6409                        reportSettingsProblem(Log.WARN, msg);
6410                    }
6411                }
6412            } else {
6413                try {
6414                    verifySignaturesLP(pkgSetting, pkg);
6415                    // We just determined the app is signed correctly, so bring
6416                    // over the latest parsed certs.
6417                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6418                } catch (PackageManagerException e) {
6419                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6420                        throw e;
6421                    }
6422                    // The signature has changed, but this package is in the system
6423                    // image...  let's recover!
6424                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6425                    // However...  if this package is part of a shared user, but it
6426                    // doesn't match the signature of the shared user, let's fail.
6427                    // What this means is that you can't change the signatures
6428                    // associated with an overall shared user, which doesn't seem all
6429                    // that unreasonable.
6430                    if (pkgSetting.sharedUser != null) {
6431                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6432                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6433                            throw new PackageManagerException(
6434                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6435                                            "Signature mismatch for shared user : "
6436                                            + pkgSetting.sharedUser);
6437                        }
6438                    }
6439                    // File a report about this.
6440                    String msg = "System package " + pkg.packageName
6441                        + " signature changed; retaining data.";
6442                    reportSettingsProblem(Log.WARN, msg);
6443                }
6444            }
6445            // Verify that this new package doesn't have any content providers
6446            // that conflict with existing packages.  Only do this if the
6447            // package isn't already installed, since we don't want to break
6448            // things that are installed.
6449            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6450                final int N = pkg.providers.size();
6451                int i;
6452                for (i=0; i<N; i++) {
6453                    PackageParser.Provider p = pkg.providers.get(i);
6454                    if (p.info.authority != null) {
6455                        String names[] = p.info.authority.split(";");
6456                        for (int j = 0; j < names.length; j++) {
6457                            if (mProvidersByAuthority.containsKey(names[j])) {
6458                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6459                                final String otherPackageName =
6460                                        ((other != null && other.getComponentName() != null) ?
6461                                                other.getComponentName().getPackageName() : "?");
6462                                throw new PackageManagerException(
6463                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6464                                                "Can't install because provider name " + names[j]
6465                                                + " (in package " + pkg.applicationInfo.packageName
6466                                                + ") is already used by " + otherPackageName);
6467                            }
6468                        }
6469                    }
6470                }
6471            }
6472
6473            if (pkg.mAdoptPermissions != null) {
6474                // This package wants to adopt ownership of permissions from
6475                // another package.
6476                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6477                    final String origName = pkg.mAdoptPermissions.get(i);
6478                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6479                    if (orig != null) {
6480                        if (verifyPackageUpdateLPr(orig, pkg)) {
6481                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6482                                    + pkg.packageName);
6483                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6484                        }
6485                    }
6486                }
6487            }
6488        }
6489
6490        final String pkgName = pkg.packageName;
6491
6492        final long scanFileTime = scanFile.lastModified();
6493        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6494        pkg.applicationInfo.processName = fixProcessName(
6495                pkg.applicationInfo.packageName,
6496                pkg.applicationInfo.processName,
6497                pkg.applicationInfo.uid);
6498
6499        File dataPath;
6500        if (mPlatformPackage == pkg) {
6501            // The system package is special.
6502            dataPath = new File(Environment.getDataDirectory(), "system");
6503
6504            pkg.applicationInfo.dataDir = dataPath.getPath();
6505
6506        } else {
6507            // This is a normal package, need to make its data directory.
6508            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6509                    UserHandle.USER_OWNER);
6510
6511            boolean uidError = false;
6512            if (dataPath.exists()) {
6513                int currentUid = 0;
6514                try {
6515                    StructStat stat = Os.stat(dataPath.getPath());
6516                    currentUid = stat.st_uid;
6517                } catch (ErrnoException e) {
6518                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6519                }
6520
6521                // If we have mismatched owners for the data path, we have a problem.
6522                if (currentUid != pkg.applicationInfo.uid) {
6523                    boolean recovered = false;
6524                    if (currentUid == 0) {
6525                        // The directory somehow became owned by root.  Wow.
6526                        // This is probably because the system was stopped while
6527                        // installd was in the middle of messing with its libs
6528                        // directory.  Ask installd to fix that.
6529                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6530                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6531                        if (ret >= 0) {
6532                            recovered = true;
6533                            String msg = "Package " + pkg.packageName
6534                                    + " unexpectedly changed to uid 0; recovered to " +
6535                                    + pkg.applicationInfo.uid;
6536                            reportSettingsProblem(Log.WARN, msg);
6537                        }
6538                    }
6539                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6540                            || (scanFlags&SCAN_BOOTING) != 0)) {
6541                        // If this is a system app, we can at least delete its
6542                        // current data so the application will still work.
6543                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6544                        if (ret >= 0) {
6545                            // TODO: Kill the processes first
6546                            // Old data gone!
6547                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6548                                    ? "System package " : "Third party package ";
6549                            String msg = prefix + pkg.packageName
6550                                    + " has changed from uid: "
6551                                    + currentUid + " to "
6552                                    + pkg.applicationInfo.uid + "; old data erased";
6553                            reportSettingsProblem(Log.WARN, msg);
6554                            recovered = true;
6555
6556                            // And now re-install the app.
6557                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6558                                    pkg.applicationInfo.seinfo);
6559                            if (ret == -1) {
6560                                // Ack should not happen!
6561                                msg = prefix + pkg.packageName
6562                                        + " could not have data directory re-created after delete.";
6563                                reportSettingsProblem(Log.WARN, msg);
6564                                throw new PackageManagerException(
6565                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6566                            }
6567                        }
6568                        if (!recovered) {
6569                            mHasSystemUidErrors = true;
6570                        }
6571                    } else if (!recovered) {
6572                        // If we allow this install to proceed, we will be broken.
6573                        // Abort, abort!
6574                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6575                                "scanPackageLI");
6576                    }
6577                    if (!recovered) {
6578                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6579                            + pkg.applicationInfo.uid + "/fs_"
6580                            + currentUid;
6581                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6582                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6583                        String msg = "Package " + pkg.packageName
6584                                + " has mismatched uid: "
6585                                + currentUid + " on disk, "
6586                                + pkg.applicationInfo.uid + " in settings";
6587                        // writer
6588                        synchronized (mPackages) {
6589                            mSettings.mReadMessages.append(msg);
6590                            mSettings.mReadMessages.append('\n');
6591                            uidError = true;
6592                            if (!pkgSetting.uidError) {
6593                                reportSettingsProblem(Log.ERROR, msg);
6594                            }
6595                        }
6596                    }
6597                }
6598                pkg.applicationInfo.dataDir = dataPath.getPath();
6599                if (mShouldRestoreconData) {
6600                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6601                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6602                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6603                }
6604            } else {
6605                if (DEBUG_PACKAGE_SCANNING) {
6606                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6607                        Log.v(TAG, "Want this data dir: " + dataPath);
6608                }
6609                //invoke installer to do the actual installation
6610                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6611                        pkg.applicationInfo.seinfo);
6612                if (ret < 0) {
6613                    // Error from installer
6614                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6615                            "Unable to create data dirs [errorCode=" + ret + "]");
6616                }
6617
6618                if (dataPath.exists()) {
6619                    pkg.applicationInfo.dataDir = dataPath.getPath();
6620                } else {
6621                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6622                    pkg.applicationInfo.dataDir = null;
6623                }
6624            }
6625
6626            pkgSetting.uidError = uidError;
6627        }
6628
6629        final String path = scanFile.getPath();
6630        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6631
6632        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6633            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6634
6635            // Some system apps still use directory structure for native libraries
6636            // in which case we might end up not detecting abi solely based on apk
6637            // structure. Try to detect abi based on directory structure.
6638            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6639                    pkg.applicationInfo.primaryCpuAbi == null) {
6640                setBundledAppAbisAndRoots(pkg, pkgSetting);
6641                setNativeLibraryPaths(pkg);
6642            }
6643
6644        } else {
6645            if ((scanFlags & SCAN_MOVE) != 0) {
6646                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6647                // but we already have this packages package info in the PackageSetting. We just
6648                // use that and derive the native library path based on the new codepath.
6649                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6650                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6651            }
6652
6653            // Set native library paths again. For moves, the path will be updated based on the
6654            // ABIs we've determined above. For non-moves, the path will be updated based on the
6655            // ABIs we determined during compilation, but the path will depend on the final
6656            // package path (after the rename away from the stage path).
6657            setNativeLibraryPaths(pkg);
6658        }
6659
6660        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6661        final int[] userIds = sUserManager.getUserIds();
6662        synchronized (mInstallLock) {
6663            // Create a native library symlink only if we have native libraries
6664            // and if the native libraries are 32 bit libraries. We do not provide
6665            // this symlink for 64 bit libraries.
6666            if (pkg.applicationInfo.primaryCpuAbi != null &&
6667                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6668                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6669                for (int userId : userIds) {
6670                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6671                            nativeLibPath, userId) < 0) {
6672                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6673                                "Failed linking native library dir (user=" + userId + ")");
6674                    }
6675                }
6676            }
6677        }
6678
6679        // This is a special case for the "system" package, where the ABI is
6680        // dictated by the zygote configuration (and init.rc). We should keep track
6681        // of this ABI so that we can deal with "normal" applications that run under
6682        // the same UID correctly.
6683        if (mPlatformPackage == pkg) {
6684            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6685                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6686        }
6687
6688        // If there's a mismatch between the abi-override in the package setting
6689        // and the abiOverride specified for the install. Warn about this because we
6690        // would've already compiled the app without taking the package setting into
6691        // account.
6692        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6693            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6694                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6695                        " for package: " + pkg.packageName);
6696            }
6697        }
6698
6699        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6700        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6701        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6702
6703        // Copy the derived override back to the parsed package, so that we can
6704        // update the package settings accordingly.
6705        pkg.cpuAbiOverride = cpuAbiOverride;
6706
6707        if (DEBUG_ABI_SELECTION) {
6708            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6709                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6710                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6711        }
6712
6713        // Push the derived path down into PackageSettings so we know what to
6714        // clean up at uninstall time.
6715        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6716
6717        if (DEBUG_ABI_SELECTION) {
6718            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6719                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6720                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6721        }
6722
6723        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6724            // We don't do this here during boot because we can do it all
6725            // at once after scanning all existing packages.
6726            //
6727            // We also do this *before* we perform dexopt on this package, so that
6728            // we can avoid redundant dexopts, and also to make sure we've got the
6729            // code and package path correct.
6730            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6731                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6732        }
6733
6734        if ((scanFlags & SCAN_NO_DEX) == 0) {
6735            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6736                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6737            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6738                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6739            }
6740        }
6741        if (mFactoryTest && pkg.requestedPermissions.contains(
6742                android.Manifest.permission.FACTORY_TEST)) {
6743            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6744        }
6745
6746        ArrayList<PackageParser.Package> clientLibPkgs = null;
6747
6748        // writer
6749        synchronized (mPackages) {
6750            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6751                // Only system apps can add new shared libraries.
6752                if (pkg.libraryNames != null) {
6753                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6754                        String name = pkg.libraryNames.get(i);
6755                        boolean allowed = false;
6756                        if (pkg.isUpdatedSystemApp()) {
6757                            // New library entries can only be added through the
6758                            // system image.  This is important to get rid of a lot
6759                            // of nasty edge cases: for example if we allowed a non-
6760                            // system update of the app to add a library, then uninstalling
6761                            // the update would make the library go away, and assumptions
6762                            // we made such as through app install filtering would now
6763                            // have allowed apps on the device which aren't compatible
6764                            // with it.  Better to just have the restriction here, be
6765                            // conservative, and create many fewer cases that can negatively
6766                            // impact the user experience.
6767                            final PackageSetting sysPs = mSettings
6768                                    .getDisabledSystemPkgLPr(pkg.packageName);
6769                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6770                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6771                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6772                                        allowed = true;
6773                                        allowed = true;
6774                                        break;
6775                                    }
6776                                }
6777                            }
6778                        } else {
6779                            allowed = true;
6780                        }
6781                        if (allowed) {
6782                            if (!mSharedLibraries.containsKey(name)) {
6783                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6784                            } else if (!name.equals(pkg.packageName)) {
6785                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6786                                        + name + " already exists; skipping");
6787                            }
6788                        } else {
6789                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6790                                    + name + " that is not declared on system image; skipping");
6791                        }
6792                    }
6793                    if ((scanFlags&SCAN_BOOTING) == 0) {
6794                        // If we are not booting, we need to update any applications
6795                        // that are clients of our shared library.  If we are booting,
6796                        // this will all be done once the scan is complete.
6797                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6798                    }
6799                }
6800            }
6801        }
6802
6803        // We also need to dexopt any apps that are dependent on this library.  Note that
6804        // if these fail, we should abort the install since installing the library will
6805        // result in some apps being broken.
6806        if (clientLibPkgs != null) {
6807            if ((scanFlags & SCAN_NO_DEX) == 0) {
6808                for (int i = 0; i < clientLibPkgs.size(); i++) {
6809                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6810                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6811                            null /* instruction sets */, forceDex,
6812                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6813                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6814                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6815                                "scanPackageLI failed to dexopt clientLibPkgs");
6816                    }
6817                }
6818            }
6819        }
6820
6821        // Also need to kill any apps that are dependent on the library.
6822        if (clientLibPkgs != null) {
6823            for (int i=0; i<clientLibPkgs.size(); i++) {
6824                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6825                killApplication(clientPkg.applicationInfo.packageName,
6826                        clientPkg.applicationInfo.uid, "update lib");
6827            }
6828        }
6829
6830        // Make sure we're not adding any bogus keyset info
6831        KeySetManagerService ksms = mSettings.mKeySetManagerService;
6832        ksms.assertScannedPackageValid(pkg);
6833
6834        // writer
6835        synchronized (mPackages) {
6836            // We don't expect installation to fail beyond this point
6837
6838            // Add the new setting to mSettings
6839            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6840            // Add the new setting to mPackages
6841            mPackages.put(pkg.applicationInfo.packageName, pkg);
6842            // Make sure we don't accidentally delete its data.
6843            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6844            while (iter.hasNext()) {
6845                PackageCleanItem item = iter.next();
6846                if (pkgName.equals(item.packageName)) {
6847                    iter.remove();
6848                }
6849            }
6850
6851            // Take care of first install / last update times.
6852            if (currentTime != 0) {
6853                if (pkgSetting.firstInstallTime == 0) {
6854                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6855                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6856                    pkgSetting.lastUpdateTime = currentTime;
6857                }
6858            } else if (pkgSetting.firstInstallTime == 0) {
6859                // We need *something*.  Take time time stamp of the file.
6860                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6861            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6862                if (scanFileTime != pkgSetting.timeStamp) {
6863                    // A package on the system image has changed; consider this
6864                    // to be an update.
6865                    pkgSetting.lastUpdateTime = scanFileTime;
6866                }
6867            }
6868
6869            // Add the package's KeySets to the global KeySetManagerService
6870            ksms.addScannedPackageLPw(pkg);
6871
6872            int N = pkg.providers.size();
6873            StringBuilder r = null;
6874            int i;
6875            for (i=0; i<N; i++) {
6876                PackageParser.Provider p = pkg.providers.get(i);
6877                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6878                        p.info.processName, pkg.applicationInfo.uid);
6879                mProviders.addProvider(p);
6880                p.syncable = p.info.isSyncable;
6881                if (p.info.authority != null) {
6882                    String names[] = p.info.authority.split(";");
6883                    p.info.authority = null;
6884                    for (int j = 0; j < names.length; j++) {
6885                        if (j == 1 && p.syncable) {
6886                            // We only want the first authority for a provider to possibly be
6887                            // syncable, so if we already added this provider using a different
6888                            // authority clear the syncable flag. We copy the provider before
6889                            // changing it because the mProviders object contains a reference
6890                            // to a provider that we don't want to change.
6891                            // Only do this for the second authority since the resulting provider
6892                            // object can be the same for all future authorities for this provider.
6893                            p = new PackageParser.Provider(p);
6894                            p.syncable = false;
6895                        }
6896                        if (!mProvidersByAuthority.containsKey(names[j])) {
6897                            mProvidersByAuthority.put(names[j], p);
6898                            if (p.info.authority == null) {
6899                                p.info.authority = names[j];
6900                            } else {
6901                                p.info.authority = p.info.authority + ";" + names[j];
6902                            }
6903                            if (DEBUG_PACKAGE_SCANNING) {
6904                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6905                                    Log.d(TAG, "Registered content provider: " + names[j]
6906                                            + ", className = " + p.info.name + ", isSyncable = "
6907                                            + p.info.isSyncable);
6908                            }
6909                        } else {
6910                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6911                            Slog.w(TAG, "Skipping provider name " + names[j] +
6912                                    " (in package " + pkg.applicationInfo.packageName +
6913                                    "): name already used by "
6914                                    + ((other != null && other.getComponentName() != null)
6915                                            ? other.getComponentName().getPackageName() : "?"));
6916                        }
6917                    }
6918                }
6919                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6920                    if (r == null) {
6921                        r = new StringBuilder(256);
6922                    } else {
6923                        r.append(' ');
6924                    }
6925                    r.append(p.info.name);
6926                }
6927            }
6928            if (r != null) {
6929                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6930            }
6931
6932            N = pkg.services.size();
6933            r = null;
6934            for (i=0; i<N; i++) {
6935                PackageParser.Service s = pkg.services.get(i);
6936                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6937                        s.info.processName, pkg.applicationInfo.uid);
6938                mServices.addService(s);
6939                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6940                    if (r == null) {
6941                        r = new StringBuilder(256);
6942                    } else {
6943                        r.append(' ');
6944                    }
6945                    r.append(s.info.name);
6946                }
6947            }
6948            if (r != null) {
6949                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6950            }
6951
6952            N = pkg.receivers.size();
6953            r = null;
6954            for (i=0; i<N; i++) {
6955                PackageParser.Activity a = pkg.receivers.get(i);
6956                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6957                        a.info.processName, pkg.applicationInfo.uid);
6958                mReceivers.addActivity(a, "receiver");
6959                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6960                    if (r == null) {
6961                        r = new StringBuilder(256);
6962                    } else {
6963                        r.append(' ');
6964                    }
6965                    r.append(a.info.name);
6966                }
6967            }
6968            if (r != null) {
6969                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6970            }
6971
6972            N = pkg.activities.size();
6973            r = null;
6974            for (i=0; i<N; i++) {
6975                PackageParser.Activity a = pkg.activities.get(i);
6976                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6977                        a.info.processName, pkg.applicationInfo.uid);
6978                mActivities.addActivity(a, "activity");
6979                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6980                    if (r == null) {
6981                        r = new StringBuilder(256);
6982                    } else {
6983                        r.append(' ');
6984                    }
6985                    r.append(a.info.name);
6986                }
6987            }
6988            if (r != null) {
6989                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6990            }
6991
6992            N = pkg.permissionGroups.size();
6993            r = null;
6994            for (i=0; i<N; i++) {
6995                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6996                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6997                if (cur == null) {
6998                    mPermissionGroups.put(pg.info.name, pg);
6999                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7000                        if (r == null) {
7001                            r = new StringBuilder(256);
7002                        } else {
7003                            r.append(' ');
7004                        }
7005                        r.append(pg.info.name);
7006                    }
7007                } else {
7008                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7009                            + pg.info.packageName + " ignored: original from "
7010                            + cur.info.packageName);
7011                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7012                        if (r == null) {
7013                            r = new StringBuilder(256);
7014                        } else {
7015                            r.append(' ');
7016                        }
7017                        r.append("DUP:");
7018                        r.append(pg.info.name);
7019                    }
7020                }
7021            }
7022            if (r != null) {
7023                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7024            }
7025
7026            N = pkg.permissions.size();
7027            r = null;
7028            for (i=0; i<N; i++) {
7029                PackageParser.Permission p = pkg.permissions.get(i);
7030
7031                // Now that permission groups have a special meaning, we ignore permission
7032                // groups for legacy apps to prevent unexpected behavior. In particular,
7033                // permissions for one app being granted to someone just becuase they happen
7034                // to be in a group defined by another app (before this had no implications).
7035                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7036                    p.group = mPermissionGroups.get(p.info.group);
7037                    // Warn for a permission in an unknown group.
7038                    if (p.info.group != null && p.group == null) {
7039                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7040                                + p.info.packageName + " in an unknown group " + p.info.group);
7041                    }
7042                }
7043
7044                ArrayMap<String, BasePermission> permissionMap =
7045                        p.tree ? mSettings.mPermissionTrees
7046                                : mSettings.mPermissions;
7047                BasePermission bp = permissionMap.get(p.info.name);
7048
7049                // Allow system apps to redefine non-system permissions
7050                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7051                    final boolean currentOwnerIsSystem = (bp.perm != null
7052                            && isSystemApp(bp.perm.owner));
7053                    if (isSystemApp(p.owner)) {
7054                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7055                            // It's a built-in permission and no owner, take ownership now
7056                            bp.packageSetting = pkgSetting;
7057                            bp.perm = p;
7058                            bp.uid = pkg.applicationInfo.uid;
7059                            bp.sourcePackage = p.info.packageName;
7060                        } else if (!currentOwnerIsSystem) {
7061                            String msg = "New decl " + p.owner + " of permission  "
7062                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7063                            reportSettingsProblem(Log.WARN, msg);
7064                            bp = null;
7065                        }
7066                    }
7067                }
7068
7069                if (bp == null) {
7070                    bp = new BasePermission(p.info.name, p.info.packageName,
7071                            BasePermission.TYPE_NORMAL);
7072                    permissionMap.put(p.info.name, bp);
7073                }
7074
7075                if (bp.perm == null) {
7076                    if (bp.sourcePackage == null
7077                            || bp.sourcePackage.equals(p.info.packageName)) {
7078                        BasePermission tree = findPermissionTreeLP(p.info.name);
7079                        if (tree == null
7080                                || tree.sourcePackage.equals(p.info.packageName)) {
7081                            bp.packageSetting = pkgSetting;
7082                            bp.perm = p;
7083                            bp.uid = pkg.applicationInfo.uid;
7084                            bp.sourcePackage = p.info.packageName;
7085                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7086                                if (r == null) {
7087                                    r = new StringBuilder(256);
7088                                } else {
7089                                    r.append(' ');
7090                                }
7091                                r.append(p.info.name);
7092                            }
7093                        } else {
7094                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7095                                    + p.info.packageName + " ignored: base tree "
7096                                    + tree.name + " is from package "
7097                                    + tree.sourcePackage);
7098                        }
7099                    } else {
7100                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7101                                + p.info.packageName + " ignored: original from "
7102                                + bp.sourcePackage);
7103                    }
7104                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7105                    if (r == null) {
7106                        r = new StringBuilder(256);
7107                    } else {
7108                        r.append(' ');
7109                    }
7110                    r.append("DUP:");
7111                    r.append(p.info.name);
7112                }
7113                if (bp.perm == p) {
7114                    bp.protectionLevel = p.info.protectionLevel;
7115                }
7116            }
7117
7118            if (r != null) {
7119                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7120            }
7121
7122            N = pkg.instrumentation.size();
7123            r = null;
7124            for (i=0; i<N; i++) {
7125                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7126                a.info.packageName = pkg.applicationInfo.packageName;
7127                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7128                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7129                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7130                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7131                a.info.dataDir = pkg.applicationInfo.dataDir;
7132
7133                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7134                // need other information about the application, like the ABI and what not ?
7135                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7136                mInstrumentation.put(a.getComponentName(), a);
7137                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7138                    if (r == null) {
7139                        r = new StringBuilder(256);
7140                    } else {
7141                        r.append(' ');
7142                    }
7143                    r.append(a.info.name);
7144                }
7145            }
7146            if (r != null) {
7147                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7148            }
7149
7150            if (pkg.protectedBroadcasts != null) {
7151                N = pkg.protectedBroadcasts.size();
7152                for (i=0; i<N; i++) {
7153                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7154                }
7155            }
7156
7157            pkgSetting.setTimeStamp(scanFileTime);
7158
7159            // Create idmap files for pairs of (packages, overlay packages).
7160            // Note: "android", ie framework-res.apk, is handled by native layers.
7161            if (pkg.mOverlayTarget != null) {
7162                // This is an overlay package.
7163                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7164                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7165                        mOverlays.put(pkg.mOverlayTarget,
7166                                new ArrayMap<String, PackageParser.Package>());
7167                    }
7168                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7169                    map.put(pkg.packageName, pkg);
7170                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7171                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7172                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7173                                "scanPackageLI failed to createIdmap");
7174                    }
7175                }
7176            } else if (mOverlays.containsKey(pkg.packageName) &&
7177                    !pkg.packageName.equals("android")) {
7178                // This is a regular package, with one or more known overlay packages.
7179                createIdmapsForPackageLI(pkg);
7180            }
7181        }
7182
7183        return pkg;
7184    }
7185
7186    /**
7187     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7188     * is derived purely on the basis of the contents of {@code scanFile} and
7189     * {@code cpuAbiOverride}.
7190     *
7191     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7192     */
7193    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7194                                 String cpuAbiOverride, boolean extractLibs)
7195            throws PackageManagerException {
7196        // TODO: We can probably be smarter about this stuff. For installed apps,
7197        // we can calculate this information at install time once and for all. For
7198        // system apps, we can probably assume that this information doesn't change
7199        // after the first boot scan. As things stand, we do lots of unnecessary work.
7200
7201        // Give ourselves some initial paths; we'll come back for another
7202        // pass once we've determined ABI below.
7203        setNativeLibraryPaths(pkg);
7204
7205        // We would never need to extract libs for forward-locked and external packages,
7206        // since the container service will do it for us. We shouldn't attempt to
7207        // extract libs from system app when it was not updated.
7208        if (pkg.isForwardLocked() || isExternal(pkg) ||
7209            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7210            extractLibs = false;
7211        }
7212
7213        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7214        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7215
7216        NativeLibraryHelper.Handle handle = null;
7217        try {
7218            handle = NativeLibraryHelper.Handle.create(scanFile);
7219            // TODO(multiArch): This can be null for apps that didn't go through the
7220            // usual installation process. We can calculate it again, like we
7221            // do during install time.
7222            //
7223            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7224            // unnecessary.
7225            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7226
7227            // Null out the abis so that they can be recalculated.
7228            pkg.applicationInfo.primaryCpuAbi = null;
7229            pkg.applicationInfo.secondaryCpuAbi = null;
7230            if (isMultiArch(pkg.applicationInfo)) {
7231                // Warn if we've set an abiOverride for multi-lib packages..
7232                // By definition, we need to copy both 32 and 64 bit libraries for
7233                // such packages.
7234                if (pkg.cpuAbiOverride != null
7235                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7236                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7237                }
7238
7239                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7240                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7241                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7242                    if (extractLibs) {
7243                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7244                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7245                                useIsaSpecificSubdirs);
7246                    } else {
7247                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7248                    }
7249                }
7250
7251                maybeThrowExceptionForMultiArchCopy(
7252                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7253
7254                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7255                    if (extractLibs) {
7256                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7257                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7258                                useIsaSpecificSubdirs);
7259                    } else {
7260                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7261                    }
7262                }
7263
7264                maybeThrowExceptionForMultiArchCopy(
7265                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7266
7267                if (abi64 >= 0) {
7268                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7269                }
7270
7271                if (abi32 >= 0) {
7272                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7273                    if (abi64 >= 0) {
7274                        pkg.applicationInfo.secondaryCpuAbi = abi;
7275                    } else {
7276                        pkg.applicationInfo.primaryCpuAbi = abi;
7277                    }
7278                }
7279            } else {
7280                String[] abiList = (cpuAbiOverride != null) ?
7281                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7282
7283                // Enable gross and lame hacks for apps that are built with old
7284                // SDK tools. We must scan their APKs for renderscript bitcode and
7285                // not launch them if it's present. Don't bother checking on devices
7286                // that don't have 64 bit support.
7287                boolean needsRenderScriptOverride = false;
7288                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7289                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7290                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7291                    needsRenderScriptOverride = true;
7292                }
7293
7294                final int copyRet;
7295                if (extractLibs) {
7296                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7297                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7298                } else {
7299                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7300                }
7301
7302                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7303                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7304                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7305                }
7306
7307                if (copyRet >= 0) {
7308                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7309                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7310                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7311                } else if (needsRenderScriptOverride) {
7312                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7313                }
7314            }
7315        } catch (IOException ioe) {
7316            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7317        } finally {
7318            IoUtils.closeQuietly(handle);
7319        }
7320
7321        // Now that we've calculated the ABIs and determined if it's an internal app,
7322        // we will go ahead and populate the nativeLibraryPath.
7323        setNativeLibraryPaths(pkg);
7324    }
7325
7326    /**
7327     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7328     * i.e, so that all packages can be run inside a single process if required.
7329     *
7330     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7331     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7332     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7333     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7334     * updating a package that belongs to a shared user.
7335     *
7336     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7337     * adds unnecessary complexity.
7338     */
7339    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7340            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7341        String requiredInstructionSet = null;
7342        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7343            requiredInstructionSet = VMRuntime.getInstructionSet(
7344                     scannedPackage.applicationInfo.primaryCpuAbi);
7345        }
7346
7347        PackageSetting requirer = null;
7348        for (PackageSetting ps : packagesForUser) {
7349            // If packagesForUser contains scannedPackage, we skip it. This will happen
7350            // when scannedPackage is an update of an existing package. Without this check,
7351            // we will never be able to change the ABI of any package belonging to a shared
7352            // user, even if it's compatible with other packages.
7353            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7354                if (ps.primaryCpuAbiString == null) {
7355                    continue;
7356                }
7357
7358                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7359                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7360                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7361                    // this but there's not much we can do.
7362                    String errorMessage = "Instruction set mismatch, "
7363                            + ((requirer == null) ? "[caller]" : requirer)
7364                            + " requires " + requiredInstructionSet + " whereas " + ps
7365                            + " requires " + instructionSet;
7366                    Slog.w(TAG, errorMessage);
7367                }
7368
7369                if (requiredInstructionSet == null) {
7370                    requiredInstructionSet = instructionSet;
7371                    requirer = ps;
7372                }
7373            }
7374        }
7375
7376        if (requiredInstructionSet != null) {
7377            String adjustedAbi;
7378            if (requirer != null) {
7379                // requirer != null implies that either scannedPackage was null or that scannedPackage
7380                // did not require an ABI, in which case we have to adjust scannedPackage to match
7381                // the ABI of the set (which is the same as requirer's ABI)
7382                adjustedAbi = requirer.primaryCpuAbiString;
7383                if (scannedPackage != null) {
7384                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7385                }
7386            } else {
7387                // requirer == null implies that we're updating all ABIs in the set to
7388                // match scannedPackage.
7389                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7390            }
7391
7392            for (PackageSetting ps : packagesForUser) {
7393                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7394                    if (ps.primaryCpuAbiString != null) {
7395                        continue;
7396                    }
7397
7398                    ps.primaryCpuAbiString = adjustedAbi;
7399                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7400                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7401                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7402
7403                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7404                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7405                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7406                            ps.primaryCpuAbiString = null;
7407                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7408                            return;
7409                        } else {
7410                            mInstaller.rmdex(ps.codePathString,
7411                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7412                        }
7413                    }
7414                }
7415            }
7416        }
7417    }
7418
7419    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7420        synchronized (mPackages) {
7421            mResolverReplaced = true;
7422            // Set up information for custom user intent resolution activity.
7423            mResolveActivity.applicationInfo = pkg.applicationInfo;
7424            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7425            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7426            mResolveActivity.processName = pkg.applicationInfo.packageName;
7427            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7428            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7429                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7430            mResolveActivity.theme = 0;
7431            mResolveActivity.exported = true;
7432            mResolveActivity.enabled = true;
7433            mResolveInfo.activityInfo = mResolveActivity;
7434            mResolveInfo.priority = 0;
7435            mResolveInfo.preferredOrder = 0;
7436            mResolveInfo.match = 0;
7437            mResolveComponentName = mCustomResolverComponentName;
7438            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7439                    mResolveComponentName);
7440        }
7441    }
7442
7443    private static String calculateBundledApkRoot(final String codePathString) {
7444        final File codePath = new File(codePathString);
7445        final File codeRoot;
7446        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7447            codeRoot = Environment.getRootDirectory();
7448        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7449            codeRoot = Environment.getOemDirectory();
7450        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7451            codeRoot = Environment.getVendorDirectory();
7452        } else {
7453            // Unrecognized code path; take its top real segment as the apk root:
7454            // e.g. /something/app/blah.apk => /something
7455            try {
7456                File f = codePath.getCanonicalFile();
7457                File parent = f.getParentFile();    // non-null because codePath is a file
7458                File tmp;
7459                while ((tmp = parent.getParentFile()) != null) {
7460                    f = parent;
7461                    parent = tmp;
7462                }
7463                codeRoot = f;
7464                Slog.w(TAG, "Unrecognized code path "
7465                        + codePath + " - using " + codeRoot);
7466            } catch (IOException e) {
7467                // Can't canonicalize the code path -- shenanigans?
7468                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7469                return Environment.getRootDirectory().getPath();
7470            }
7471        }
7472        return codeRoot.getPath();
7473    }
7474
7475    /**
7476     * Derive and set the location of native libraries for the given package,
7477     * which varies depending on where and how the package was installed.
7478     */
7479    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7480        final ApplicationInfo info = pkg.applicationInfo;
7481        final String codePath = pkg.codePath;
7482        final File codeFile = new File(codePath);
7483        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7484        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7485
7486        info.nativeLibraryRootDir = null;
7487        info.nativeLibraryRootRequiresIsa = false;
7488        info.nativeLibraryDir = null;
7489        info.secondaryNativeLibraryDir = null;
7490
7491        if (isApkFile(codeFile)) {
7492            // Monolithic install
7493            if (bundledApp) {
7494                // If "/system/lib64/apkname" exists, assume that is the per-package
7495                // native library directory to use; otherwise use "/system/lib/apkname".
7496                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7497                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7498                        getPrimaryInstructionSet(info));
7499
7500                // This is a bundled system app so choose the path based on the ABI.
7501                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7502                // is just the default path.
7503                final String apkName = deriveCodePathName(codePath);
7504                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7505                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7506                        apkName).getAbsolutePath();
7507
7508                if (info.secondaryCpuAbi != null) {
7509                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7510                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7511                            secondaryLibDir, apkName).getAbsolutePath();
7512                }
7513            } else if (asecApp) {
7514                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7515                        .getAbsolutePath();
7516            } else {
7517                final String apkName = deriveCodePathName(codePath);
7518                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7519                        .getAbsolutePath();
7520            }
7521
7522            info.nativeLibraryRootRequiresIsa = false;
7523            info.nativeLibraryDir = info.nativeLibraryRootDir;
7524        } else {
7525            // Cluster install
7526            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7527            info.nativeLibraryRootRequiresIsa = true;
7528
7529            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7530                    getPrimaryInstructionSet(info)).getAbsolutePath();
7531
7532            if (info.secondaryCpuAbi != null) {
7533                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7534                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7535            }
7536        }
7537    }
7538
7539    /**
7540     * Calculate the abis and roots for a bundled app. These can uniquely
7541     * be determined from the contents of the system partition, i.e whether
7542     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7543     * of this information, and instead assume that the system was built
7544     * sensibly.
7545     */
7546    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7547                                           PackageSetting pkgSetting) {
7548        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7549
7550        // If "/system/lib64/apkname" exists, assume that is the per-package
7551        // native library directory to use; otherwise use "/system/lib/apkname".
7552        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7553        setBundledAppAbi(pkg, apkRoot, apkName);
7554        // pkgSetting might be null during rescan following uninstall of updates
7555        // to a bundled app, so accommodate that possibility.  The settings in
7556        // that case will be established later from the parsed package.
7557        //
7558        // If the settings aren't null, sync them up with what we've just derived.
7559        // note that apkRoot isn't stored in the package settings.
7560        if (pkgSetting != null) {
7561            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7562            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7563        }
7564    }
7565
7566    /**
7567     * Deduces the ABI of a bundled app and sets the relevant fields on the
7568     * parsed pkg object.
7569     *
7570     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7571     *        under which system libraries are installed.
7572     * @param apkName the name of the installed package.
7573     */
7574    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7575        final File codeFile = new File(pkg.codePath);
7576
7577        final boolean has64BitLibs;
7578        final boolean has32BitLibs;
7579        if (isApkFile(codeFile)) {
7580            // Monolithic install
7581            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7582            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7583        } else {
7584            // Cluster install
7585            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7586            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7587                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7588                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7589                has64BitLibs = (new File(rootDir, isa)).exists();
7590            } else {
7591                has64BitLibs = false;
7592            }
7593            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7594                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7595                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7596                has32BitLibs = (new File(rootDir, isa)).exists();
7597            } else {
7598                has32BitLibs = false;
7599            }
7600        }
7601
7602        if (has64BitLibs && !has32BitLibs) {
7603            // The package has 64 bit libs, but not 32 bit libs. Its primary
7604            // ABI should be 64 bit. We can safely assume here that the bundled
7605            // native libraries correspond to the most preferred ABI in the list.
7606
7607            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7608            pkg.applicationInfo.secondaryCpuAbi = null;
7609        } else if (has32BitLibs && !has64BitLibs) {
7610            // The package has 32 bit libs but not 64 bit libs. Its primary
7611            // ABI should be 32 bit.
7612
7613            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7614            pkg.applicationInfo.secondaryCpuAbi = null;
7615        } else if (has32BitLibs && has64BitLibs) {
7616            // The application has both 64 and 32 bit bundled libraries. We check
7617            // here that the app declares multiArch support, and warn if it doesn't.
7618            //
7619            // We will be lenient here and record both ABIs. The primary will be the
7620            // ABI that's higher on the list, i.e, a device that's configured to prefer
7621            // 64 bit apps will see a 64 bit primary ABI,
7622
7623            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7624                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7625            }
7626
7627            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7628                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7629                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7630            } else {
7631                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7632                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7633            }
7634        } else {
7635            pkg.applicationInfo.primaryCpuAbi = null;
7636            pkg.applicationInfo.secondaryCpuAbi = null;
7637        }
7638    }
7639
7640    private void killApplication(String pkgName, int appId, String reason) {
7641        // Request the ActivityManager to kill the process(only for existing packages)
7642        // so that we do not end up in a confused state while the user is still using the older
7643        // version of the application while the new one gets installed.
7644        IActivityManager am = ActivityManagerNative.getDefault();
7645        if (am != null) {
7646            try {
7647                am.killApplicationWithAppId(pkgName, appId, reason);
7648            } catch (RemoteException e) {
7649            }
7650        }
7651    }
7652
7653    void removePackageLI(PackageSetting ps, boolean chatty) {
7654        if (DEBUG_INSTALL) {
7655            if (chatty)
7656                Log.d(TAG, "Removing package " + ps.name);
7657        }
7658
7659        // writer
7660        synchronized (mPackages) {
7661            mPackages.remove(ps.name);
7662            final PackageParser.Package pkg = ps.pkg;
7663            if (pkg != null) {
7664                cleanPackageDataStructuresLILPw(pkg, chatty);
7665            }
7666        }
7667    }
7668
7669    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7670        if (DEBUG_INSTALL) {
7671            if (chatty)
7672                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7673        }
7674
7675        // writer
7676        synchronized (mPackages) {
7677            mPackages.remove(pkg.applicationInfo.packageName);
7678            cleanPackageDataStructuresLILPw(pkg, chatty);
7679        }
7680    }
7681
7682    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7683        int N = pkg.providers.size();
7684        StringBuilder r = null;
7685        int i;
7686        for (i=0; i<N; i++) {
7687            PackageParser.Provider p = pkg.providers.get(i);
7688            mProviders.removeProvider(p);
7689            if (p.info.authority == null) {
7690
7691                /* There was another ContentProvider with this authority when
7692                 * this app was installed so this authority is null,
7693                 * Ignore it as we don't have to unregister the provider.
7694                 */
7695                continue;
7696            }
7697            String names[] = p.info.authority.split(";");
7698            for (int j = 0; j < names.length; j++) {
7699                if (mProvidersByAuthority.get(names[j]) == p) {
7700                    mProvidersByAuthority.remove(names[j]);
7701                    if (DEBUG_REMOVE) {
7702                        if (chatty)
7703                            Log.d(TAG, "Unregistered content provider: " + names[j]
7704                                    + ", className = " + p.info.name + ", isSyncable = "
7705                                    + p.info.isSyncable);
7706                    }
7707                }
7708            }
7709            if (DEBUG_REMOVE && chatty) {
7710                if (r == null) {
7711                    r = new StringBuilder(256);
7712                } else {
7713                    r.append(' ');
7714                }
7715                r.append(p.info.name);
7716            }
7717        }
7718        if (r != null) {
7719            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7720        }
7721
7722        N = pkg.services.size();
7723        r = null;
7724        for (i=0; i<N; i++) {
7725            PackageParser.Service s = pkg.services.get(i);
7726            mServices.removeService(s);
7727            if (chatty) {
7728                if (r == null) {
7729                    r = new StringBuilder(256);
7730                } else {
7731                    r.append(' ');
7732                }
7733                r.append(s.info.name);
7734            }
7735        }
7736        if (r != null) {
7737            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7738        }
7739
7740        N = pkg.receivers.size();
7741        r = null;
7742        for (i=0; i<N; i++) {
7743            PackageParser.Activity a = pkg.receivers.get(i);
7744            mReceivers.removeActivity(a, "receiver");
7745            if (DEBUG_REMOVE && chatty) {
7746                if (r == null) {
7747                    r = new StringBuilder(256);
7748                } else {
7749                    r.append(' ');
7750                }
7751                r.append(a.info.name);
7752            }
7753        }
7754        if (r != null) {
7755            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7756        }
7757
7758        N = pkg.activities.size();
7759        r = null;
7760        for (i=0; i<N; i++) {
7761            PackageParser.Activity a = pkg.activities.get(i);
7762            mActivities.removeActivity(a, "activity");
7763            if (DEBUG_REMOVE && chatty) {
7764                if (r == null) {
7765                    r = new StringBuilder(256);
7766                } else {
7767                    r.append(' ');
7768                }
7769                r.append(a.info.name);
7770            }
7771        }
7772        if (r != null) {
7773            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7774        }
7775
7776        N = pkg.permissions.size();
7777        r = null;
7778        for (i=0; i<N; i++) {
7779            PackageParser.Permission p = pkg.permissions.get(i);
7780            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7781            if (bp == null) {
7782                bp = mSettings.mPermissionTrees.get(p.info.name);
7783            }
7784            if (bp != null && bp.perm == p) {
7785                bp.perm = null;
7786                if (DEBUG_REMOVE && chatty) {
7787                    if (r == null) {
7788                        r = new StringBuilder(256);
7789                    } else {
7790                        r.append(' ');
7791                    }
7792                    r.append(p.info.name);
7793                }
7794            }
7795            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7796                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7797                if (appOpPerms != null) {
7798                    appOpPerms.remove(pkg.packageName);
7799                }
7800            }
7801        }
7802        if (r != null) {
7803            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7804        }
7805
7806        N = pkg.requestedPermissions.size();
7807        r = null;
7808        for (i=0; i<N; i++) {
7809            String perm = pkg.requestedPermissions.get(i);
7810            BasePermission bp = mSettings.mPermissions.get(perm);
7811            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7812                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7813                if (appOpPerms != null) {
7814                    appOpPerms.remove(pkg.packageName);
7815                    if (appOpPerms.isEmpty()) {
7816                        mAppOpPermissionPackages.remove(perm);
7817                    }
7818                }
7819            }
7820        }
7821        if (r != null) {
7822            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7823        }
7824
7825        N = pkg.instrumentation.size();
7826        r = null;
7827        for (i=0; i<N; i++) {
7828            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7829            mInstrumentation.remove(a.getComponentName());
7830            if (DEBUG_REMOVE && chatty) {
7831                if (r == null) {
7832                    r = new StringBuilder(256);
7833                } else {
7834                    r.append(' ');
7835                }
7836                r.append(a.info.name);
7837            }
7838        }
7839        if (r != null) {
7840            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7841        }
7842
7843        r = null;
7844        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7845            // Only system apps can hold shared libraries.
7846            if (pkg.libraryNames != null) {
7847                for (i=0; i<pkg.libraryNames.size(); i++) {
7848                    String name = pkg.libraryNames.get(i);
7849                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7850                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7851                        mSharedLibraries.remove(name);
7852                        if (DEBUG_REMOVE && chatty) {
7853                            if (r == null) {
7854                                r = new StringBuilder(256);
7855                            } else {
7856                                r.append(' ');
7857                            }
7858                            r.append(name);
7859                        }
7860                    }
7861                }
7862            }
7863        }
7864        if (r != null) {
7865            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7866        }
7867    }
7868
7869    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7870        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7871            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7872                return true;
7873            }
7874        }
7875        return false;
7876    }
7877
7878    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7879    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7880    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7881
7882    private void updatePermissionsLPw(String changingPkg,
7883            PackageParser.Package pkgInfo, int flags) {
7884        // Make sure there are no dangling permission trees.
7885        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7886        while (it.hasNext()) {
7887            final BasePermission bp = it.next();
7888            if (bp.packageSetting == null) {
7889                // We may not yet have parsed the package, so just see if
7890                // we still know about its settings.
7891                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7892            }
7893            if (bp.packageSetting == null) {
7894                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7895                        + " from package " + bp.sourcePackage);
7896                it.remove();
7897            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7898                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7899                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7900                            + " from package " + bp.sourcePackage);
7901                    flags |= UPDATE_PERMISSIONS_ALL;
7902                    it.remove();
7903                }
7904            }
7905        }
7906
7907        // Make sure all dynamic permissions have been assigned to a package,
7908        // and make sure there are no dangling permissions.
7909        it = mSettings.mPermissions.values().iterator();
7910        while (it.hasNext()) {
7911            final BasePermission bp = it.next();
7912            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7913                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7914                        + bp.name + " pkg=" + bp.sourcePackage
7915                        + " info=" + bp.pendingInfo);
7916                if (bp.packageSetting == null && bp.pendingInfo != null) {
7917                    final BasePermission tree = findPermissionTreeLP(bp.name);
7918                    if (tree != null && tree.perm != null) {
7919                        bp.packageSetting = tree.packageSetting;
7920                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7921                                new PermissionInfo(bp.pendingInfo));
7922                        bp.perm.info.packageName = tree.perm.info.packageName;
7923                        bp.perm.info.name = bp.name;
7924                        bp.uid = tree.uid;
7925                    }
7926                }
7927            }
7928            if (bp.packageSetting == null) {
7929                // We may not yet have parsed the package, so just see if
7930                // we still know about its settings.
7931                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7932            }
7933            if (bp.packageSetting == null) {
7934                Slog.w(TAG, "Removing dangling permission: " + bp.name
7935                        + " from package " + bp.sourcePackage);
7936                it.remove();
7937            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7938                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7939                    Slog.i(TAG, "Removing old permission: " + bp.name
7940                            + " from package " + bp.sourcePackage);
7941                    flags |= UPDATE_PERMISSIONS_ALL;
7942                    it.remove();
7943                }
7944            }
7945        }
7946
7947        // Now update the permissions for all packages, in particular
7948        // replace the granted permissions of the system packages.
7949        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7950            for (PackageParser.Package pkg : mPackages.values()) {
7951                if (pkg != pkgInfo) {
7952                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7953                            changingPkg);
7954                }
7955            }
7956        }
7957
7958        if (pkgInfo != null) {
7959            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7960        }
7961    }
7962
7963    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7964            String packageOfInterest) {
7965        // IMPORTANT: There are two types of permissions: install and runtime.
7966        // Install time permissions are granted when the app is installed to
7967        // all device users and users added in the future. Runtime permissions
7968        // are granted at runtime explicitly to specific users. Normal and signature
7969        // protected permissions are install time permissions. Dangerous permissions
7970        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7971        // otherwise they are runtime permissions. This function does not manage
7972        // runtime permissions except for the case an app targeting Lollipop MR1
7973        // being upgraded to target a newer SDK, in which case dangerous permissions
7974        // are transformed from install time to runtime ones.
7975
7976        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7977        if (ps == null) {
7978            return;
7979        }
7980
7981        PermissionsState permissionsState = ps.getPermissionsState();
7982        PermissionsState origPermissions = permissionsState;
7983
7984        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7985
7986        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
7987
7988        boolean changedInstallPermission = false;
7989
7990        if (replace) {
7991            ps.installPermissionsFixed = false;
7992            if (!ps.isSharedUser()) {
7993                origPermissions = new PermissionsState(permissionsState);
7994                permissionsState.reset();
7995            }
7996        }
7997
7998        permissionsState.setGlobalGids(mGlobalGids);
7999
8000        final int N = pkg.requestedPermissions.size();
8001        for (int i=0; i<N; i++) {
8002            final String name = pkg.requestedPermissions.get(i);
8003            final BasePermission bp = mSettings.mPermissions.get(name);
8004
8005            if (DEBUG_INSTALL) {
8006                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8007            }
8008
8009            if (bp == null || bp.packageSetting == null) {
8010                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8011                    Slog.w(TAG, "Unknown permission " + name
8012                            + " in package " + pkg.packageName);
8013                }
8014                continue;
8015            }
8016
8017            final String perm = bp.name;
8018            boolean allowedSig = false;
8019            int grant = GRANT_DENIED;
8020
8021            // Keep track of app op permissions.
8022            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8023                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8024                if (pkgs == null) {
8025                    pkgs = new ArraySet<>();
8026                    mAppOpPermissionPackages.put(bp.name, pkgs);
8027                }
8028                pkgs.add(pkg.packageName);
8029            }
8030
8031            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8032            switch (level) {
8033                case PermissionInfo.PROTECTION_NORMAL: {
8034                    // For all apps normal permissions are install time ones.
8035                    grant = GRANT_INSTALL;
8036                } break;
8037
8038                case PermissionInfo.PROTECTION_DANGEROUS: {
8039                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8040                        // For legacy apps dangerous permissions are install time ones.
8041                        grant = GRANT_INSTALL_LEGACY;
8042                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8043                        // For legacy apps that became modern, install becomes runtime.
8044                        grant = GRANT_UPGRADE;
8045                    } else {
8046                        // For modern apps keep runtime permissions unchanged.
8047                        grant = GRANT_RUNTIME;
8048                    }
8049                } break;
8050
8051                case PermissionInfo.PROTECTION_SIGNATURE: {
8052                    // For all apps signature permissions are install time ones.
8053                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8054                    if (allowedSig) {
8055                        grant = GRANT_INSTALL;
8056                    }
8057                } break;
8058            }
8059
8060            if (DEBUG_INSTALL) {
8061                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8062            }
8063
8064            if (grant != GRANT_DENIED) {
8065                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8066                    // If this is an existing, non-system package, then
8067                    // we can't add any new permissions to it.
8068                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8069                        // Except...  if this is a permission that was added
8070                        // to the platform (note: need to only do this when
8071                        // updating the platform).
8072                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8073                            grant = GRANT_DENIED;
8074                        }
8075                    }
8076                }
8077
8078                switch (grant) {
8079                    case GRANT_INSTALL: {
8080                        // Revoke this as runtime permission to handle the case of
8081                        // a runtime permission being downgraded to an install one.
8082                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8083                            if (origPermissions.getRuntimePermissionState(
8084                                    bp.name, userId) != null) {
8085                                // Revoke the runtime permission and clear the flags.
8086                                origPermissions.revokeRuntimePermission(bp, userId);
8087                                origPermissions.updatePermissionFlags(bp, userId,
8088                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8089                                // If we revoked a permission permission, we have to write.
8090                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8091                                        changedRuntimePermissionUserIds, userId);
8092                            }
8093                        }
8094                        // Grant an install permission.
8095                        if (permissionsState.grantInstallPermission(bp) !=
8096                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8097                            changedInstallPermission = true;
8098                        }
8099                    } break;
8100
8101                    case GRANT_INSTALL_LEGACY: {
8102                        // Grant an install permission.
8103                        if (permissionsState.grantInstallPermission(bp) !=
8104                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8105                            changedInstallPermission = true;
8106                        }
8107                    } break;
8108
8109                    case GRANT_RUNTIME: {
8110                        // Grant previously granted runtime permissions.
8111                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8112                            PermissionState permissionState = origPermissions
8113                                    .getRuntimePermissionState(bp.name, userId);
8114                            final int flags = permissionState != null
8115                                    ? permissionState.getFlags() : 0;
8116                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8117                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8118                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8119                                    // If we cannot put the permission as it was, we have to write.
8120                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8121                                            changedRuntimePermissionUserIds, userId);
8122                                }
8123                            }
8124                            // Propagate the permission flags.
8125                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8126                        }
8127                    } break;
8128
8129                    case GRANT_UPGRADE: {
8130                        // Grant runtime permissions for a previously held install permission.
8131                        PermissionState permissionState = origPermissions
8132                                .getInstallPermissionState(bp.name);
8133                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8134
8135                        if (origPermissions.revokeInstallPermission(bp)
8136                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8137                            // We will be transferring the permission flags, so clear them.
8138                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8139                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8140                            changedInstallPermission = true;
8141                        }
8142
8143                        // If the permission is not to be promoted to runtime we ignore it and
8144                        // also its other flags as they are not applicable to install permissions.
8145                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8146                            for (int userId : currentUserIds) {
8147                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8148                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8149                                    // Transfer the permission flags.
8150                                    permissionsState.updatePermissionFlags(bp, userId,
8151                                            flags, flags);
8152                                    // If we granted the permission, we have to write.
8153                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8154                                            changedRuntimePermissionUserIds, userId);
8155                                }
8156                            }
8157                        }
8158                    } break;
8159
8160                    default: {
8161                        if (packageOfInterest == null
8162                                || packageOfInterest.equals(pkg.packageName)) {
8163                            Slog.w(TAG, "Not granting permission " + perm
8164                                    + " to package " + pkg.packageName
8165                                    + " because it was previously installed without");
8166                        }
8167                    } break;
8168                }
8169            } else {
8170                if (permissionsState.revokeInstallPermission(bp) !=
8171                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8172                    // Also drop the permission flags.
8173                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8174                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8175                    changedInstallPermission = true;
8176                    Slog.i(TAG, "Un-granting permission " + perm
8177                            + " from package " + pkg.packageName
8178                            + " (protectionLevel=" + bp.protectionLevel
8179                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8180                            + ")");
8181                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8182                    // Don't print warning for app op permissions, since it is fine for them
8183                    // not to be granted, there is a UI for the user to decide.
8184                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8185                        Slog.w(TAG, "Not granting permission " + perm
8186                                + " to package " + pkg.packageName
8187                                + " (protectionLevel=" + bp.protectionLevel
8188                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8189                                + ")");
8190                    }
8191                }
8192            }
8193        }
8194
8195        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8196                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8197            // This is the first that we have heard about this package, so the
8198            // permissions we have now selected are fixed until explicitly
8199            // changed.
8200            ps.installPermissionsFixed = true;
8201        }
8202
8203        // Persist the runtime permissions state for users with changes.
8204        for (int userId : changedRuntimePermissionUserIds) {
8205            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8206        }
8207    }
8208
8209    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8210        boolean allowed = false;
8211        final int NP = PackageParser.NEW_PERMISSIONS.length;
8212        for (int ip=0; ip<NP; ip++) {
8213            final PackageParser.NewPermissionInfo npi
8214                    = PackageParser.NEW_PERMISSIONS[ip];
8215            if (npi.name.equals(perm)
8216                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8217                allowed = true;
8218                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8219                        + pkg.packageName);
8220                break;
8221            }
8222        }
8223        return allowed;
8224    }
8225
8226    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8227            BasePermission bp, PermissionsState origPermissions) {
8228        boolean allowed;
8229        allowed = (compareSignatures(
8230                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8231                        == PackageManager.SIGNATURE_MATCH)
8232                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8233                        == PackageManager.SIGNATURE_MATCH);
8234        if (!allowed && (bp.protectionLevel
8235                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
8236            if (isSystemApp(pkg)) {
8237                // For updated system applications, a system permission
8238                // is granted only if it had been defined by the original application.
8239                if (pkg.isUpdatedSystemApp()) {
8240                    final PackageSetting sysPs = mSettings
8241                            .getDisabledSystemPkgLPr(pkg.packageName);
8242                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8243                        // If the original was granted this permission, we take
8244                        // that grant decision as read and propagate it to the
8245                        // update.
8246                        if (sysPs.isPrivileged()) {
8247                            allowed = true;
8248                        }
8249                    } else {
8250                        // The system apk may have been updated with an older
8251                        // version of the one on the data partition, but which
8252                        // granted a new system permission that it didn't have
8253                        // before.  In this case we do want to allow the app to
8254                        // now get the new permission if the ancestral apk is
8255                        // privileged to get it.
8256                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8257                            for (int j=0;
8258                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8259                                if (perm.equals(
8260                                        sysPs.pkg.requestedPermissions.get(j))) {
8261                                    allowed = true;
8262                                    break;
8263                                }
8264                            }
8265                        }
8266                    }
8267                } else {
8268                    allowed = isPrivilegedApp(pkg);
8269                }
8270            }
8271        }
8272        if (!allowed && (bp.protectionLevel
8273                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8274            // For development permissions, a development permission
8275            // is granted only if it was already granted.
8276            allowed = origPermissions.hasInstallPermission(perm);
8277        }
8278        return allowed;
8279    }
8280
8281    final class ActivityIntentResolver
8282            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8283        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8284                boolean defaultOnly, int userId) {
8285            if (!sUserManager.exists(userId)) return null;
8286            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8287            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8288        }
8289
8290        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8291                int userId) {
8292            if (!sUserManager.exists(userId)) return null;
8293            mFlags = flags;
8294            return super.queryIntent(intent, resolvedType,
8295                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8296        }
8297
8298        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8299                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8300            if (!sUserManager.exists(userId)) return null;
8301            if (packageActivities == null) {
8302                return null;
8303            }
8304            mFlags = flags;
8305            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8306            final int N = packageActivities.size();
8307            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8308                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8309
8310            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8311            for (int i = 0; i < N; ++i) {
8312                intentFilters = packageActivities.get(i).intents;
8313                if (intentFilters != null && intentFilters.size() > 0) {
8314                    PackageParser.ActivityIntentInfo[] array =
8315                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8316                    intentFilters.toArray(array);
8317                    listCut.add(array);
8318                }
8319            }
8320            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8321        }
8322
8323        public final void addActivity(PackageParser.Activity a, String type) {
8324            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8325            mActivities.put(a.getComponentName(), a);
8326            if (DEBUG_SHOW_INFO)
8327                Log.v(
8328                TAG, "  " + type + " " +
8329                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8330            if (DEBUG_SHOW_INFO)
8331                Log.v(TAG, "    Class=" + a.info.name);
8332            final int NI = a.intents.size();
8333            for (int j=0; j<NI; j++) {
8334                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8335                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8336                    intent.setPriority(0);
8337                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8338                            + a.className + " with priority > 0, forcing to 0");
8339                }
8340                if (DEBUG_SHOW_INFO) {
8341                    Log.v(TAG, "    IntentFilter:");
8342                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8343                }
8344                if (!intent.debugCheck()) {
8345                    Log.w(TAG, "==> For Activity " + a.info.name);
8346                }
8347                addFilter(intent);
8348            }
8349        }
8350
8351        public final void removeActivity(PackageParser.Activity a, String type) {
8352            mActivities.remove(a.getComponentName());
8353            if (DEBUG_SHOW_INFO) {
8354                Log.v(TAG, "  " + type + " "
8355                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8356                                : a.info.name) + ":");
8357                Log.v(TAG, "    Class=" + a.info.name);
8358            }
8359            final int NI = a.intents.size();
8360            for (int j=0; j<NI; j++) {
8361                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8362                if (DEBUG_SHOW_INFO) {
8363                    Log.v(TAG, "    IntentFilter:");
8364                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8365                }
8366                removeFilter(intent);
8367            }
8368        }
8369
8370        @Override
8371        protected boolean allowFilterResult(
8372                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8373            ActivityInfo filterAi = filter.activity.info;
8374            for (int i=dest.size()-1; i>=0; i--) {
8375                ActivityInfo destAi = dest.get(i).activityInfo;
8376                if (destAi.name == filterAi.name
8377                        && destAi.packageName == filterAi.packageName) {
8378                    return false;
8379                }
8380            }
8381            return true;
8382        }
8383
8384        @Override
8385        protected ActivityIntentInfo[] newArray(int size) {
8386            return new ActivityIntentInfo[size];
8387        }
8388
8389        @Override
8390        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8391            if (!sUserManager.exists(userId)) return true;
8392            PackageParser.Package p = filter.activity.owner;
8393            if (p != null) {
8394                PackageSetting ps = (PackageSetting)p.mExtras;
8395                if (ps != null) {
8396                    // System apps are never considered stopped for purposes of
8397                    // filtering, because there may be no way for the user to
8398                    // actually re-launch them.
8399                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8400                            && ps.getStopped(userId);
8401                }
8402            }
8403            return false;
8404        }
8405
8406        @Override
8407        protected boolean isPackageForFilter(String packageName,
8408                PackageParser.ActivityIntentInfo info) {
8409            return packageName.equals(info.activity.owner.packageName);
8410        }
8411
8412        @Override
8413        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8414                int match, int userId) {
8415            if (!sUserManager.exists(userId)) return null;
8416            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8417                return null;
8418            }
8419            final PackageParser.Activity activity = info.activity;
8420            if (mSafeMode && (activity.info.applicationInfo.flags
8421                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8422                return null;
8423            }
8424            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8425            if (ps == null) {
8426                return null;
8427            }
8428            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8429                    ps.readUserState(userId), userId);
8430            if (ai == null) {
8431                return null;
8432            }
8433            final ResolveInfo res = new ResolveInfo();
8434            res.activityInfo = ai;
8435            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8436                res.filter = info;
8437            }
8438            if (info != null) {
8439                res.handleAllWebDataURI = info.handleAllWebDataURI();
8440            }
8441            res.priority = info.getPriority();
8442            res.preferredOrder = activity.owner.mPreferredOrder;
8443            //System.out.println("Result: " + res.activityInfo.className +
8444            //                   " = " + res.priority);
8445            res.match = match;
8446            res.isDefault = info.hasDefault;
8447            res.labelRes = info.labelRes;
8448            res.nonLocalizedLabel = info.nonLocalizedLabel;
8449            if (userNeedsBadging(userId)) {
8450                res.noResourceId = true;
8451            } else {
8452                res.icon = info.icon;
8453            }
8454            res.iconResourceId = info.icon;
8455            res.system = res.activityInfo.applicationInfo.isSystemApp();
8456            return res;
8457        }
8458
8459        @Override
8460        protected void sortResults(List<ResolveInfo> results) {
8461            Collections.sort(results, mResolvePrioritySorter);
8462        }
8463
8464        @Override
8465        protected void dumpFilter(PrintWriter out, String prefix,
8466                PackageParser.ActivityIntentInfo filter) {
8467            out.print(prefix); out.print(
8468                    Integer.toHexString(System.identityHashCode(filter.activity)));
8469                    out.print(' ');
8470                    filter.activity.printComponentShortName(out);
8471                    out.print(" filter ");
8472                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8473        }
8474
8475        @Override
8476        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8477            return filter.activity;
8478        }
8479
8480        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8481            PackageParser.Activity activity = (PackageParser.Activity)label;
8482            out.print(prefix); out.print(
8483                    Integer.toHexString(System.identityHashCode(activity)));
8484                    out.print(' ');
8485                    activity.printComponentShortName(out);
8486            if (count > 1) {
8487                out.print(" ("); out.print(count); out.print(" filters)");
8488            }
8489            out.println();
8490        }
8491
8492//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8493//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8494//            final List<ResolveInfo> retList = Lists.newArrayList();
8495//            while (i.hasNext()) {
8496//                final ResolveInfo resolveInfo = i.next();
8497//                if (isEnabledLP(resolveInfo.activityInfo)) {
8498//                    retList.add(resolveInfo);
8499//                }
8500//            }
8501//            return retList;
8502//        }
8503
8504        // Keys are String (activity class name), values are Activity.
8505        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8506                = new ArrayMap<ComponentName, PackageParser.Activity>();
8507        private int mFlags;
8508    }
8509
8510    private final class ServiceIntentResolver
8511            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8512        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8513                boolean defaultOnly, int userId) {
8514            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8515            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8516        }
8517
8518        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8519                int userId) {
8520            if (!sUserManager.exists(userId)) return null;
8521            mFlags = flags;
8522            return super.queryIntent(intent, resolvedType,
8523                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8524        }
8525
8526        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8527                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8528            if (!sUserManager.exists(userId)) return null;
8529            if (packageServices == null) {
8530                return null;
8531            }
8532            mFlags = flags;
8533            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8534            final int N = packageServices.size();
8535            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8536                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8537
8538            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8539            for (int i = 0; i < N; ++i) {
8540                intentFilters = packageServices.get(i).intents;
8541                if (intentFilters != null && intentFilters.size() > 0) {
8542                    PackageParser.ServiceIntentInfo[] array =
8543                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8544                    intentFilters.toArray(array);
8545                    listCut.add(array);
8546                }
8547            }
8548            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8549        }
8550
8551        public final void addService(PackageParser.Service s) {
8552            mServices.put(s.getComponentName(), s);
8553            if (DEBUG_SHOW_INFO) {
8554                Log.v(TAG, "  "
8555                        + (s.info.nonLocalizedLabel != null
8556                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8557                Log.v(TAG, "    Class=" + s.info.name);
8558            }
8559            final int NI = s.intents.size();
8560            int j;
8561            for (j=0; j<NI; j++) {
8562                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8563                if (DEBUG_SHOW_INFO) {
8564                    Log.v(TAG, "    IntentFilter:");
8565                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8566                }
8567                if (!intent.debugCheck()) {
8568                    Log.w(TAG, "==> For Service " + s.info.name);
8569                }
8570                addFilter(intent);
8571            }
8572        }
8573
8574        public final void removeService(PackageParser.Service s) {
8575            mServices.remove(s.getComponentName());
8576            if (DEBUG_SHOW_INFO) {
8577                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8578                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8579                Log.v(TAG, "    Class=" + s.info.name);
8580            }
8581            final int NI = s.intents.size();
8582            int j;
8583            for (j=0; j<NI; j++) {
8584                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8585                if (DEBUG_SHOW_INFO) {
8586                    Log.v(TAG, "    IntentFilter:");
8587                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8588                }
8589                removeFilter(intent);
8590            }
8591        }
8592
8593        @Override
8594        protected boolean allowFilterResult(
8595                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8596            ServiceInfo filterSi = filter.service.info;
8597            for (int i=dest.size()-1; i>=0; i--) {
8598                ServiceInfo destAi = dest.get(i).serviceInfo;
8599                if (destAi.name == filterSi.name
8600                        && destAi.packageName == filterSi.packageName) {
8601                    return false;
8602                }
8603            }
8604            return true;
8605        }
8606
8607        @Override
8608        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8609            return new PackageParser.ServiceIntentInfo[size];
8610        }
8611
8612        @Override
8613        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8614            if (!sUserManager.exists(userId)) return true;
8615            PackageParser.Package p = filter.service.owner;
8616            if (p != null) {
8617                PackageSetting ps = (PackageSetting)p.mExtras;
8618                if (ps != null) {
8619                    // System apps are never considered stopped for purposes of
8620                    // filtering, because there may be no way for the user to
8621                    // actually re-launch them.
8622                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8623                            && ps.getStopped(userId);
8624                }
8625            }
8626            return false;
8627        }
8628
8629        @Override
8630        protected boolean isPackageForFilter(String packageName,
8631                PackageParser.ServiceIntentInfo info) {
8632            return packageName.equals(info.service.owner.packageName);
8633        }
8634
8635        @Override
8636        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8637                int match, int userId) {
8638            if (!sUserManager.exists(userId)) return null;
8639            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8640            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8641                return null;
8642            }
8643            final PackageParser.Service service = info.service;
8644            if (mSafeMode && (service.info.applicationInfo.flags
8645                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8646                return null;
8647            }
8648            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8649            if (ps == null) {
8650                return null;
8651            }
8652            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8653                    ps.readUserState(userId), userId);
8654            if (si == null) {
8655                return null;
8656            }
8657            final ResolveInfo res = new ResolveInfo();
8658            res.serviceInfo = si;
8659            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8660                res.filter = filter;
8661            }
8662            res.priority = info.getPriority();
8663            res.preferredOrder = service.owner.mPreferredOrder;
8664            res.match = match;
8665            res.isDefault = info.hasDefault;
8666            res.labelRes = info.labelRes;
8667            res.nonLocalizedLabel = info.nonLocalizedLabel;
8668            res.icon = info.icon;
8669            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8670            return res;
8671        }
8672
8673        @Override
8674        protected void sortResults(List<ResolveInfo> results) {
8675            Collections.sort(results, mResolvePrioritySorter);
8676        }
8677
8678        @Override
8679        protected void dumpFilter(PrintWriter out, String prefix,
8680                PackageParser.ServiceIntentInfo filter) {
8681            out.print(prefix); out.print(
8682                    Integer.toHexString(System.identityHashCode(filter.service)));
8683                    out.print(' ');
8684                    filter.service.printComponentShortName(out);
8685                    out.print(" filter ");
8686                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8687        }
8688
8689        @Override
8690        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8691            return filter.service;
8692        }
8693
8694        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8695            PackageParser.Service service = (PackageParser.Service)label;
8696            out.print(prefix); out.print(
8697                    Integer.toHexString(System.identityHashCode(service)));
8698                    out.print(' ');
8699                    service.printComponentShortName(out);
8700            if (count > 1) {
8701                out.print(" ("); out.print(count); out.print(" filters)");
8702            }
8703            out.println();
8704        }
8705
8706//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8707//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8708//            final List<ResolveInfo> retList = Lists.newArrayList();
8709//            while (i.hasNext()) {
8710//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8711//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8712//                    retList.add(resolveInfo);
8713//                }
8714//            }
8715//            return retList;
8716//        }
8717
8718        // Keys are String (activity class name), values are Activity.
8719        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8720                = new ArrayMap<ComponentName, PackageParser.Service>();
8721        private int mFlags;
8722    };
8723
8724    private final class ProviderIntentResolver
8725            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8726        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8727                boolean defaultOnly, int userId) {
8728            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8729            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8730        }
8731
8732        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8733                int userId) {
8734            if (!sUserManager.exists(userId))
8735                return null;
8736            mFlags = flags;
8737            return super.queryIntent(intent, resolvedType,
8738                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8739        }
8740
8741        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8742                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8743            if (!sUserManager.exists(userId))
8744                return null;
8745            if (packageProviders == null) {
8746                return null;
8747            }
8748            mFlags = flags;
8749            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8750            final int N = packageProviders.size();
8751            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8752                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8753
8754            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8755            for (int i = 0; i < N; ++i) {
8756                intentFilters = packageProviders.get(i).intents;
8757                if (intentFilters != null && intentFilters.size() > 0) {
8758                    PackageParser.ProviderIntentInfo[] array =
8759                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8760                    intentFilters.toArray(array);
8761                    listCut.add(array);
8762                }
8763            }
8764            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8765        }
8766
8767        public final void addProvider(PackageParser.Provider p) {
8768            if (mProviders.containsKey(p.getComponentName())) {
8769                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8770                return;
8771            }
8772
8773            mProviders.put(p.getComponentName(), p);
8774            if (DEBUG_SHOW_INFO) {
8775                Log.v(TAG, "  "
8776                        + (p.info.nonLocalizedLabel != null
8777                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8778                Log.v(TAG, "    Class=" + p.info.name);
8779            }
8780            final int NI = p.intents.size();
8781            int j;
8782            for (j = 0; j < NI; j++) {
8783                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8784                if (DEBUG_SHOW_INFO) {
8785                    Log.v(TAG, "    IntentFilter:");
8786                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8787                }
8788                if (!intent.debugCheck()) {
8789                    Log.w(TAG, "==> For Provider " + p.info.name);
8790                }
8791                addFilter(intent);
8792            }
8793        }
8794
8795        public final void removeProvider(PackageParser.Provider p) {
8796            mProviders.remove(p.getComponentName());
8797            if (DEBUG_SHOW_INFO) {
8798                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8799                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8800                Log.v(TAG, "    Class=" + p.info.name);
8801            }
8802            final int NI = p.intents.size();
8803            int j;
8804            for (j = 0; j < NI; j++) {
8805                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8806                if (DEBUG_SHOW_INFO) {
8807                    Log.v(TAG, "    IntentFilter:");
8808                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8809                }
8810                removeFilter(intent);
8811            }
8812        }
8813
8814        @Override
8815        protected boolean allowFilterResult(
8816                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8817            ProviderInfo filterPi = filter.provider.info;
8818            for (int i = dest.size() - 1; i >= 0; i--) {
8819                ProviderInfo destPi = dest.get(i).providerInfo;
8820                if (destPi.name == filterPi.name
8821                        && destPi.packageName == filterPi.packageName) {
8822                    return false;
8823                }
8824            }
8825            return true;
8826        }
8827
8828        @Override
8829        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8830            return new PackageParser.ProviderIntentInfo[size];
8831        }
8832
8833        @Override
8834        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8835            if (!sUserManager.exists(userId))
8836                return true;
8837            PackageParser.Package p = filter.provider.owner;
8838            if (p != null) {
8839                PackageSetting ps = (PackageSetting) p.mExtras;
8840                if (ps != null) {
8841                    // System apps are never considered stopped for purposes of
8842                    // filtering, because there may be no way for the user to
8843                    // actually re-launch them.
8844                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8845                            && ps.getStopped(userId);
8846                }
8847            }
8848            return false;
8849        }
8850
8851        @Override
8852        protected boolean isPackageForFilter(String packageName,
8853                PackageParser.ProviderIntentInfo info) {
8854            return packageName.equals(info.provider.owner.packageName);
8855        }
8856
8857        @Override
8858        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8859                int match, int userId) {
8860            if (!sUserManager.exists(userId))
8861                return null;
8862            final PackageParser.ProviderIntentInfo info = filter;
8863            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8864                return null;
8865            }
8866            final PackageParser.Provider provider = info.provider;
8867            if (mSafeMode && (provider.info.applicationInfo.flags
8868                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8869                return null;
8870            }
8871            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8872            if (ps == null) {
8873                return null;
8874            }
8875            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8876                    ps.readUserState(userId), userId);
8877            if (pi == null) {
8878                return null;
8879            }
8880            final ResolveInfo res = new ResolveInfo();
8881            res.providerInfo = pi;
8882            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8883                res.filter = filter;
8884            }
8885            res.priority = info.getPriority();
8886            res.preferredOrder = provider.owner.mPreferredOrder;
8887            res.match = match;
8888            res.isDefault = info.hasDefault;
8889            res.labelRes = info.labelRes;
8890            res.nonLocalizedLabel = info.nonLocalizedLabel;
8891            res.icon = info.icon;
8892            res.system = res.providerInfo.applicationInfo.isSystemApp();
8893            return res;
8894        }
8895
8896        @Override
8897        protected void sortResults(List<ResolveInfo> results) {
8898            Collections.sort(results, mResolvePrioritySorter);
8899        }
8900
8901        @Override
8902        protected void dumpFilter(PrintWriter out, String prefix,
8903                PackageParser.ProviderIntentInfo filter) {
8904            out.print(prefix);
8905            out.print(
8906                    Integer.toHexString(System.identityHashCode(filter.provider)));
8907            out.print(' ');
8908            filter.provider.printComponentShortName(out);
8909            out.print(" filter ");
8910            out.println(Integer.toHexString(System.identityHashCode(filter)));
8911        }
8912
8913        @Override
8914        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8915            return filter.provider;
8916        }
8917
8918        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8919            PackageParser.Provider provider = (PackageParser.Provider)label;
8920            out.print(prefix); out.print(
8921                    Integer.toHexString(System.identityHashCode(provider)));
8922                    out.print(' ');
8923                    provider.printComponentShortName(out);
8924            if (count > 1) {
8925                out.print(" ("); out.print(count); out.print(" filters)");
8926            }
8927            out.println();
8928        }
8929
8930        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8931                = new ArrayMap<ComponentName, PackageParser.Provider>();
8932        private int mFlags;
8933    };
8934
8935    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8936            new Comparator<ResolveInfo>() {
8937        public int compare(ResolveInfo r1, ResolveInfo r2) {
8938            int v1 = r1.priority;
8939            int v2 = r2.priority;
8940            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8941            if (v1 != v2) {
8942                return (v1 > v2) ? -1 : 1;
8943            }
8944            v1 = r1.preferredOrder;
8945            v2 = r2.preferredOrder;
8946            if (v1 != v2) {
8947                return (v1 > v2) ? -1 : 1;
8948            }
8949            if (r1.isDefault != r2.isDefault) {
8950                return r1.isDefault ? -1 : 1;
8951            }
8952            v1 = r1.match;
8953            v2 = r2.match;
8954            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8955            if (v1 != v2) {
8956                return (v1 > v2) ? -1 : 1;
8957            }
8958            if (r1.system != r2.system) {
8959                return r1.system ? -1 : 1;
8960            }
8961            return 0;
8962        }
8963    };
8964
8965    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8966            new Comparator<ProviderInfo>() {
8967        public int compare(ProviderInfo p1, ProviderInfo p2) {
8968            final int v1 = p1.initOrder;
8969            final int v2 = p2.initOrder;
8970            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8971        }
8972    };
8973
8974    final void sendPackageBroadcast(final String action, final String pkg,
8975            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
8976            final int[] userIds) {
8977        mHandler.post(new Runnable() {
8978            @Override
8979            public void run() {
8980                try {
8981                    final IActivityManager am = ActivityManagerNative.getDefault();
8982                    if (am == null) return;
8983                    final int[] resolvedUserIds;
8984                    if (userIds == null) {
8985                        resolvedUserIds = am.getRunningUserIds();
8986                    } else {
8987                        resolvedUserIds = userIds;
8988                    }
8989                    for (int id : resolvedUserIds) {
8990                        final Intent intent = new Intent(action,
8991                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
8992                        if (extras != null) {
8993                            intent.putExtras(extras);
8994                        }
8995                        if (targetPkg != null) {
8996                            intent.setPackage(targetPkg);
8997                        }
8998                        // Modify the UID when posting to other users
8999                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9000                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9001                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9002                            intent.putExtra(Intent.EXTRA_UID, uid);
9003                        }
9004                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9005                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9006                        if (DEBUG_BROADCASTS) {
9007                            RuntimeException here = new RuntimeException("here");
9008                            here.fillInStackTrace();
9009                            Slog.d(TAG, "Sending to user " + id + ": "
9010                                    + intent.toShortString(false, true, false, false)
9011                                    + " " + intent.getExtras(), here);
9012                        }
9013                        am.broadcastIntent(null, intent, null, finishedReceiver,
9014                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9015                                null, finishedReceiver != null, false, id);
9016                    }
9017                } catch (RemoteException ex) {
9018                }
9019            }
9020        });
9021    }
9022
9023    /**
9024     * Check if the external storage media is available. This is true if there
9025     * is a mounted external storage medium or if the external storage is
9026     * emulated.
9027     */
9028    private boolean isExternalMediaAvailable() {
9029        return mMediaMounted || Environment.isExternalStorageEmulated();
9030    }
9031
9032    @Override
9033    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9034        // writer
9035        synchronized (mPackages) {
9036            if (!isExternalMediaAvailable()) {
9037                // If the external storage is no longer mounted at this point,
9038                // the caller may not have been able to delete all of this
9039                // packages files and can not delete any more.  Bail.
9040                return null;
9041            }
9042            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9043            if (lastPackage != null) {
9044                pkgs.remove(lastPackage);
9045            }
9046            if (pkgs.size() > 0) {
9047                return pkgs.get(0);
9048            }
9049        }
9050        return null;
9051    }
9052
9053    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9054        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9055                userId, andCode ? 1 : 0, packageName);
9056        if (mSystemReady) {
9057            msg.sendToTarget();
9058        } else {
9059            if (mPostSystemReadyMessages == null) {
9060                mPostSystemReadyMessages = new ArrayList<>();
9061            }
9062            mPostSystemReadyMessages.add(msg);
9063        }
9064    }
9065
9066    void startCleaningPackages() {
9067        // reader
9068        synchronized (mPackages) {
9069            if (!isExternalMediaAvailable()) {
9070                return;
9071            }
9072            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9073                return;
9074            }
9075        }
9076        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9077        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9078        IActivityManager am = ActivityManagerNative.getDefault();
9079        if (am != null) {
9080            try {
9081                am.startService(null, intent, null, UserHandle.USER_OWNER);
9082            } catch (RemoteException e) {
9083            }
9084        }
9085    }
9086
9087    @Override
9088    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9089            int installFlags, String installerPackageName, VerificationParams verificationParams,
9090            String packageAbiOverride) {
9091        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9092                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9093    }
9094
9095    @Override
9096    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9097            int installFlags, String installerPackageName, VerificationParams verificationParams,
9098            String packageAbiOverride, int userId) {
9099        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9100
9101        final int callingUid = Binder.getCallingUid();
9102        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9103
9104        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9105            try {
9106                if (observer != null) {
9107                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9108                }
9109            } catch (RemoteException re) {
9110            }
9111            return;
9112        }
9113
9114        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9115            installFlags |= PackageManager.INSTALL_FROM_ADB;
9116
9117        } else {
9118            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9119            // about installerPackageName.
9120
9121            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9122            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9123        }
9124
9125        UserHandle user;
9126        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9127            user = UserHandle.ALL;
9128        } else {
9129            user = new UserHandle(userId);
9130        }
9131
9132        // Only system components can circumvent runtime permissions when installing.
9133        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9134                && mContext.checkCallingOrSelfPermission(Manifest.permission
9135                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9136            throw new SecurityException("You need the "
9137                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9138                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9139        }
9140
9141        verificationParams.setInstallerUid(callingUid);
9142
9143        final File originFile = new File(originPath);
9144        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9145
9146        final Message msg = mHandler.obtainMessage(INIT_COPY);
9147        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9148                null, verificationParams, user, packageAbiOverride);
9149        mHandler.sendMessage(msg);
9150    }
9151
9152    void installStage(String packageName, File stagedDir, String stagedCid,
9153            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9154            String installerPackageName, int installerUid, UserHandle user) {
9155        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9156                params.referrerUri, installerUid, null);
9157        verifParams.setInstallerUid(installerUid);
9158
9159        final OriginInfo origin;
9160        if (stagedDir != null) {
9161            origin = OriginInfo.fromStagedFile(stagedDir);
9162        } else {
9163            origin = OriginInfo.fromStagedContainer(stagedCid);
9164        }
9165
9166        final Message msg = mHandler.obtainMessage(INIT_COPY);
9167        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9168                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9169        mHandler.sendMessage(msg);
9170    }
9171
9172    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9173        Bundle extras = new Bundle(1);
9174        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9175
9176        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9177                packageName, extras, null, null, new int[] {userId});
9178        try {
9179            IActivityManager am = ActivityManagerNative.getDefault();
9180            final boolean isSystem =
9181                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9182            if (isSystem && am.isUserRunning(userId, false)) {
9183                // The just-installed/enabled app is bundled on the system, so presumed
9184                // to be able to run automatically without needing an explicit launch.
9185                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9186                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9187                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9188                        .setPackage(packageName);
9189                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9190                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9191            }
9192        } catch (RemoteException e) {
9193            // shouldn't happen
9194            Slog.w(TAG, "Unable to bootstrap installed package", e);
9195        }
9196    }
9197
9198    @Override
9199    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9200            int userId) {
9201        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9202        PackageSetting pkgSetting;
9203        final int uid = Binder.getCallingUid();
9204        enforceCrossUserPermission(uid, userId, true, true,
9205                "setApplicationHiddenSetting for user " + userId);
9206
9207        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9208            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9209            return false;
9210        }
9211
9212        long callingId = Binder.clearCallingIdentity();
9213        try {
9214            boolean sendAdded = false;
9215            boolean sendRemoved = false;
9216            // writer
9217            synchronized (mPackages) {
9218                pkgSetting = mSettings.mPackages.get(packageName);
9219                if (pkgSetting == null) {
9220                    return false;
9221                }
9222                if (pkgSetting.getHidden(userId) != hidden) {
9223                    pkgSetting.setHidden(hidden, userId);
9224                    mSettings.writePackageRestrictionsLPr(userId);
9225                    if (hidden) {
9226                        sendRemoved = true;
9227                    } else {
9228                        sendAdded = true;
9229                    }
9230                }
9231            }
9232            if (sendAdded) {
9233                sendPackageAddedForUser(packageName, pkgSetting, userId);
9234                return true;
9235            }
9236            if (sendRemoved) {
9237                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9238                        "hiding pkg");
9239                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9240            }
9241        } finally {
9242            Binder.restoreCallingIdentity(callingId);
9243        }
9244        return false;
9245    }
9246
9247    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9248            int userId) {
9249        final PackageRemovedInfo info = new PackageRemovedInfo();
9250        info.removedPackage = packageName;
9251        info.removedUsers = new int[] {userId};
9252        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9253        info.sendBroadcast(false, false, false);
9254    }
9255
9256    /**
9257     * Returns true if application is not found or there was an error. Otherwise it returns
9258     * the hidden state of the package for the given user.
9259     */
9260    @Override
9261    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9262        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9263        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9264                false, "getApplicationHidden for user " + userId);
9265        PackageSetting pkgSetting;
9266        long callingId = Binder.clearCallingIdentity();
9267        try {
9268            // writer
9269            synchronized (mPackages) {
9270                pkgSetting = mSettings.mPackages.get(packageName);
9271                if (pkgSetting == null) {
9272                    return true;
9273                }
9274                return pkgSetting.getHidden(userId);
9275            }
9276        } finally {
9277            Binder.restoreCallingIdentity(callingId);
9278        }
9279    }
9280
9281    /**
9282     * @hide
9283     */
9284    @Override
9285    public int installExistingPackageAsUser(String packageName, int userId) {
9286        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9287                null);
9288        PackageSetting pkgSetting;
9289        final int uid = Binder.getCallingUid();
9290        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9291                + userId);
9292        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9293            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9294        }
9295
9296        long callingId = Binder.clearCallingIdentity();
9297        try {
9298            boolean sendAdded = false;
9299
9300            // writer
9301            synchronized (mPackages) {
9302                pkgSetting = mSettings.mPackages.get(packageName);
9303                if (pkgSetting == null) {
9304                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9305                }
9306                if (!pkgSetting.getInstalled(userId)) {
9307                    pkgSetting.setInstalled(true, userId);
9308                    pkgSetting.setHidden(false, userId);
9309                    mSettings.writePackageRestrictionsLPr(userId);
9310                    sendAdded = true;
9311                }
9312            }
9313
9314            if (sendAdded) {
9315                sendPackageAddedForUser(packageName, pkgSetting, userId);
9316            }
9317        } finally {
9318            Binder.restoreCallingIdentity(callingId);
9319        }
9320
9321        return PackageManager.INSTALL_SUCCEEDED;
9322    }
9323
9324    boolean isUserRestricted(int userId, String restrictionKey) {
9325        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9326        if (restrictions.getBoolean(restrictionKey, false)) {
9327            Log.w(TAG, "User is restricted: " + restrictionKey);
9328            return true;
9329        }
9330        return false;
9331    }
9332
9333    @Override
9334    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9335        mContext.enforceCallingOrSelfPermission(
9336                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9337                "Only package verification agents can verify applications");
9338
9339        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9340        final PackageVerificationResponse response = new PackageVerificationResponse(
9341                verificationCode, Binder.getCallingUid());
9342        msg.arg1 = id;
9343        msg.obj = response;
9344        mHandler.sendMessage(msg);
9345    }
9346
9347    @Override
9348    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9349            long millisecondsToDelay) {
9350        mContext.enforceCallingOrSelfPermission(
9351                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9352                "Only package verification agents can extend verification timeouts");
9353
9354        final PackageVerificationState state = mPendingVerification.get(id);
9355        final PackageVerificationResponse response = new PackageVerificationResponse(
9356                verificationCodeAtTimeout, Binder.getCallingUid());
9357
9358        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9359            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9360        }
9361        if (millisecondsToDelay < 0) {
9362            millisecondsToDelay = 0;
9363        }
9364        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9365                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9366            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9367        }
9368
9369        if ((state != null) && !state.timeoutExtended()) {
9370            state.extendTimeout();
9371
9372            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9373            msg.arg1 = id;
9374            msg.obj = response;
9375            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9376        }
9377    }
9378
9379    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9380            int verificationCode, UserHandle user) {
9381        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9382        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9383        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9384        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9385        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9386
9387        mContext.sendBroadcastAsUser(intent, user,
9388                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9389    }
9390
9391    private ComponentName matchComponentForVerifier(String packageName,
9392            List<ResolveInfo> receivers) {
9393        ActivityInfo targetReceiver = null;
9394
9395        final int NR = receivers.size();
9396        for (int i = 0; i < NR; i++) {
9397            final ResolveInfo info = receivers.get(i);
9398            if (info.activityInfo == null) {
9399                continue;
9400            }
9401
9402            if (packageName.equals(info.activityInfo.packageName)) {
9403                targetReceiver = info.activityInfo;
9404                break;
9405            }
9406        }
9407
9408        if (targetReceiver == null) {
9409            return null;
9410        }
9411
9412        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9413    }
9414
9415    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9416            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9417        if (pkgInfo.verifiers.length == 0) {
9418            return null;
9419        }
9420
9421        final int N = pkgInfo.verifiers.length;
9422        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9423        for (int i = 0; i < N; i++) {
9424            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9425
9426            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9427                    receivers);
9428            if (comp == null) {
9429                continue;
9430            }
9431
9432            final int verifierUid = getUidForVerifier(verifierInfo);
9433            if (verifierUid == -1) {
9434                continue;
9435            }
9436
9437            if (DEBUG_VERIFY) {
9438                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9439                        + " with the correct signature");
9440            }
9441            sufficientVerifiers.add(comp);
9442            verificationState.addSufficientVerifier(verifierUid);
9443        }
9444
9445        return sufficientVerifiers;
9446    }
9447
9448    private int getUidForVerifier(VerifierInfo verifierInfo) {
9449        synchronized (mPackages) {
9450            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9451            if (pkg == null) {
9452                return -1;
9453            } else if (pkg.mSignatures.length != 1) {
9454                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9455                        + " has more than one signature; ignoring");
9456                return -1;
9457            }
9458
9459            /*
9460             * If the public key of the package's signature does not match
9461             * our expected public key, then this is a different package and
9462             * we should skip.
9463             */
9464
9465            final byte[] expectedPublicKey;
9466            try {
9467                final Signature verifierSig = pkg.mSignatures[0];
9468                final PublicKey publicKey = verifierSig.getPublicKey();
9469                expectedPublicKey = publicKey.getEncoded();
9470            } catch (CertificateException e) {
9471                return -1;
9472            }
9473
9474            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9475
9476            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9477                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9478                        + " does not have the expected public key; ignoring");
9479                return -1;
9480            }
9481
9482            return pkg.applicationInfo.uid;
9483        }
9484    }
9485
9486    @Override
9487    public void finishPackageInstall(int token) {
9488        enforceSystemOrRoot("Only the system is allowed to finish installs");
9489
9490        if (DEBUG_INSTALL) {
9491            Slog.v(TAG, "BM finishing package install for " + token);
9492        }
9493
9494        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9495        mHandler.sendMessage(msg);
9496    }
9497
9498    /**
9499     * Get the verification agent timeout.
9500     *
9501     * @return verification timeout in milliseconds
9502     */
9503    private long getVerificationTimeout() {
9504        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9505                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9506                DEFAULT_VERIFICATION_TIMEOUT);
9507    }
9508
9509    /**
9510     * Get the default verification agent response code.
9511     *
9512     * @return default verification response code
9513     */
9514    private int getDefaultVerificationResponse() {
9515        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9516                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9517                DEFAULT_VERIFICATION_RESPONSE);
9518    }
9519
9520    /**
9521     * Check whether or not package verification has been enabled.
9522     *
9523     * @return true if verification should be performed
9524     */
9525    private boolean isVerificationEnabled(int userId, int installFlags) {
9526        if (!DEFAULT_VERIFY_ENABLE) {
9527            return false;
9528        }
9529
9530        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9531
9532        // Check if installing from ADB
9533        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9534            // Do not run verification in a test harness environment
9535            if (ActivityManager.isRunningInTestHarness()) {
9536                return false;
9537            }
9538            if (ensureVerifyAppsEnabled) {
9539                return true;
9540            }
9541            // Check if the developer does not want package verification for ADB installs
9542            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9543                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9544                return false;
9545            }
9546        }
9547
9548        if (ensureVerifyAppsEnabled) {
9549            return true;
9550        }
9551
9552        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9553                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9554    }
9555
9556    @Override
9557    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9558            throws RemoteException {
9559        mContext.enforceCallingOrSelfPermission(
9560                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9561                "Only intentfilter verification agents can verify applications");
9562
9563        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9564        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9565                Binder.getCallingUid(), verificationCode, failedDomains);
9566        msg.arg1 = id;
9567        msg.obj = response;
9568        mHandler.sendMessage(msg);
9569    }
9570
9571    @Override
9572    public int getIntentVerificationStatus(String packageName, int userId) {
9573        synchronized (mPackages) {
9574            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9575        }
9576    }
9577
9578    @Override
9579    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9580        boolean result = false;
9581        synchronized (mPackages) {
9582            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9583        }
9584        if (result) {
9585            scheduleWritePackageRestrictionsLocked(userId);
9586        }
9587        return result;
9588    }
9589
9590    @Override
9591    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9592        synchronized (mPackages) {
9593            return mSettings.getIntentFilterVerificationsLPr(packageName);
9594        }
9595    }
9596
9597    @Override
9598    public List<IntentFilter> getAllIntentFilters(String packageName) {
9599        if (TextUtils.isEmpty(packageName)) {
9600            return Collections.<IntentFilter>emptyList();
9601        }
9602        synchronized (mPackages) {
9603            PackageParser.Package pkg = mPackages.get(packageName);
9604            if (pkg == null || pkg.activities == null) {
9605                return Collections.<IntentFilter>emptyList();
9606            }
9607            final int count = pkg.activities.size();
9608            ArrayList<IntentFilter> result = new ArrayList<>();
9609            for (int n=0; n<count; n++) {
9610                PackageParser.Activity activity = pkg.activities.get(n);
9611                if (activity.intents != null || activity.intents.size() > 0) {
9612                    result.addAll(activity.intents);
9613                }
9614            }
9615            return result;
9616        }
9617    }
9618
9619    @Override
9620    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9621        synchronized (mPackages) {
9622            boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9623            if (packageName != null) {
9624                result |= updateIntentVerificationStatus(packageName,
9625                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9626                        UserHandle.myUserId());
9627            }
9628            return result;
9629        }
9630    }
9631
9632    @Override
9633    public String getDefaultBrowserPackageName(int userId) {
9634        synchronized (mPackages) {
9635            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9636        }
9637    }
9638
9639    /**
9640     * Get the "allow unknown sources" setting.
9641     *
9642     * @return the current "allow unknown sources" setting
9643     */
9644    private int getUnknownSourcesSettings() {
9645        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9646                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9647                -1);
9648    }
9649
9650    @Override
9651    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9652        final int uid = Binder.getCallingUid();
9653        // writer
9654        synchronized (mPackages) {
9655            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9656            if (targetPackageSetting == null) {
9657                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9658            }
9659
9660            PackageSetting installerPackageSetting;
9661            if (installerPackageName != null) {
9662                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9663                if (installerPackageSetting == null) {
9664                    throw new IllegalArgumentException("Unknown installer package: "
9665                            + installerPackageName);
9666                }
9667            } else {
9668                installerPackageSetting = null;
9669            }
9670
9671            Signature[] callerSignature;
9672            Object obj = mSettings.getUserIdLPr(uid);
9673            if (obj != null) {
9674                if (obj instanceof SharedUserSetting) {
9675                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9676                } else if (obj instanceof PackageSetting) {
9677                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9678                } else {
9679                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9680                }
9681            } else {
9682                throw new SecurityException("Unknown calling uid " + uid);
9683            }
9684
9685            // Verify: can't set installerPackageName to a package that is
9686            // not signed with the same cert as the caller.
9687            if (installerPackageSetting != null) {
9688                if (compareSignatures(callerSignature,
9689                        installerPackageSetting.signatures.mSignatures)
9690                        != PackageManager.SIGNATURE_MATCH) {
9691                    throw new SecurityException(
9692                            "Caller does not have same cert as new installer package "
9693                            + installerPackageName);
9694                }
9695            }
9696
9697            // Verify: if target already has an installer package, it must
9698            // be signed with the same cert as the caller.
9699            if (targetPackageSetting.installerPackageName != null) {
9700                PackageSetting setting = mSettings.mPackages.get(
9701                        targetPackageSetting.installerPackageName);
9702                // If the currently set package isn't valid, then it's always
9703                // okay to change it.
9704                if (setting != null) {
9705                    if (compareSignatures(callerSignature,
9706                            setting.signatures.mSignatures)
9707                            != PackageManager.SIGNATURE_MATCH) {
9708                        throw new SecurityException(
9709                                "Caller does not have same cert as old installer package "
9710                                + targetPackageSetting.installerPackageName);
9711                    }
9712                }
9713            }
9714
9715            // Okay!
9716            targetPackageSetting.installerPackageName = installerPackageName;
9717            scheduleWriteSettingsLocked();
9718        }
9719    }
9720
9721    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9722        // Queue up an async operation since the package installation may take a little while.
9723        mHandler.post(new Runnable() {
9724            public void run() {
9725                mHandler.removeCallbacks(this);
9726                 // Result object to be returned
9727                PackageInstalledInfo res = new PackageInstalledInfo();
9728                res.returnCode = currentStatus;
9729                res.uid = -1;
9730                res.pkg = null;
9731                res.removedInfo = new PackageRemovedInfo();
9732                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9733                    args.doPreInstall(res.returnCode);
9734                    synchronized (mInstallLock) {
9735                        installPackageLI(args, res);
9736                    }
9737                    args.doPostInstall(res.returnCode, res.uid);
9738                }
9739
9740                // A restore should be performed at this point if (a) the install
9741                // succeeded, (b) the operation is not an update, and (c) the new
9742                // package has not opted out of backup participation.
9743                final boolean update = res.removedInfo.removedPackage != null;
9744                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9745                boolean doRestore = !update
9746                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9747
9748                // Set up the post-install work request bookkeeping.  This will be used
9749                // and cleaned up by the post-install event handling regardless of whether
9750                // there's a restore pass performed.  Token values are >= 1.
9751                int token;
9752                if (mNextInstallToken < 0) mNextInstallToken = 1;
9753                token = mNextInstallToken++;
9754
9755                PostInstallData data = new PostInstallData(args, res);
9756                mRunningInstalls.put(token, data);
9757                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9758
9759                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9760                    // Pass responsibility to the Backup Manager.  It will perform a
9761                    // restore if appropriate, then pass responsibility back to the
9762                    // Package Manager to run the post-install observer callbacks
9763                    // and broadcasts.
9764                    IBackupManager bm = IBackupManager.Stub.asInterface(
9765                            ServiceManager.getService(Context.BACKUP_SERVICE));
9766                    if (bm != null) {
9767                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9768                                + " to BM for possible restore");
9769                        try {
9770                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9771                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9772                            } else {
9773                                doRestore = false;
9774                            }
9775                        } catch (RemoteException e) {
9776                            // can't happen; the backup manager is local
9777                        } catch (Exception e) {
9778                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9779                            doRestore = false;
9780                        }
9781                    } else {
9782                        Slog.e(TAG, "Backup Manager not found!");
9783                        doRestore = false;
9784                    }
9785                }
9786
9787                if (!doRestore) {
9788                    // No restore possible, or the Backup Manager was mysteriously not
9789                    // available -- just fire the post-install work request directly.
9790                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9791                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9792                    mHandler.sendMessage(msg);
9793                }
9794            }
9795        });
9796    }
9797
9798    private abstract class HandlerParams {
9799        private static final int MAX_RETRIES = 4;
9800
9801        /**
9802         * Number of times startCopy() has been attempted and had a non-fatal
9803         * error.
9804         */
9805        private int mRetries = 0;
9806
9807        /** User handle for the user requesting the information or installation. */
9808        private final UserHandle mUser;
9809
9810        HandlerParams(UserHandle user) {
9811            mUser = user;
9812        }
9813
9814        UserHandle getUser() {
9815            return mUser;
9816        }
9817
9818        final boolean startCopy() {
9819            boolean res;
9820            try {
9821                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9822
9823                if (++mRetries > MAX_RETRIES) {
9824                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9825                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9826                    handleServiceError();
9827                    return false;
9828                } else {
9829                    handleStartCopy();
9830                    res = true;
9831                }
9832            } catch (RemoteException e) {
9833                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9834                mHandler.sendEmptyMessage(MCS_RECONNECT);
9835                res = false;
9836            }
9837            handleReturnCode();
9838            return res;
9839        }
9840
9841        final void serviceError() {
9842            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9843            handleServiceError();
9844            handleReturnCode();
9845        }
9846
9847        abstract void handleStartCopy() throws RemoteException;
9848        abstract void handleServiceError();
9849        abstract void handleReturnCode();
9850    }
9851
9852    class MeasureParams extends HandlerParams {
9853        private final PackageStats mStats;
9854        private boolean mSuccess;
9855
9856        private final IPackageStatsObserver mObserver;
9857
9858        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9859            super(new UserHandle(stats.userHandle));
9860            mObserver = observer;
9861            mStats = stats;
9862        }
9863
9864        @Override
9865        public String toString() {
9866            return "MeasureParams{"
9867                + Integer.toHexString(System.identityHashCode(this))
9868                + " " + mStats.packageName + "}";
9869        }
9870
9871        @Override
9872        void handleStartCopy() throws RemoteException {
9873            synchronized (mInstallLock) {
9874                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9875            }
9876
9877            if (mSuccess) {
9878                final boolean mounted;
9879                if (Environment.isExternalStorageEmulated()) {
9880                    mounted = true;
9881                } else {
9882                    final String status = Environment.getExternalStorageState();
9883                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9884                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9885                }
9886
9887                if (mounted) {
9888                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9889
9890                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9891                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9892
9893                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9894                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9895
9896                    // Always subtract cache size, since it's a subdirectory
9897                    mStats.externalDataSize -= mStats.externalCacheSize;
9898
9899                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9900                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9901
9902                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9903                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9904                }
9905            }
9906        }
9907
9908        @Override
9909        void handleReturnCode() {
9910            if (mObserver != null) {
9911                try {
9912                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9913                } catch (RemoteException e) {
9914                    Slog.i(TAG, "Observer no longer exists.");
9915                }
9916            }
9917        }
9918
9919        @Override
9920        void handleServiceError() {
9921            Slog.e(TAG, "Could not measure application " + mStats.packageName
9922                            + " external storage");
9923        }
9924    }
9925
9926    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9927            throws RemoteException {
9928        long result = 0;
9929        for (File path : paths) {
9930            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9931        }
9932        return result;
9933    }
9934
9935    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9936        for (File path : paths) {
9937            try {
9938                mcs.clearDirectory(path.getAbsolutePath());
9939            } catch (RemoteException e) {
9940            }
9941        }
9942    }
9943
9944    static class OriginInfo {
9945        /**
9946         * Location where install is coming from, before it has been
9947         * copied/renamed into place. This could be a single monolithic APK
9948         * file, or a cluster directory. This location may be untrusted.
9949         */
9950        final File file;
9951        final String cid;
9952
9953        /**
9954         * Flag indicating that {@link #file} or {@link #cid} has already been
9955         * staged, meaning downstream users don't need to defensively copy the
9956         * contents.
9957         */
9958        final boolean staged;
9959
9960        /**
9961         * Flag indicating that {@link #file} or {@link #cid} is an already
9962         * installed app that is being moved.
9963         */
9964        final boolean existing;
9965
9966        final String resolvedPath;
9967        final File resolvedFile;
9968
9969        static OriginInfo fromNothing() {
9970            return new OriginInfo(null, null, false, false);
9971        }
9972
9973        static OriginInfo fromUntrustedFile(File file) {
9974            return new OriginInfo(file, null, false, false);
9975        }
9976
9977        static OriginInfo fromExistingFile(File file) {
9978            return new OriginInfo(file, null, false, true);
9979        }
9980
9981        static OriginInfo fromStagedFile(File file) {
9982            return new OriginInfo(file, null, true, false);
9983        }
9984
9985        static OriginInfo fromStagedContainer(String cid) {
9986            return new OriginInfo(null, cid, true, false);
9987        }
9988
9989        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9990            this.file = file;
9991            this.cid = cid;
9992            this.staged = staged;
9993            this.existing = existing;
9994
9995            if (cid != null) {
9996                resolvedPath = PackageHelper.getSdDir(cid);
9997                resolvedFile = new File(resolvedPath);
9998            } else if (file != null) {
9999                resolvedPath = file.getAbsolutePath();
10000                resolvedFile = file;
10001            } else {
10002                resolvedPath = null;
10003                resolvedFile = null;
10004            }
10005        }
10006    }
10007
10008    class MoveInfo {
10009        final int moveId;
10010        final String fromUuid;
10011        final String toUuid;
10012        final String packageName;
10013        final String dataAppName;
10014        final int appId;
10015        final String seinfo;
10016
10017        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10018                String dataAppName, int appId, String seinfo) {
10019            this.moveId = moveId;
10020            this.fromUuid = fromUuid;
10021            this.toUuid = toUuid;
10022            this.packageName = packageName;
10023            this.dataAppName = dataAppName;
10024            this.appId = appId;
10025            this.seinfo = seinfo;
10026        }
10027    }
10028
10029    class InstallParams extends HandlerParams {
10030        final OriginInfo origin;
10031        final MoveInfo move;
10032        final IPackageInstallObserver2 observer;
10033        int installFlags;
10034        final String installerPackageName;
10035        final String volumeUuid;
10036        final VerificationParams verificationParams;
10037        private InstallArgs mArgs;
10038        private int mRet;
10039        final String packageAbiOverride;
10040
10041        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10042                int installFlags, String installerPackageName, String volumeUuid,
10043                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10044            super(user);
10045            this.origin = origin;
10046            this.move = move;
10047            this.observer = observer;
10048            this.installFlags = installFlags;
10049            this.installerPackageName = installerPackageName;
10050            this.volumeUuid = volumeUuid;
10051            this.verificationParams = verificationParams;
10052            this.packageAbiOverride = packageAbiOverride;
10053        }
10054
10055        @Override
10056        public String toString() {
10057            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10058                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10059        }
10060
10061        public ManifestDigest getManifestDigest() {
10062            if (verificationParams == null) {
10063                return null;
10064            }
10065            return verificationParams.getManifestDigest();
10066        }
10067
10068        private int installLocationPolicy(PackageInfoLite pkgLite) {
10069            String packageName = pkgLite.packageName;
10070            int installLocation = pkgLite.installLocation;
10071            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10072            // reader
10073            synchronized (mPackages) {
10074                PackageParser.Package pkg = mPackages.get(packageName);
10075                if (pkg != null) {
10076                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10077                        // Check for downgrading.
10078                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10079                            try {
10080                                checkDowngrade(pkg, pkgLite);
10081                            } catch (PackageManagerException e) {
10082                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10083                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10084                            }
10085                        }
10086                        // Check for updated system application.
10087                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10088                            if (onSd) {
10089                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10090                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10091                            }
10092                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10093                        } else {
10094                            if (onSd) {
10095                                // Install flag overrides everything.
10096                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10097                            }
10098                            // If current upgrade specifies particular preference
10099                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10100                                // Application explicitly specified internal.
10101                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10102                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10103                                // App explictly prefers external. Let policy decide
10104                            } else {
10105                                // Prefer previous location
10106                                if (isExternal(pkg)) {
10107                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10108                                }
10109                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10110                            }
10111                        }
10112                    } else {
10113                        // Invalid install. Return error code
10114                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10115                    }
10116                }
10117            }
10118            // All the special cases have been taken care of.
10119            // Return result based on recommended install location.
10120            if (onSd) {
10121                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10122            }
10123            return pkgLite.recommendedInstallLocation;
10124        }
10125
10126        /*
10127         * Invoke remote method to get package information and install
10128         * location values. Override install location based on default
10129         * policy if needed and then create install arguments based
10130         * on the install location.
10131         */
10132        public void handleStartCopy() throws RemoteException {
10133            int ret = PackageManager.INSTALL_SUCCEEDED;
10134
10135            // If we're already staged, we've firmly committed to an install location
10136            if (origin.staged) {
10137                if (origin.file != null) {
10138                    installFlags |= PackageManager.INSTALL_INTERNAL;
10139                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10140                } else if (origin.cid != null) {
10141                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10142                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10143                } else {
10144                    throw new IllegalStateException("Invalid stage location");
10145                }
10146            }
10147
10148            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10149            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10150
10151            PackageInfoLite pkgLite = null;
10152
10153            if (onInt && onSd) {
10154                // Check if both bits are set.
10155                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10156                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10157            } else {
10158                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10159                        packageAbiOverride);
10160
10161                /*
10162                 * If we have too little free space, try to free cache
10163                 * before giving up.
10164                 */
10165                if (!origin.staged && pkgLite.recommendedInstallLocation
10166                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10167                    // TODO: focus freeing disk space on the target device
10168                    final StorageManager storage = StorageManager.from(mContext);
10169                    final long lowThreshold = storage.getStorageLowBytes(
10170                            Environment.getDataDirectory());
10171
10172                    final long sizeBytes = mContainerService.calculateInstalledSize(
10173                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10174
10175                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10176                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10177                                installFlags, packageAbiOverride);
10178                    }
10179
10180                    /*
10181                     * The cache free must have deleted the file we
10182                     * downloaded to install.
10183                     *
10184                     * TODO: fix the "freeCache" call to not delete
10185                     *       the file we care about.
10186                     */
10187                    if (pkgLite.recommendedInstallLocation
10188                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10189                        pkgLite.recommendedInstallLocation
10190                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10191                    }
10192                }
10193            }
10194
10195            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10196                int loc = pkgLite.recommendedInstallLocation;
10197                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10198                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10199                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10200                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10201                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10202                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10203                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10204                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10205                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10206                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10207                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10208                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10209                } else {
10210                    // Override with defaults if needed.
10211                    loc = installLocationPolicy(pkgLite);
10212                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10213                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10214                    } else if (!onSd && !onInt) {
10215                        // Override install location with flags
10216                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10217                            // Set the flag to install on external media.
10218                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10219                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10220                        } else {
10221                            // Make sure the flag for installing on external
10222                            // media is unset
10223                            installFlags |= PackageManager.INSTALL_INTERNAL;
10224                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10225                        }
10226                    }
10227                }
10228            }
10229
10230            final InstallArgs args = createInstallArgs(this);
10231            mArgs = args;
10232
10233            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10234                 /*
10235                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10236                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10237                 */
10238                int userIdentifier = getUser().getIdentifier();
10239                if (userIdentifier == UserHandle.USER_ALL
10240                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10241                    userIdentifier = UserHandle.USER_OWNER;
10242                }
10243
10244                /*
10245                 * Determine if we have any installed package verifiers. If we
10246                 * do, then we'll defer to them to verify the packages.
10247                 */
10248                final int requiredUid = mRequiredVerifierPackage == null ? -1
10249                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10250                if (!origin.existing && requiredUid != -1
10251                        && isVerificationEnabled(userIdentifier, installFlags)) {
10252                    final Intent verification = new Intent(
10253                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10254                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10255                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10256                            PACKAGE_MIME_TYPE);
10257                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10258
10259                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10260                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10261                            0 /* TODO: Which userId? */);
10262
10263                    if (DEBUG_VERIFY) {
10264                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10265                                + verification.toString() + " with " + pkgLite.verifiers.length
10266                                + " optional verifiers");
10267                    }
10268
10269                    final int verificationId = mPendingVerificationToken++;
10270
10271                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10272
10273                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10274                            installerPackageName);
10275
10276                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10277                            installFlags);
10278
10279                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10280                            pkgLite.packageName);
10281
10282                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10283                            pkgLite.versionCode);
10284
10285                    if (verificationParams != null) {
10286                        if (verificationParams.getVerificationURI() != null) {
10287                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10288                                 verificationParams.getVerificationURI());
10289                        }
10290                        if (verificationParams.getOriginatingURI() != null) {
10291                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10292                                  verificationParams.getOriginatingURI());
10293                        }
10294                        if (verificationParams.getReferrer() != null) {
10295                            verification.putExtra(Intent.EXTRA_REFERRER,
10296                                  verificationParams.getReferrer());
10297                        }
10298                        if (verificationParams.getOriginatingUid() >= 0) {
10299                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10300                                  verificationParams.getOriginatingUid());
10301                        }
10302                        if (verificationParams.getInstallerUid() >= 0) {
10303                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10304                                  verificationParams.getInstallerUid());
10305                        }
10306                    }
10307
10308                    final PackageVerificationState verificationState = new PackageVerificationState(
10309                            requiredUid, args);
10310
10311                    mPendingVerification.append(verificationId, verificationState);
10312
10313                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10314                            receivers, verificationState);
10315
10316                    /*
10317                     * If any sufficient verifiers were listed in the package
10318                     * manifest, attempt to ask them.
10319                     */
10320                    if (sufficientVerifiers != null) {
10321                        final int N = sufficientVerifiers.size();
10322                        if (N == 0) {
10323                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10324                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10325                        } else {
10326                            for (int i = 0; i < N; i++) {
10327                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10328
10329                                final Intent sufficientIntent = new Intent(verification);
10330                                sufficientIntent.setComponent(verifierComponent);
10331
10332                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10333                            }
10334                        }
10335                    }
10336
10337                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10338                            mRequiredVerifierPackage, receivers);
10339                    if (ret == PackageManager.INSTALL_SUCCEEDED
10340                            && mRequiredVerifierPackage != null) {
10341                        /*
10342                         * Send the intent to the required verification agent,
10343                         * but only start the verification timeout after the
10344                         * target BroadcastReceivers have run.
10345                         */
10346                        verification.setComponent(requiredVerifierComponent);
10347                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10348                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10349                                new BroadcastReceiver() {
10350                                    @Override
10351                                    public void onReceive(Context context, Intent intent) {
10352                                        final Message msg = mHandler
10353                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10354                                        msg.arg1 = verificationId;
10355                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10356                                    }
10357                                }, null, 0, null, null);
10358
10359                        /*
10360                         * We don't want the copy to proceed until verification
10361                         * succeeds, so null out this field.
10362                         */
10363                        mArgs = null;
10364                    }
10365                } else {
10366                    /*
10367                     * No package verification is enabled, so immediately start
10368                     * the remote call to initiate copy using temporary file.
10369                     */
10370                    ret = args.copyApk(mContainerService, true);
10371                }
10372            }
10373
10374            mRet = ret;
10375        }
10376
10377        @Override
10378        void handleReturnCode() {
10379            // If mArgs is null, then MCS couldn't be reached. When it
10380            // reconnects, it will try again to install. At that point, this
10381            // will succeed.
10382            if (mArgs != null) {
10383                processPendingInstall(mArgs, mRet);
10384            }
10385        }
10386
10387        @Override
10388        void handleServiceError() {
10389            mArgs = createInstallArgs(this);
10390            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10391        }
10392
10393        public boolean isForwardLocked() {
10394            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10395        }
10396    }
10397
10398    /**
10399     * Used during creation of InstallArgs
10400     *
10401     * @param installFlags package installation flags
10402     * @return true if should be installed on external storage
10403     */
10404    private static boolean installOnExternalAsec(int installFlags) {
10405        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10406            return false;
10407        }
10408        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10409            return true;
10410        }
10411        return false;
10412    }
10413
10414    /**
10415     * Used during creation of InstallArgs
10416     *
10417     * @param installFlags package installation flags
10418     * @return true if should be installed as forward locked
10419     */
10420    private static boolean installForwardLocked(int installFlags) {
10421        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10422    }
10423
10424    private InstallArgs createInstallArgs(InstallParams params) {
10425        if (params.move != null) {
10426            return new MoveInstallArgs(params);
10427        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10428            return new AsecInstallArgs(params);
10429        } else {
10430            return new FileInstallArgs(params);
10431        }
10432    }
10433
10434    /**
10435     * Create args that describe an existing installed package. Typically used
10436     * when cleaning up old installs, or used as a move source.
10437     */
10438    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10439            String resourcePath, String[] instructionSets) {
10440        final boolean isInAsec;
10441        if (installOnExternalAsec(installFlags)) {
10442            /* Apps on SD card are always in ASEC containers. */
10443            isInAsec = true;
10444        } else if (installForwardLocked(installFlags)
10445                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10446            /*
10447             * Forward-locked apps are only in ASEC containers if they're the
10448             * new style
10449             */
10450            isInAsec = true;
10451        } else {
10452            isInAsec = false;
10453        }
10454
10455        if (isInAsec) {
10456            return new AsecInstallArgs(codePath, instructionSets,
10457                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10458        } else {
10459            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10460        }
10461    }
10462
10463    static abstract class InstallArgs {
10464        /** @see InstallParams#origin */
10465        final OriginInfo origin;
10466        /** @see InstallParams#move */
10467        final MoveInfo move;
10468
10469        final IPackageInstallObserver2 observer;
10470        // Always refers to PackageManager flags only
10471        final int installFlags;
10472        final String installerPackageName;
10473        final String volumeUuid;
10474        final ManifestDigest manifestDigest;
10475        final UserHandle user;
10476        final String abiOverride;
10477
10478        // The list of instruction sets supported by this app. This is currently
10479        // only used during the rmdex() phase to clean up resources. We can get rid of this
10480        // if we move dex files under the common app path.
10481        /* nullable */ String[] instructionSets;
10482
10483        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10484                int installFlags, String installerPackageName, String volumeUuid,
10485                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10486                String abiOverride) {
10487            this.origin = origin;
10488            this.move = move;
10489            this.installFlags = installFlags;
10490            this.observer = observer;
10491            this.installerPackageName = installerPackageName;
10492            this.volumeUuid = volumeUuid;
10493            this.manifestDigest = manifestDigest;
10494            this.user = user;
10495            this.instructionSets = instructionSets;
10496            this.abiOverride = abiOverride;
10497        }
10498
10499        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10500        abstract int doPreInstall(int status);
10501
10502        /**
10503         * Rename package into final resting place. All paths on the given
10504         * scanned package should be updated to reflect the rename.
10505         */
10506        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10507        abstract int doPostInstall(int status, int uid);
10508
10509        /** @see PackageSettingBase#codePathString */
10510        abstract String getCodePath();
10511        /** @see PackageSettingBase#resourcePathString */
10512        abstract String getResourcePath();
10513
10514        // Need installer lock especially for dex file removal.
10515        abstract void cleanUpResourcesLI();
10516        abstract boolean doPostDeleteLI(boolean delete);
10517
10518        /**
10519         * Called before the source arguments are copied. This is used mostly
10520         * for MoveParams when it needs to read the source file to put it in the
10521         * destination.
10522         */
10523        int doPreCopy() {
10524            return PackageManager.INSTALL_SUCCEEDED;
10525        }
10526
10527        /**
10528         * Called after the source arguments are copied. This is used mostly for
10529         * MoveParams when it needs to read the source file to put it in the
10530         * destination.
10531         *
10532         * @return
10533         */
10534        int doPostCopy(int uid) {
10535            return PackageManager.INSTALL_SUCCEEDED;
10536        }
10537
10538        protected boolean isFwdLocked() {
10539            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10540        }
10541
10542        protected boolean isExternalAsec() {
10543            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10544        }
10545
10546        UserHandle getUser() {
10547            return user;
10548        }
10549    }
10550
10551    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10552        if (!allCodePaths.isEmpty()) {
10553            if (instructionSets == null) {
10554                throw new IllegalStateException("instructionSet == null");
10555            }
10556            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10557            for (String codePath : allCodePaths) {
10558                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10559                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10560                    if (retCode < 0) {
10561                        Slog.w(TAG, "Couldn't remove dex file for package: "
10562                                + " at location " + codePath + ", retcode=" + retCode);
10563                        // we don't consider this to be a failure of the core package deletion
10564                    }
10565                }
10566            }
10567        }
10568    }
10569
10570    /**
10571     * Logic to handle installation of non-ASEC applications, including copying
10572     * and renaming logic.
10573     */
10574    class FileInstallArgs extends InstallArgs {
10575        private File codeFile;
10576        private File resourceFile;
10577
10578        // Example topology:
10579        // /data/app/com.example/base.apk
10580        // /data/app/com.example/split_foo.apk
10581        // /data/app/com.example/lib/arm/libfoo.so
10582        // /data/app/com.example/lib/arm64/libfoo.so
10583        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10584
10585        /** New install */
10586        FileInstallArgs(InstallParams params) {
10587            super(params.origin, params.move, params.observer, params.installFlags,
10588                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10589                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10590            if (isFwdLocked()) {
10591                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10592            }
10593        }
10594
10595        /** Existing install */
10596        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10597            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10598                    null);
10599            this.codeFile = (codePath != null) ? new File(codePath) : null;
10600            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10601        }
10602
10603        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10604            if (origin.staged) {
10605                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10606                codeFile = origin.file;
10607                resourceFile = origin.file;
10608                return PackageManager.INSTALL_SUCCEEDED;
10609            }
10610
10611            try {
10612                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10613                codeFile = tempDir;
10614                resourceFile = tempDir;
10615            } catch (IOException e) {
10616                Slog.w(TAG, "Failed to create copy file: " + e);
10617                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10618            }
10619
10620            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10621                @Override
10622                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10623                    if (!FileUtils.isValidExtFilename(name)) {
10624                        throw new IllegalArgumentException("Invalid filename: " + name);
10625                    }
10626                    try {
10627                        final File file = new File(codeFile, name);
10628                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10629                                O_RDWR | O_CREAT, 0644);
10630                        Os.chmod(file.getAbsolutePath(), 0644);
10631                        return new ParcelFileDescriptor(fd);
10632                    } catch (ErrnoException e) {
10633                        throw new RemoteException("Failed to open: " + e.getMessage());
10634                    }
10635                }
10636            };
10637
10638            int ret = PackageManager.INSTALL_SUCCEEDED;
10639            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10640            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10641                Slog.e(TAG, "Failed to copy package");
10642                return ret;
10643            }
10644
10645            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10646            NativeLibraryHelper.Handle handle = null;
10647            try {
10648                handle = NativeLibraryHelper.Handle.create(codeFile);
10649                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10650                        abiOverride);
10651            } catch (IOException e) {
10652                Slog.e(TAG, "Copying native libraries failed", e);
10653                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10654            } finally {
10655                IoUtils.closeQuietly(handle);
10656            }
10657
10658            return ret;
10659        }
10660
10661        int doPreInstall(int status) {
10662            if (status != PackageManager.INSTALL_SUCCEEDED) {
10663                cleanUp();
10664            }
10665            return status;
10666        }
10667
10668        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10669            if (status != PackageManager.INSTALL_SUCCEEDED) {
10670                cleanUp();
10671                return false;
10672            }
10673
10674            final File targetDir = codeFile.getParentFile();
10675            final File beforeCodeFile = codeFile;
10676            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10677
10678            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10679            try {
10680                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10681            } catch (ErrnoException e) {
10682                Slog.w(TAG, "Failed to rename", e);
10683                return false;
10684            }
10685
10686            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10687                Slog.w(TAG, "Failed to restorecon");
10688                return false;
10689            }
10690
10691            // Reflect the rename internally
10692            codeFile = afterCodeFile;
10693            resourceFile = afterCodeFile;
10694
10695            // Reflect the rename in scanned details
10696            pkg.codePath = afterCodeFile.getAbsolutePath();
10697            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10698                    pkg.baseCodePath);
10699            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10700                    pkg.splitCodePaths);
10701
10702            // Reflect the rename in app info
10703            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10704            pkg.applicationInfo.setCodePath(pkg.codePath);
10705            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10706            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10707            pkg.applicationInfo.setResourcePath(pkg.codePath);
10708            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10709            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10710
10711            return true;
10712        }
10713
10714        int doPostInstall(int status, int uid) {
10715            if (status != PackageManager.INSTALL_SUCCEEDED) {
10716                cleanUp();
10717            }
10718            return status;
10719        }
10720
10721        @Override
10722        String getCodePath() {
10723            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10724        }
10725
10726        @Override
10727        String getResourcePath() {
10728            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10729        }
10730
10731        private boolean cleanUp() {
10732            if (codeFile == null || !codeFile.exists()) {
10733                return false;
10734            }
10735
10736            if (codeFile.isDirectory()) {
10737                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10738            } else {
10739                codeFile.delete();
10740            }
10741
10742            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10743                resourceFile.delete();
10744            }
10745
10746            return true;
10747        }
10748
10749        void cleanUpResourcesLI() {
10750            // Try enumerating all code paths before deleting
10751            List<String> allCodePaths = Collections.EMPTY_LIST;
10752            if (codeFile != null && codeFile.exists()) {
10753                try {
10754                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10755                    allCodePaths = pkg.getAllCodePaths();
10756                } catch (PackageParserException e) {
10757                    // Ignored; we tried our best
10758                }
10759            }
10760
10761            cleanUp();
10762            removeDexFiles(allCodePaths, instructionSets);
10763        }
10764
10765        boolean doPostDeleteLI(boolean delete) {
10766            // XXX err, shouldn't we respect the delete flag?
10767            cleanUpResourcesLI();
10768            return true;
10769        }
10770    }
10771
10772    private boolean isAsecExternal(String cid) {
10773        final String asecPath = PackageHelper.getSdFilesystem(cid);
10774        return !asecPath.startsWith(mAsecInternalPath);
10775    }
10776
10777    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10778            PackageManagerException {
10779        if (copyRet < 0) {
10780            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10781                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10782                throw new PackageManagerException(copyRet, message);
10783            }
10784        }
10785    }
10786
10787    /**
10788     * Extract the MountService "container ID" from the full code path of an
10789     * .apk.
10790     */
10791    static String cidFromCodePath(String fullCodePath) {
10792        int eidx = fullCodePath.lastIndexOf("/");
10793        String subStr1 = fullCodePath.substring(0, eidx);
10794        int sidx = subStr1.lastIndexOf("/");
10795        return subStr1.substring(sidx+1, eidx);
10796    }
10797
10798    /**
10799     * Logic to handle installation of ASEC applications, including copying and
10800     * renaming logic.
10801     */
10802    class AsecInstallArgs extends InstallArgs {
10803        static final String RES_FILE_NAME = "pkg.apk";
10804        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10805
10806        String cid;
10807        String packagePath;
10808        String resourcePath;
10809
10810        /** New install */
10811        AsecInstallArgs(InstallParams params) {
10812            super(params.origin, params.move, params.observer, params.installFlags,
10813                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10814                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10815        }
10816
10817        /** Existing install */
10818        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10819                        boolean isExternal, boolean isForwardLocked) {
10820            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10821                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10822                    instructionSets, null);
10823            // Hackily pretend we're still looking at a full code path
10824            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10825                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10826            }
10827
10828            // Extract cid from fullCodePath
10829            int eidx = fullCodePath.lastIndexOf("/");
10830            String subStr1 = fullCodePath.substring(0, eidx);
10831            int sidx = subStr1.lastIndexOf("/");
10832            cid = subStr1.substring(sidx+1, eidx);
10833            setMountPath(subStr1);
10834        }
10835
10836        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10837            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10838                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10839                    instructionSets, null);
10840            this.cid = cid;
10841            setMountPath(PackageHelper.getSdDir(cid));
10842        }
10843
10844        void createCopyFile() {
10845            cid = mInstallerService.allocateExternalStageCidLegacy();
10846        }
10847
10848        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10849            if (origin.staged) {
10850                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
10851                cid = origin.cid;
10852                setMountPath(PackageHelper.getSdDir(cid));
10853                return PackageManager.INSTALL_SUCCEEDED;
10854            }
10855
10856            if (temp) {
10857                createCopyFile();
10858            } else {
10859                /*
10860                 * Pre-emptively destroy the container since it's destroyed if
10861                 * copying fails due to it existing anyway.
10862                 */
10863                PackageHelper.destroySdDir(cid);
10864            }
10865
10866            final String newMountPath = imcs.copyPackageToContainer(
10867                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10868                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10869
10870            if (newMountPath != null) {
10871                setMountPath(newMountPath);
10872                return PackageManager.INSTALL_SUCCEEDED;
10873            } else {
10874                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10875            }
10876        }
10877
10878        @Override
10879        String getCodePath() {
10880            return packagePath;
10881        }
10882
10883        @Override
10884        String getResourcePath() {
10885            return resourcePath;
10886        }
10887
10888        int doPreInstall(int status) {
10889            if (status != PackageManager.INSTALL_SUCCEEDED) {
10890                // Destroy container
10891                PackageHelper.destroySdDir(cid);
10892            } else {
10893                boolean mounted = PackageHelper.isContainerMounted(cid);
10894                if (!mounted) {
10895                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10896                            Process.SYSTEM_UID);
10897                    if (newMountPath != null) {
10898                        setMountPath(newMountPath);
10899                    } else {
10900                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10901                    }
10902                }
10903            }
10904            return status;
10905        }
10906
10907        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10908            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10909            String newMountPath = null;
10910            if (PackageHelper.isContainerMounted(cid)) {
10911                // Unmount the container
10912                if (!PackageHelper.unMountSdDir(cid)) {
10913                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10914                    return false;
10915                }
10916            }
10917            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10918                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10919                        " which might be stale. Will try to clean up.");
10920                // Clean up the stale container and proceed to recreate.
10921                if (!PackageHelper.destroySdDir(newCacheId)) {
10922                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10923                    return false;
10924                }
10925                // Successfully cleaned up stale container. Try to rename again.
10926                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10927                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10928                            + " inspite of cleaning it up.");
10929                    return false;
10930                }
10931            }
10932            if (!PackageHelper.isContainerMounted(newCacheId)) {
10933                Slog.w(TAG, "Mounting container " + newCacheId);
10934                newMountPath = PackageHelper.mountSdDir(newCacheId,
10935                        getEncryptKey(), Process.SYSTEM_UID);
10936            } else {
10937                newMountPath = PackageHelper.getSdDir(newCacheId);
10938            }
10939            if (newMountPath == null) {
10940                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10941                return false;
10942            }
10943            Log.i(TAG, "Succesfully renamed " + cid +
10944                    " to " + newCacheId +
10945                    " at new path: " + newMountPath);
10946            cid = newCacheId;
10947
10948            final File beforeCodeFile = new File(packagePath);
10949            setMountPath(newMountPath);
10950            final File afterCodeFile = new File(packagePath);
10951
10952            // Reflect the rename in scanned details
10953            pkg.codePath = afterCodeFile.getAbsolutePath();
10954            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10955                    pkg.baseCodePath);
10956            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10957                    pkg.splitCodePaths);
10958
10959            // Reflect the rename in app info
10960            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10961            pkg.applicationInfo.setCodePath(pkg.codePath);
10962            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10963            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10964            pkg.applicationInfo.setResourcePath(pkg.codePath);
10965            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10966            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10967
10968            return true;
10969        }
10970
10971        private void setMountPath(String mountPath) {
10972            final File mountFile = new File(mountPath);
10973
10974            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10975            if (monolithicFile.exists()) {
10976                packagePath = monolithicFile.getAbsolutePath();
10977                if (isFwdLocked()) {
10978                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10979                } else {
10980                    resourcePath = packagePath;
10981                }
10982            } else {
10983                packagePath = mountFile.getAbsolutePath();
10984                resourcePath = packagePath;
10985            }
10986        }
10987
10988        int doPostInstall(int status, int uid) {
10989            if (status != PackageManager.INSTALL_SUCCEEDED) {
10990                cleanUp();
10991            } else {
10992                final int groupOwner;
10993                final String protectedFile;
10994                if (isFwdLocked()) {
10995                    groupOwner = UserHandle.getSharedAppGid(uid);
10996                    protectedFile = RES_FILE_NAME;
10997                } else {
10998                    groupOwner = -1;
10999                    protectedFile = null;
11000                }
11001
11002                if (uid < Process.FIRST_APPLICATION_UID
11003                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11004                    Slog.e(TAG, "Failed to finalize " + cid);
11005                    PackageHelper.destroySdDir(cid);
11006                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11007                }
11008
11009                boolean mounted = PackageHelper.isContainerMounted(cid);
11010                if (!mounted) {
11011                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11012                }
11013            }
11014            return status;
11015        }
11016
11017        private void cleanUp() {
11018            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11019
11020            // Destroy secure container
11021            PackageHelper.destroySdDir(cid);
11022        }
11023
11024        private List<String> getAllCodePaths() {
11025            final File codeFile = new File(getCodePath());
11026            if (codeFile != null && codeFile.exists()) {
11027                try {
11028                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11029                    return pkg.getAllCodePaths();
11030                } catch (PackageParserException e) {
11031                    // Ignored; we tried our best
11032                }
11033            }
11034            return Collections.EMPTY_LIST;
11035        }
11036
11037        void cleanUpResourcesLI() {
11038            // Enumerate all code paths before deleting
11039            cleanUpResourcesLI(getAllCodePaths());
11040        }
11041
11042        private void cleanUpResourcesLI(List<String> allCodePaths) {
11043            cleanUp();
11044            removeDexFiles(allCodePaths, instructionSets);
11045        }
11046
11047        String getPackageName() {
11048            return getAsecPackageName(cid);
11049        }
11050
11051        boolean doPostDeleteLI(boolean delete) {
11052            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11053            final List<String> allCodePaths = getAllCodePaths();
11054            boolean mounted = PackageHelper.isContainerMounted(cid);
11055            if (mounted) {
11056                // Unmount first
11057                if (PackageHelper.unMountSdDir(cid)) {
11058                    mounted = false;
11059                }
11060            }
11061            if (!mounted && delete) {
11062                cleanUpResourcesLI(allCodePaths);
11063            }
11064            return !mounted;
11065        }
11066
11067        @Override
11068        int doPreCopy() {
11069            if (isFwdLocked()) {
11070                if (!PackageHelper.fixSdPermissions(cid,
11071                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11072                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11073                }
11074            }
11075
11076            return PackageManager.INSTALL_SUCCEEDED;
11077        }
11078
11079        @Override
11080        int doPostCopy(int uid) {
11081            if (isFwdLocked()) {
11082                if (uid < Process.FIRST_APPLICATION_UID
11083                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11084                                RES_FILE_NAME)) {
11085                    Slog.e(TAG, "Failed to finalize " + cid);
11086                    PackageHelper.destroySdDir(cid);
11087                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11088                }
11089            }
11090
11091            return PackageManager.INSTALL_SUCCEEDED;
11092        }
11093    }
11094
11095    /**
11096     * Logic to handle movement of existing installed applications.
11097     */
11098    class MoveInstallArgs extends InstallArgs {
11099        private File codeFile;
11100        private File resourceFile;
11101
11102        /** New install */
11103        MoveInstallArgs(InstallParams params) {
11104            super(params.origin, params.move, params.observer, params.installFlags,
11105                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11106                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11107        }
11108
11109        int copyApk(IMediaContainerService imcs, boolean temp) {
11110            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11111                    + move.fromUuid + " to " + move.toUuid);
11112            synchronized (mInstaller) {
11113                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11114                        move.dataAppName, move.appId, move.seinfo) != 0) {
11115                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11116                }
11117            }
11118
11119            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11120            resourceFile = codeFile;
11121            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11122
11123            return PackageManager.INSTALL_SUCCEEDED;
11124        }
11125
11126        int doPreInstall(int status) {
11127            if (status != PackageManager.INSTALL_SUCCEEDED) {
11128                cleanUp();
11129            }
11130            return status;
11131        }
11132
11133        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11134            if (status != PackageManager.INSTALL_SUCCEEDED) {
11135                cleanUp();
11136                return false;
11137            }
11138
11139            // Reflect the move in app info
11140            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11141            pkg.applicationInfo.setCodePath(pkg.codePath);
11142            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11143            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11144            pkg.applicationInfo.setResourcePath(pkg.codePath);
11145            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11146            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11147
11148            return true;
11149        }
11150
11151        int doPostInstall(int status, int uid) {
11152            if (status != PackageManager.INSTALL_SUCCEEDED) {
11153                cleanUp();
11154            }
11155            return status;
11156        }
11157
11158        @Override
11159        String getCodePath() {
11160            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11161        }
11162
11163        @Override
11164        String getResourcePath() {
11165            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11166        }
11167
11168        private boolean cleanUp() {
11169            if (codeFile == null || !codeFile.exists()) {
11170                return false;
11171            }
11172
11173            if (codeFile.isDirectory()) {
11174                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11175            } else {
11176                codeFile.delete();
11177            }
11178
11179            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11180                resourceFile.delete();
11181            }
11182
11183            return true;
11184        }
11185
11186        void cleanUpResourcesLI() {
11187            cleanUp();
11188        }
11189
11190        boolean doPostDeleteLI(boolean delete) {
11191            // XXX err, shouldn't we respect the delete flag?
11192            cleanUpResourcesLI();
11193            return true;
11194        }
11195    }
11196
11197    static String getAsecPackageName(String packageCid) {
11198        int idx = packageCid.lastIndexOf("-");
11199        if (idx == -1) {
11200            return packageCid;
11201        }
11202        return packageCid.substring(0, idx);
11203    }
11204
11205    // Utility method used to create code paths based on package name and available index.
11206    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11207        String idxStr = "";
11208        int idx = 1;
11209        // Fall back to default value of idx=1 if prefix is not
11210        // part of oldCodePath
11211        if (oldCodePath != null) {
11212            String subStr = oldCodePath;
11213            // Drop the suffix right away
11214            if (suffix != null && subStr.endsWith(suffix)) {
11215                subStr = subStr.substring(0, subStr.length() - suffix.length());
11216            }
11217            // If oldCodePath already contains prefix find out the
11218            // ending index to either increment or decrement.
11219            int sidx = subStr.lastIndexOf(prefix);
11220            if (sidx != -1) {
11221                subStr = subStr.substring(sidx + prefix.length());
11222                if (subStr != null) {
11223                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11224                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11225                    }
11226                    try {
11227                        idx = Integer.parseInt(subStr);
11228                        if (idx <= 1) {
11229                            idx++;
11230                        } else {
11231                            idx--;
11232                        }
11233                    } catch(NumberFormatException e) {
11234                    }
11235                }
11236            }
11237        }
11238        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11239        return prefix + idxStr;
11240    }
11241
11242    private File getNextCodePath(File targetDir, String packageName) {
11243        int suffix = 1;
11244        File result;
11245        do {
11246            result = new File(targetDir, packageName + "-" + suffix);
11247            suffix++;
11248        } while (result.exists());
11249        return result;
11250    }
11251
11252    // Utility method that returns the relative package path with respect
11253    // to the installation directory. Like say for /data/data/com.test-1.apk
11254    // string com.test-1 is returned.
11255    static String deriveCodePathName(String codePath) {
11256        if (codePath == null) {
11257            return null;
11258        }
11259        final File codeFile = new File(codePath);
11260        final String name = codeFile.getName();
11261        if (codeFile.isDirectory()) {
11262            return name;
11263        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11264            final int lastDot = name.lastIndexOf('.');
11265            return name.substring(0, lastDot);
11266        } else {
11267            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11268            return null;
11269        }
11270    }
11271
11272    class PackageInstalledInfo {
11273        String name;
11274        int uid;
11275        // The set of users that originally had this package installed.
11276        int[] origUsers;
11277        // The set of users that now have this package installed.
11278        int[] newUsers;
11279        PackageParser.Package pkg;
11280        int returnCode;
11281        String returnMsg;
11282        PackageRemovedInfo removedInfo;
11283
11284        public void setError(int code, String msg) {
11285            returnCode = code;
11286            returnMsg = msg;
11287            Slog.w(TAG, msg);
11288        }
11289
11290        public void setError(String msg, PackageParserException e) {
11291            returnCode = e.error;
11292            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11293            Slog.w(TAG, msg, e);
11294        }
11295
11296        public void setError(String msg, PackageManagerException e) {
11297            returnCode = e.error;
11298            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11299            Slog.w(TAG, msg, e);
11300        }
11301
11302        // In some error cases we want to convey more info back to the observer
11303        String origPackage;
11304        String origPermission;
11305    }
11306
11307    /*
11308     * Install a non-existing package.
11309     */
11310    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11311            UserHandle user, String installerPackageName, String volumeUuid,
11312            PackageInstalledInfo res) {
11313        // Remember this for later, in case we need to rollback this install
11314        String pkgName = pkg.packageName;
11315
11316        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11317        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
11318                UserHandle.USER_OWNER).exists();
11319        synchronized(mPackages) {
11320            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11321                // A package with the same name is already installed, though
11322                // it has been renamed to an older name.  The package we
11323                // are trying to install should be installed as an update to
11324                // the existing one, but that has not been requested, so bail.
11325                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11326                        + " without first uninstalling package running as "
11327                        + mSettings.mRenamedPackages.get(pkgName));
11328                return;
11329            }
11330            if (mPackages.containsKey(pkgName)) {
11331                // Don't allow installation over an existing package with the same name.
11332                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11333                        + " without first uninstalling.");
11334                return;
11335            }
11336        }
11337
11338        try {
11339            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11340                    System.currentTimeMillis(), user);
11341
11342            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11343            // delete the partially installed application. the data directory will have to be
11344            // restored if it was already existing
11345            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11346                // remove package from internal structures.  Note that we want deletePackageX to
11347                // delete the package data and cache directories that it created in
11348                // scanPackageLocked, unless those directories existed before we even tried to
11349                // install.
11350                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11351                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11352                                res.removedInfo, true);
11353            }
11354
11355        } catch (PackageManagerException e) {
11356            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11357        }
11358    }
11359
11360    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11361        // Can't rotate keys during boot or if sharedUser.
11362        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11363                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11364            return false;
11365        }
11366        // app is using upgradeKeySets; make sure all are valid
11367        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11368        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11369        for (int i = 0; i < upgradeKeySets.length; i++) {
11370            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11371                Slog.wtf(TAG, "Package "
11372                         + (oldPs.name != null ? oldPs.name : "<null>")
11373                         + " contains upgrade-key-set reference to unknown key-set: "
11374                         + upgradeKeySets[i]
11375                         + " reverting to signatures check.");
11376                return false;
11377            }
11378        }
11379        return true;
11380    }
11381
11382    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11383        // Upgrade keysets are being used.  Determine if new package has a superset of the
11384        // required keys.
11385        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11386        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11387        for (int i = 0; i < upgradeKeySets.length; i++) {
11388            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11389            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11390                return true;
11391            }
11392        }
11393        return false;
11394    }
11395
11396    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11397            UserHandle user, String installerPackageName, String volumeUuid,
11398            PackageInstalledInfo res) {
11399        final PackageParser.Package oldPackage;
11400        final String pkgName = pkg.packageName;
11401        final int[] allUsers;
11402        final boolean[] perUserInstalled;
11403        final boolean weFroze;
11404
11405        // First find the old package info and check signatures
11406        synchronized(mPackages) {
11407            oldPackage = mPackages.get(pkgName);
11408            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11409            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11410            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11411                if(!checkUpgradeKeySetLP(ps, pkg)) {
11412                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11413                            "New package not signed by keys specified by upgrade-keysets: "
11414                            + pkgName);
11415                    return;
11416                }
11417            } else {
11418                // default to original signature matching
11419                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11420                    != PackageManager.SIGNATURE_MATCH) {
11421                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11422                            "New package has a different signature: " + pkgName);
11423                    return;
11424                }
11425            }
11426
11427            // In case of rollback, remember per-user/profile install state
11428            allUsers = sUserManager.getUserIds();
11429            perUserInstalled = new boolean[allUsers.length];
11430            for (int i = 0; i < allUsers.length; i++) {
11431                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11432            }
11433
11434            // Mark the app as frozen to prevent launching during the upgrade
11435            // process, and then kill all running instances
11436            if (!ps.frozen) {
11437                ps.frozen = true;
11438                weFroze = true;
11439            } else {
11440                weFroze = false;
11441            }
11442        }
11443
11444        // Now that we're guarded by frozen state, kill app during upgrade
11445        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11446
11447        try {
11448            boolean sysPkg = (isSystemApp(oldPackage));
11449            if (sysPkg) {
11450                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11451                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11452            } else {
11453                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11454                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11455            }
11456        } finally {
11457            // Regardless of success or failure of upgrade steps above, always
11458            // unfreeze the package if we froze it
11459            if (weFroze) {
11460                unfreezePackage(pkgName);
11461            }
11462        }
11463    }
11464
11465    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11466            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11467            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11468            String volumeUuid, PackageInstalledInfo res) {
11469        String pkgName = deletedPackage.packageName;
11470        boolean deletedPkg = true;
11471        boolean updatedSettings = false;
11472
11473        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11474                + deletedPackage);
11475        long origUpdateTime;
11476        if (pkg.mExtras != null) {
11477            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11478        } else {
11479            origUpdateTime = 0;
11480        }
11481
11482        // First delete the existing package while retaining the data directory
11483        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11484                res.removedInfo, true)) {
11485            // If the existing package wasn't successfully deleted
11486            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11487            deletedPkg = false;
11488        } else {
11489            // Successfully deleted the old package; proceed with replace.
11490
11491            // If deleted package lived in a container, give users a chance to
11492            // relinquish resources before killing.
11493            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11494                if (DEBUG_INSTALL) {
11495                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11496                }
11497                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11498                final ArrayList<String> pkgList = new ArrayList<String>(1);
11499                pkgList.add(deletedPackage.applicationInfo.packageName);
11500                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11501            }
11502
11503            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11504            try {
11505                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11506                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11507                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11508                        perUserInstalled, res, user);
11509                updatedSettings = true;
11510            } catch (PackageManagerException e) {
11511                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11512            }
11513        }
11514
11515        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11516            // remove package from internal structures.  Note that we want deletePackageX to
11517            // delete the package data and cache directories that it created in
11518            // scanPackageLocked, unless those directories existed before we even tried to
11519            // install.
11520            if(updatedSettings) {
11521                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11522                deletePackageLI(
11523                        pkgName, null, true, allUsers, perUserInstalled,
11524                        PackageManager.DELETE_KEEP_DATA,
11525                                res.removedInfo, true);
11526            }
11527            // Since we failed to install the new package we need to restore the old
11528            // package that we deleted.
11529            if (deletedPkg) {
11530                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11531                File restoreFile = new File(deletedPackage.codePath);
11532                // Parse old package
11533                boolean oldExternal = isExternal(deletedPackage);
11534                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11535                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11536                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11537                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11538                try {
11539                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11540                } catch (PackageManagerException e) {
11541                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11542                            + e.getMessage());
11543                    return;
11544                }
11545                // Restore of old package succeeded. Update permissions.
11546                // writer
11547                synchronized (mPackages) {
11548                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11549                            UPDATE_PERMISSIONS_ALL);
11550                    // can downgrade to reader
11551                    mSettings.writeLPr();
11552                }
11553                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11554            }
11555        }
11556    }
11557
11558    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11559            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11560            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11561            String volumeUuid, PackageInstalledInfo res) {
11562        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11563                + ", old=" + deletedPackage);
11564        boolean disabledSystem = false;
11565        boolean updatedSettings = false;
11566        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11567        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11568                != 0) {
11569            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11570        }
11571        String packageName = deletedPackage.packageName;
11572        if (packageName == null) {
11573            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11574                    "Attempt to delete null packageName.");
11575            return;
11576        }
11577        PackageParser.Package oldPkg;
11578        PackageSetting oldPkgSetting;
11579        // reader
11580        synchronized (mPackages) {
11581            oldPkg = mPackages.get(packageName);
11582            oldPkgSetting = mSettings.mPackages.get(packageName);
11583            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11584                    (oldPkgSetting == null)) {
11585                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11586                        "Couldn't find package:" + packageName + " information");
11587                return;
11588            }
11589        }
11590
11591        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11592        res.removedInfo.removedPackage = packageName;
11593        // Remove existing system package
11594        removePackageLI(oldPkgSetting, true);
11595        // writer
11596        synchronized (mPackages) {
11597            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11598            if (!disabledSystem && deletedPackage != null) {
11599                // We didn't need to disable the .apk as a current system package,
11600                // which means we are replacing another update that is already
11601                // installed.  We need to make sure to delete the older one's .apk.
11602                res.removedInfo.args = createInstallArgsForExisting(0,
11603                        deletedPackage.applicationInfo.getCodePath(),
11604                        deletedPackage.applicationInfo.getResourcePath(),
11605                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11606            } else {
11607                res.removedInfo.args = null;
11608            }
11609        }
11610
11611        // Successfully disabled the old package. Now proceed with re-installation
11612        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11613
11614        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11615        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11616
11617        PackageParser.Package newPackage = null;
11618        try {
11619            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11620            if (newPackage.mExtras != null) {
11621                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11622                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11623                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11624
11625                // is the update attempting to change shared user? that isn't going to work...
11626                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11627                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11628                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11629                            + " to " + newPkgSetting.sharedUser);
11630                    updatedSettings = true;
11631                }
11632            }
11633
11634            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11635                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11636                        perUserInstalled, res, user);
11637                updatedSettings = true;
11638            }
11639
11640        } catch (PackageManagerException e) {
11641            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11642        }
11643
11644        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11645            // Re installation failed. Restore old information
11646            // Remove new pkg information
11647            if (newPackage != null) {
11648                removeInstalledPackageLI(newPackage, true);
11649            }
11650            // Add back the old system package
11651            try {
11652                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11653            } catch (PackageManagerException e) {
11654                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11655            }
11656            // Restore the old system information in Settings
11657            synchronized (mPackages) {
11658                if (disabledSystem) {
11659                    mSettings.enableSystemPackageLPw(packageName);
11660                }
11661                if (updatedSettings) {
11662                    mSettings.setInstallerPackageName(packageName,
11663                            oldPkgSetting.installerPackageName);
11664                }
11665                mSettings.writeLPr();
11666            }
11667        }
11668    }
11669
11670    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11671            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11672            UserHandle user) {
11673        String pkgName = newPackage.packageName;
11674        synchronized (mPackages) {
11675            //write settings. the installStatus will be incomplete at this stage.
11676            //note that the new package setting would have already been
11677            //added to mPackages. It hasn't been persisted yet.
11678            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11679            mSettings.writeLPr();
11680        }
11681
11682        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11683
11684        synchronized (mPackages) {
11685            updatePermissionsLPw(newPackage.packageName, newPackage,
11686                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11687                            ? UPDATE_PERMISSIONS_ALL : 0));
11688            // For system-bundled packages, we assume that installing an upgraded version
11689            // of the package implies that the user actually wants to run that new code,
11690            // so we enable the package.
11691            PackageSetting ps = mSettings.mPackages.get(pkgName);
11692            if (ps != null) {
11693                if (isSystemApp(newPackage)) {
11694                    // NB: implicit assumption that system package upgrades apply to all users
11695                    if (DEBUG_INSTALL) {
11696                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11697                    }
11698                    if (res.origUsers != null) {
11699                        for (int userHandle : res.origUsers) {
11700                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11701                                    userHandle, installerPackageName);
11702                        }
11703                    }
11704                    // Also convey the prior install/uninstall state
11705                    if (allUsers != null && perUserInstalled != null) {
11706                        for (int i = 0; i < allUsers.length; i++) {
11707                            if (DEBUG_INSTALL) {
11708                                Slog.d(TAG, "    user " + allUsers[i]
11709                                        + " => " + perUserInstalled[i]);
11710                            }
11711                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11712                        }
11713                        // these install state changes will be persisted in the
11714                        // upcoming call to mSettings.writeLPr().
11715                    }
11716                }
11717                // It's implied that when a user requests installation, they want the app to be
11718                // installed and enabled.
11719                int userId = user.getIdentifier();
11720                if (userId != UserHandle.USER_ALL) {
11721                    ps.setInstalled(true, userId);
11722                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11723                }
11724            }
11725            res.name = pkgName;
11726            res.uid = newPackage.applicationInfo.uid;
11727            res.pkg = newPackage;
11728            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11729            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11730            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11731            //to update install status
11732            mSettings.writeLPr();
11733        }
11734    }
11735
11736    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11737        final int installFlags = args.installFlags;
11738        final String installerPackageName = args.installerPackageName;
11739        final String volumeUuid = args.volumeUuid;
11740        final File tmpPackageFile = new File(args.getCodePath());
11741        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11742        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11743                || (args.volumeUuid != null));
11744        boolean replace = false;
11745        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11746        if (args.move != null) {
11747            // moving a complete application; perfom an initial scan on the new install location
11748            scanFlags |= SCAN_INITIAL;
11749        }
11750        // Result object to be returned
11751        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11752
11753        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11754        // Retrieve PackageSettings and parse package
11755        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11756                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11757                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11758        PackageParser pp = new PackageParser();
11759        pp.setSeparateProcesses(mSeparateProcesses);
11760        pp.setDisplayMetrics(mMetrics);
11761
11762        final PackageParser.Package pkg;
11763        try {
11764            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11765        } catch (PackageParserException e) {
11766            res.setError("Failed parse during installPackageLI", e);
11767            return;
11768        }
11769
11770        // Mark that we have an install time CPU ABI override.
11771        pkg.cpuAbiOverride = args.abiOverride;
11772
11773        String pkgName = res.name = pkg.packageName;
11774        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11775            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11776                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11777                return;
11778            }
11779        }
11780
11781        try {
11782            pp.collectCertificates(pkg, parseFlags);
11783            pp.collectManifestDigest(pkg);
11784        } catch (PackageParserException e) {
11785            res.setError("Failed collect during installPackageLI", e);
11786            return;
11787        }
11788
11789        /* If the installer passed in a manifest digest, compare it now. */
11790        if (args.manifestDigest != null) {
11791            if (DEBUG_INSTALL) {
11792                final String parsedManifest = pkg.manifestDigest == null ? "null"
11793                        : pkg.manifestDigest.toString();
11794                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11795                        + parsedManifest);
11796            }
11797
11798            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11799                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11800                return;
11801            }
11802        } else if (DEBUG_INSTALL) {
11803            final String parsedManifest = pkg.manifestDigest == null
11804                    ? "null" : pkg.manifestDigest.toString();
11805            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11806        }
11807
11808        // Get rid of all references to package scan path via parser.
11809        pp = null;
11810        String oldCodePath = null;
11811        boolean systemApp = false;
11812        synchronized (mPackages) {
11813            // Check if installing already existing package
11814            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11815                String oldName = mSettings.mRenamedPackages.get(pkgName);
11816                if (pkg.mOriginalPackages != null
11817                        && pkg.mOriginalPackages.contains(oldName)
11818                        && mPackages.containsKey(oldName)) {
11819                    // This package is derived from an original package,
11820                    // and this device has been updating from that original
11821                    // name.  We must continue using the original name, so
11822                    // rename the new package here.
11823                    pkg.setPackageName(oldName);
11824                    pkgName = pkg.packageName;
11825                    replace = true;
11826                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11827                            + oldName + " pkgName=" + pkgName);
11828                } else if (mPackages.containsKey(pkgName)) {
11829                    // This package, under its official name, already exists
11830                    // on the device; we should replace it.
11831                    replace = true;
11832                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11833                }
11834
11835                // Prevent apps opting out from runtime permissions
11836                if (replace) {
11837                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11838                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11839                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11840                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11841                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11842                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11843                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11844                                        + " doesn't support runtime permissions but the old"
11845                                        + " target SDK " + oldTargetSdk + " does.");
11846                        return;
11847                    }
11848                }
11849            }
11850
11851            PackageSetting ps = mSettings.mPackages.get(pkgName);
11852            if (ps != null) {
11853                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11854
11855                // Quick sanity check that we're signed correctly if updating;
11856                // we'll check this again later when scanning, but we want to
11857                // bail early here before tripping over redefined permissions.
11858                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11859                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11860                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11861                                + pkg.packageName + " upgrade keys do not match the "
11862                                + "previously installed version");
11863                        return;
11864                    }
11865                } else {
11866                    try {
11867                        verifySignaturesLP(ps, pkg);
11868                    } catch (PackageManagerException e) {
11869                        res.setError(e.error, e.getMessage());
11870                        return;
11871                    }
11872                }
11873
11874                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11875                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11876                    systemApp = (ps.pkg.applicationInfo.flags &
11877                            ApplicationInfo.FLAG_SYSTEM) != 0;
11878                }
11879                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11880            }
11881
11882            // Check whether the newly-scanned package wants to define an already-defined perm
11883            int N = pkg.permissions.size();
11884            for (int i = N-1; i >= 0; i--) {
11885                PackageParser.Permission perm = pkg.permissions.get(i);
11886                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11887                if (bp != null) {
11888                    // If the defining package is signed with our cert, it's okay.  This
11889                    // also includes the "updating the same package" case, of course.
11890                    // "updating same package" could also involve key-rotation.
11891                    final boolean sigsOk;
11892                    if (bp.sourcePackage.equals(pkg.packageName)
11893                            && (bp.packageSetting instanceof PackageSetting)
11894                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
11895                                    scanFlags))) {
11896                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11897                    } else {
11898                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11899                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11900                    }
11901                    if (!sigsOk) {
11902                        // If the owning package is the system itself, we log but allow
11903                        // install to proceed; we fail the install on all other permission
11904                        // redefinitions.
11905                        if (!bp.sourcePackage.equals("android")) {
11906                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11907                                    + pkg.packageName + " attempting to redeclare permission "
11908                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11909                            res.origPermission = perm.info.name;
11910                            res.origPackage = bp.sourcePackage;
11911                            return;
11912                        } else {
11913                            Slog.w(TAG, "Package " + pkg.packageName
11914                                    + " attempting to redeclare system permission "
11915                                    + perm.info.name + "; ignoring new declaration");
11916                            pkg.permissions.remove(i);
11917                        }
11918                    }
11919                }
11920            }
11921
11922        }
11923
11924        if (systemApp && onExternal) {
11925            // Disable updates to system apps on sdcard
11926            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11927                    "Cannot install updates to system apps on sdcard");
11928            return;
11929        }
11930
11931        if (args.move != null) {
11932            // We did an in-place move, so dex is ready to roll
11933            scanFlags |= SCAN_NO_DEX;
11934            scanFlags |= SCAN_MOVE;
11935        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
11936            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
11937            scanFlags |= SCAN_NO_DEX;
11938
11939            try {
11940                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
11941                        true /* extract libs */);
11942            } catch (PackageManagerException pme) {
11943                Slog.e(TAG, "Error deriving application ABI", pme);
11944                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
11945                return;
11946            }
11947
11948            // Run dexopt before old package gets removed, to minimize time when app is unavailable
11949            int result = mPackageDexOptimizer
11950                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
11951                            false /* defer */, false /* inclDependencies */);
11952            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11953                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11954                return;
11955            }
11956        }
11957
11958        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11959            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11960            return;
11961        }
11962
11963        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
11964
11965        if (replace) {
11966            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
11967                    installerPackageName, volumeUuid, res);
11968        } else {
11969            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11970                    args.user, installerPackageName, volumeUuid, res);
11971        }
11972        synchronized (mPackages) {
11973            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11974            if (ps != null) {
11975                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11976            }
11977        }
11978    }
11979
11980    private void startIntentFilterVerifications(int userId, boolean replacing,
11981            PackageParser.Package pkg) {
11982        if (mIntentFilterVerifierComponent == null) {
11983            Slog.w(TAG, "No IntentFilter verification will not be done as "
11984                    + "there is no IntentFilterVerifier available!");
11985            return;
11986        }
11987
11988        final int verifierUid = getPackageUid(
11989                mIntentFilterVerifierComponent.getPackageName(),
11990                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11991
11992        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11993        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11994        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
11995        mHandler.sendMessage(msg);
11996    }
11997
11998    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
11999            PackageParser.Package pkg) {
12000        int size = pkg.activities.size();
12001        if (size == 0) {
12002            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12003                    "No activity, so no need to verify any IntentFilter!");
12004            return;
12005        }
12006
12007        final boolean hasDomainURLs = hasDomainURLs(pkg);
12008        if (!hasDomainURLs) {
12009            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12010                    "No domain URLs, so no need to verify any IntentFilter!");
12011            return;
12012        }
12013
12014        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12015                + " if any IntentFilter from the " + size
12016                + " Activities needs verification ...");
12017
12018        int count = 0;
12019        final String packageName = pkg.packageName;
12020
12021        synchronized (mPackages) {
12022            // If this is a new install and we see that we've already run verification for this
12023            // package, we have nothing to do: it means the state was restored from backup.
12024            if (!replacing) {
12025                IntentFilterVerificationInfo ivi =
12026                        mSettings.getIntentFilterVerificationLPr(packageName);
12027                if (ivi != null) {
12028                    if (DEBUG_DOMAIN_VERIFICATION) {
12029                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12030                                + ivi.getStatusString());
12031                    }
12032                    return;
12033                }
12034            }
12035
12036            // If any filters need to be verified, then all need to be.
12037            boolean needToVerify = false;
12038            for (PackageParser.Activity a : pkg.activities) {
12039                for (ActivityIntentInfo filter : a.intents) {
12040                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12041                        if (DEBUG_DOMAIN_VERIFICATION) {
12042                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12043                        }
12044                        needToVerify = true;
12045                        break;
12046                    }
12047                }
12048            }
12049
12050            if (needToVerify) {
12051                final int verificationId = mIntentFilterVerificationToken++;
12052                for (PackageParser.Activity a : pkg.activities) {
12053                    for (ActivityIntentInfo filter : a.intents) {
12054                        if (filter.hasOnlyWebDataURI() && needsNetworkVerificationLPr(filter)) {
12055                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12056                                    "Verification needed for IntentFilter:" + filter.toString());
12057                            mIntentFilterVerifier.addOneIntentFilterVerification(
12058                                    verifierUid, userId, verificationId, filter, packageName);
12059                            count++;
12060                        }
12061                    }
12062                }
12063            }
12064        }
12065
12066        if (count > 0) {
12067            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12068                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12069                    +  " for userId:" + userId);
12070            mIntentFilterVerifier.startVerifications(userId);
12071        } else {
12072            if (DEBUG_DOMAIN_VERIFICATION) {
12073                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12074            }
12075        }
12076    }
12077
12078    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12079        final ComponentName cn  = filter.activity.getComponentName();
12080        final String packageName = cn.getPackageName();
12081
12082        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12083                packageName);
12084        if (ivi == null) {
12085            return true;
12086        }
12087        int status = ivi.getStatus();
12088        switch (status) {
12089            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12090            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12091                return true;
12092
12093            default:
12094                // Nothing to do
12095                return false;
12096        }
12097    }
12098
12099    private static boolean isMultiArch(PackageSetting ps) {
12100        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12101    }
12102
12103    private static boolean isMultiArch(ApplicationInfo info) {
12104        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12105    }
12106
12107    private static boolean isExternal(PackageParser.Package pkg) {
12108        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12109    }
12110
12111    private static boolean isExternal(PackageSetting ps) {
12112        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12113    }
12114
12115    private static boolean isExternal(ApplicationInfo info) {
12116        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12117    }
12118
12119    private static boolean isSystemApp(PackageParser.Package pkg) {
12120        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12121    }
12122
12123    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12124        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12125    }
12126
12127    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12128        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12129    }
12130
12131    private static boolean isSystemApp(PackageSetting ps) {
12132        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12133    }
12134
12135    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12136        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12137    }
12138
12139    private int packageFlagsToInstallFlags(PackageSetting ps) {
12140        int installFlags = 0;
12141        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12142            // This existing package was an external ASEC install when we have
12143            // the external flag without a UUID
12144            installFlags |= PackageManager.INSTALL_EXTERNAL;
12145        }
12146        if (ps.isForwardLocked()) {
12147            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12148        }
12149        return installFlags;
12150    }
12151
12152    private void deleteTempPackageFiles() {
12153        final FilenameFilter filter = new FilenameFilter() {
12154            public boolean accept(File dir, String name) {
12155                return name.startsWith("vmdl") && name.endsWith(".tmp");
12156            }
12157        };
12158        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12159            file.delete();
12160        }
12161    }
12162
12163    @Override
12164    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12165            int flags) {
12166        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12167                flags);
12168    }
12169
12170    @Override
12171    public void deletePackage(final String packageName,
12172            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12173        mContext.enforceCallingOrSelfPermission(
12174                android.Manifest.permission.DELETE_PACKAGES, null);
12175        final int uid = Binder.getCallingUid();
12176        if (UserHandle.getUserId(uid) != userId) {
12177            mContext.enforceCallingPermission(
12178                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12179                    "deletePackage for user " + userId);
12180        }
12181        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12182            try {
12183                observer.onPackageDeleted(packageName,
12184                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12185            } catch (RemoteException re) {
12186            }
12187            return;
12188        }
12189
12190        boolean uninstallBlocked = false;
12191        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12192            int[] users = sUserManager.getUserIds();
12193            for (int i = 0; i < users.length; ++i) {
12194                if (getBlockUninstallForUser(packageName, users[i])) {
12195                    uninstallBlocked = true;
12196                    break;
12197                }
12198            }
12199        } else {
12200            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12201        }
12202        if (uninstallBlocked) {
12203            try {
12204                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12205                        null);
12206            } catch (RemoteException re) {
12207            }
12208            return;
12209        }
12210
12211        if (DEBUG_REMOVE) {
12212            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12213        }
12214        // Queue up an async operation since the package deletion may take a little while.
12215        mHandler.post(new Runnable() {
12216            public void run() {
12217                mHandler.removeCallbacks(this);
12218                final int returnCode = deletePackageX(packageName, userId, flags);
12219                if (observer != null) {
12220                    try {
12221                        observer.onPackageDeleted(packageName, returnCode, null);
12222                    } catch (RemoteException e) {
12223                        Log.i(TAG, "Observer no longer exists.");
12224                    } //end catch
12225                } //end if
12226            } //end run
12227        });
12228    }
12229
12230    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12231        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12232                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12233        try {
12234            if (dpm != null) {
12235                if (dpm.isDeviceOwner(packageName)) {
12236                    return true;
12237                }
12238                int[] users;
12239                if (userId == UserHandle.USER_ALL) {
12240                    users = sUserManager.getUserIds();
12241                } else {
12242                    users = new int[]{userId};
12243                }
12244                for (int i = 0; i < users.length; ++i) {
12245                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12246                        return true;
12247                    }
12248                }
12249            }
12250        } catch (RemoteException e) {
12251        }
12252        return false;
12253    }
12254
12255    /**
12256     *  This method is an internal method that could be get invoked either
12257     *  to delete an installed package or to clean up a failed installation.
12258     *  After deleting an installed package, a broadcast is sent to notify any
12259     *  listeners that the package has been installed. For cleaning up a failed
12260     *  installation, the broadcast is not necessary since the package's
12261     *  installation wouldn't have sent the initial broadcast either
12262     *  The key steps in deleting a package are
12263     *  deleting the package information in internal structures like mPackages,
12264     *  deleting the packages base directories through installd
12265     *  updating mSettings to reflect current status
12266     *  persisting settings for later use
12267     *  sending a broadcast if necessary
12268     */
12269    private int deletePackageX(String packageName, int userId, int flags) {
12270        final PackageRemovedInfo info = new PackageRemovedInfo();
12271        final boolean res;
12272
12273        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12274                ? UserHandle.ALL : new UserHandle(userId);
12275
12276        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12277            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12278            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12279        }
12280
12281        boolean removedForAllUsers = false;
12282        boolean systemUpdate = false;
12283
12284        // for the uninstall-updates case and restricted profiles, remember the per-
12285        // userhandle installed state
12286        int[] allUsers;
12287        boolean[] perUserInstalled;
12288        synchronized (mPackages) {
12289            PackageSetting ps = mSettings.mPackages.get(packageName);
12290            allUsers = sUserManager.getUserIds();
12291            perUserInstalled = new boolean[allUsers.length];
12292            for (int i = 0; i < allUsers.length; i++) {
12293                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12294            }
12295        }
12296
12297        synchronized (mInstallLock) {
12298            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12299            res = deletePackageLI(packageName, removeForUser,
12300                    true, allUsers, perUserInstalled,
12301                    flags | REMOVE_CHATTY, info, true);
12302            systemUpdate = info.isRemovedPackageSystemUpdate;
12303            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12304                removedForAllUsers = true;
12305            }
12306            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12307                    + " removedForAllUsers=" + removedForAllUsers);
12308        }
12309
12310        if (res) {
12311            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12312
12313            // If the removed package was a system update, the old system package
12314            // was re-enabled; we need to broadcast this information
12315            if (systemUpdate) {
12316                Bundle extras = new Bundle(1);
12317                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12318                        ? info.removedAppId : info.uid);
12319                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12320
12321                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12322                        extras, null, null, null);
12323                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12324                        extras, null, null, null);
12325                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12326                        null, packageName, null, null);
12327            }
12328        }
12329        // Force a gc here.
12330        Runtime.getRuntime().gc();
12331        // Delete the resources here after sending the broadcast to let
12332        // other processes clean up before deleting resources.
12333        if (info.args != null) {
12334            synchronized (mInstallLock) {
12335                info.args.doPostDeleteLI(true);
12336            }
12337        }
12338
12339        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12340    }
12341
12342    class PackageRemovedInfo {
12343        String removedPackage;
12344        int uid = -1;
12345        int removedAppId = -1;
12346        int[] removedUsers = null;
12347        boolean isRemovedPackageSystemUpdate = false;
12348        // Clean up resources deleted packages.
12349        InstallArgs args = null;
12350
12351        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12352            Bundle extras = new Bundle(1);
12353            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12354            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12355            if (replacing) {
12356                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12357            }
12358            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12359            if (removedPackage != null) {
12360                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12361                        extras, null, null, removedUsers);
12362                if (fullRemove && !replacing) {
12363                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12364                            extras, null, null, removedUsers);
12365                }
12366            }
12367            if (removedAppId >= 0) {
12368                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12369                        removedUsers);
12370            }
12371        }
12372    }
12373
12374    /*
12375     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12376     * flag is not set, the data directory is removed as well.
12377     * make sure this flag is set for partially installed apps. If not its meaningless to
12378     * delete a partially installed application.
12379     */
12380    private void removePackageDataLI(PackageSetting ps,
12381            int[] allUserHandles, boolean[] perUserInstalled,
12382            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12383        String packageName = ps.name;
12384        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12385        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12386        // Retrieve object to delete permissions for shared user later on
12387        final PackageSetting deletedPs;
12388        // reader
12389        synchronized (mPackages) {
12390            deletedPs = mSettings.mPackages.get(packageName);
12391            if (outInfo != null) {
12392                outInfo.removedPackage = packageName;
12393                outInfo.removedUsers = deletedPs != null
12394                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12395                        : null;
12396            }
12397        }
12398        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12399            removeDataDirsLI(ps.volumeUuid, packageName);
12400            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12401        }
12402        // writer
12403        synchronized (mPackages) {
12404            if (deletedPs != null) {
12405                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12406                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12407                    clearDefaultBrowserIfNeeded(packageName);
12408                    if (outInfo != null) {
12409                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12410                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12411                    }
12412                    updatePermissionsLPw(deletedPs.name, null, 0);
12413                    if (deletedPs.sharedUser != null) {
12414                        // Remove permissions associated with package. Since runtime
12415                        // permissions are per user we have to kill the removed package
12416                        // or packages running under the shared user of the removed
12417                        // package if revoking the permissions requested only by the removed
12418                        // package is successful and this causes a change in gids.
12419                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12420                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12421                                    userId);
12422                            if (userIdToKill == UserHandle.USER_ALL
12423                                    || userIdToKill >= UserHandle.USER_OWNER) {
12424                                // If gids changed for this user, kill all affected packages.
12425                                mHandler.post(new Runnable() {
12426                                    @Override
12427                                    public void run() {
12428                                        // This has to happen with no lock held.
12429                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12430                                                KILL_APP_REASON_GIDS_CHANGED);
12431                                    }
12432                                });
12433                            break;
12434                            }
12435                        }
12436                    }
12437                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12438                }
12439                // make sure to preserve per-user disabled state if this removal was just
12440                // a downgrade of a system app to the factory package
12441                if (allUserHandles != null && perUserInstalled != null) {
12442                    if (DEBUG_REMOVE) {
12443                        Slog.d(TAG, "Propagating install state across downgrade");
12444                    }
12445                    for (int i = 0; i < allUserHandles.length; i++) {
12446                        if (DEBUG_REMOVE) {
12447                            Slog.d(TAG, "    user " + allUserHandles[i]
12448                                    + " => " + perUserInstalled[i]);
12449                        }
12450                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12451                    }
12452                }
12453            }
12454            // can downgrade to reader
12455            if (writeSettings) {
12456                // Save settings now
12457                mSettings.writeLPr();
12458            }
12459        }
12460        if (outInfo != null) {
12461            // A user ID was deleted here. Go through all users and remove it
12462            // from KeyStore.
12463            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12464        }
12465    }
12466
12467    static boolean locationIsPrivileged(File path) {
12468        try {
12469            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12470                    .getCanonicalPath();
12471            return path.getCanonicalPath().startsWith(privilegedAppDir);
12472        } catch (IOException e) {
12473            Slog.e(TAG, "Unable to access code path " + path);
12474        }
12475        return false;
12476    }
12477
12478    /*
12479     * Tries to delete system package.
12480     */
12481    private boolean deleteSystemPackageLI(PackageSetting newPs,
12482            int[] allUserHandles, boolean[] perUserInstalled,
12483            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12484        final boolean applyUserRestrictions
12485                = (allUserHandles != null) && (perUserInstalled != null);
12486        PackageSetting disabledPs = null;
12487        // Confirm if the system package has been updated
12488        // An updated system app can be deleted. This will also have to restore
12489        // the system pkg from system partition
12490        // reader
12491        synchronized (mPackages) {
12492            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12493        }
12494        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12495                + " disabledPs=" + disabledPs);
12496        if (disabledPs == null) {
12497            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12498            return false;
12499        } else if (DEBUG_REMOVE) {
12500            Slog.d(TAG, "Deleting system pkg from data partition");
12501        }
12502        if (DEBUG_REMOVE) {
12503            if (applyUserRestrictions) {
12504                Slog.d(TAG, "Remembering install states:");
12505                for (int i = 0; i < allUserHandles.length; i++) {
12506                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12507                }
12508            }
12509        }
12510        // Delete the updated package
12511        outInfo.isRemovedPackageSystemUpdate = true;
12512        if (disabledPs.versionCode < newPs.versionCode) {
12513            // Delete data for downgrades
12514            flags &= ~PackageManager.DELETE_KEEP_DATA;
12515        } else {
12516            // Preserve data by setting flag
12517            flags |= PackageManager.DELETE_KEEP_DATA;
12518        }
12519        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12520                allUserHandles, perUserInstalled, outInfo, writeSettings);
12521        if (!ret) {
12522            return false;
12523        }
12524        // writer
12525        synchronized (mPackages) {
12526            // Reinstate the old system package
12527            mSettings.enableSystemPackageLPw(newPs.name);
12528            // Remove any native libraries from the upgraded package.
12529            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12530        }
12531        // Install the system package
12532        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12533        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12534        if (locationIsPrivileged(disabledPs.codePath)) {
12535            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12536        }
12537
12538        final PackageParser.Package newPkg;
12539        try {
12540            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12541        } catch (PackageManagerException e) {
12542            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12543            return false;
12544        }
12545
12546        // writer
12547        synchronized (mPackages) {
12548            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12549            updatePermissionsLPw(newPkg.packageName, newPkg,
12550                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12551            if (applyUserRestrictions) {
12552                if (DEBUG_REMOVE) {
12553                    Slog.d(TAG, "Propagating install state across reinstall");
12554                }
12555                for (int i = 0; i < allUserHandles.length; i++) {
12556                    if (DEBUG_REMOVE) {
12557                        Slog.d(TAG, "    user " + allUserHandles[i]
12558                                + " => " + perUserInstalled[i]);
12559                    }
12560                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12561                }
12562                // Regardless of writeSettings we need to ensure that this restriction
12563                // state propagation is persisted
12564                mSettings.writeAllUsersPackageRestrictionsLPr();
12565            }
12566            // can downgrade to reader here
12567            if (writeSettings) {
12568                mSettings.writeLPr();
12569            }
12570        }
12571        return true;
12572    }
12573
12574    private boolean deleteInstalledPackageLI(PackageSetting ps,
12575            boolean deleteCodeAndResources, int flags,
12576            int[] allUserHandles, boolean[] perUserInstalled,
12577            PackageRemovedInfo outInfo, boolean writeSettings) {
12578        if (outInfo != null) {
12579            outInfo.uid = ps.appId;
12580        }
12581
12582        // Delete package data from internal structures and also remove data if flag is set
12583        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12584
12585        // Delete application code and resources
12586        if (deleteCodeAndResources && (outInfo != null)) {
12587            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12588                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12589            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12590        }
12591        return true;
12592    }
12593
12594    @Override
12595    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12596            int userId) {
12597        mContext.enforceCallingOrSelfPermission(
12598                android.Manifest.permission.DELETE_PACKAGES, null);
12599        synchronized (mPackages) {
12600            PackageSetting ps = mSettings.mPackages.get(packageName);
12601            if (ps == null) {
12602                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12603                return false;
12604            }
12605            if (!ps.getInstalled(userId)) {
12606                // Can't block uninstall for an app that is not installed or enabled.
12607                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12608                return false;
12609            }
12610            ps.setBlockUninstall(blockUninstall, userId);
12611            mSettings.writePackageRestrictionsLPr(userId);
12612        }
12613        return true;
12614    }
12615
12616    @Override
12617    public boolean getBlockUninstallForUser(String packageName, int userId) {
12618        synchronized (mPackages) {
12619            PackageSetting ps = mSettings.mPackages.get(packageName);
12620            if (ps == null) {
12621                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12622                return false;
12623            }
12624            return ps.getBlockUninstall(userId);
12625        }
12626    }
12627
12628    /*
12629     * This method handles package deletion in general
12630     */
12631    private boolean deletePackageLI(String packageName, UserHandle user,
12632            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12633            int flags, PackageRemovedInfo outInfo,
12634            boolean writeSettings) {
12635        if (packageName == null) {
12636            Slog.w(TAG, "Attempt to delete null packageName.");
12637            return false;
12638        }
12639        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12640        PackageSetting ps;
12641        boolean dataOnly = false;
12642        int removeUser = -1;
12643        int appId = -1;
12644        synchronized (mPackages) {
12645            ps = mSettings.mPackages.get(packageName);
12646            if (ps == null) {
12647                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12648                return false;
12649            }
12650            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12651                    && user.getIdentifier() != UserHandle.USER_ALL) {
12652                // The caller is asking that the package only be deleted for a single
12653                // user.  To do this, we just mark its uninstalled state and delete
12654                // its data.  If this is a system app, we only allow this to happen if
12655                // they have set the special DELETE_SYSTEM_APP which requests different
12656                // semantics than normal for uninstalling system apps.
12657                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12658                ps.setUserState(user.getIdentifier(),
12659                        COMPONENT_ENABLED_STATE_DEFAULT,
12660                        false, //installed
12661                        true,  //stopped
12662                        true,  //notLaunched
12663                        false, //hidden
12664                        null, null, null,
12665                        false, // blockUninstall
12666                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12667                if (!isSystemApp(ps)) {
12668                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12669                        // Other user still have this package installed, so all
12670                        // we need to do is clear this user's data and save that
12671                        // it is uninstalled.
12672                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12673                        removeUser = user.getIdentifier();
12674                        appId = ps.appId;
12675                        scheduleWritePackageRestrictionsLocked(removeUser);
12676                    } else {
12677                        // We need to set it back to 'installed' so the uninstall
12678                        // broadcasts will be sent correctly.
12679                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12680                        ps.setInstalled(true, user.getIdentifier());
12681                    }
12682                } else {
12683                    // This is a system app, so we assume that the
12684                    // other users still have this package installed, so all
12685                    // we need to do is clear this user's data and save that
12686                    // it is uninstalled.
12687                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12688                    removeUser = user.getIdentifier();
12689                    appId = ps.appId;
12690                    scheduleWritePackageRestrictionsLocked(removeUser);
12691                }
12692            }
12693        }
12694
12695        if (removeUser >= 0) {
12696            // From above, we determined that we are deleting this only
12697            // for a single user.  Continue the work here.
12698            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12699            if (outInfo != null) {
12700                outInfo.removedPackage = packageName;
12701                outInfo.removedAppId = appId;
12702                outInfo.removedUsers = new int[] {removeUser};
12703            }
12704            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12705            removeKeystoreDataIfNeeded(removeUser, appId);
12706            schedulePackageCleaning(packageName, removeUser, false);
12707            synchronized (mPackages) {
12708                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12709                    scheduleWritePackageRestrictionsLocked(removeUser);
12710                }
12711                revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(),
12712                        removeUser);
12713            }
12714            return true;
12715        }
12716
12717        if (dataOnly) {
12718            // Delete application data first
12719            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12720            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12721            return true;
12722        }
12723
12724        boolean ret = false;
12725        if (isSystemApp(ps)) {
12726            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12727            // When an updated system application is deleted we delete the existing resources as well and
12728            // fall back to existing code in system partition
12729            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12730                    flags, outInfo, writeSettings);
12731        } else {
12732            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12733            // Kill application pre-emptively especially for apps on sd.
12734            killApplication(packageName, ps.appId, "uninstall pkg");
12735            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12736                    allUserHandles, perUserInstalled,
12737                    outInfo, writeSettings);
12738        }
12739
12740        return ret;
12741    }
12742
12743    private final class ClearStorageConnection implements ServiceConnection {
12744        IMediaContainerService mContainerService;
12745
12746        @Override
12747        public void onServiceConnected(ComponentName name, IBinder service) {
12748            synchronized (this) {
12749                mContainerService = IMediaContainerService.Stub.asInterface(service);
12750                notifyAll();
12751            }
12752        }
12753
12754        @Override
12755        public void onServiceDisconnected(ComponentName name) {
12756        }
12757    }
12758
12759    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12760        final boolean mounted;
12761        if (Environment.isExternalStorageEmulated()) {
12762            mounted = true;
12763        } else {
12764            final String status = Environment.getExternalStorageState();
12765
12766            mounted = status.equals(Environment.MEDIA_MOUNTED)
12767                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12768        }
12769
12770        if (!mounted) {
12771            return;
12772        }
12773
12774        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12775        int[] users;
12776        if (userId == UserHandle.USER_ALL) {
12777            users = sUserManager.getUserIds();
12778        } else {
12779            users = new int[] { userId };
12780        }
12781        final ClearStorageConnection conn = new ClearStorageConnection();
12782        if (mContext.bindServiceAsUser(
12783                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12784            try {
12785                for (int curUser : users) {
12786                    long timeout = SystemClock.uptimeMillis() + 5000;
12787                    synchronized (conn) {
12788                        long now = SystemClock.uptimeMillis();
12789                        while (conn.mContainerService == null && now < timeout) {
12790                            try {
12791                                conn.wait(timeout - now);
12792                            } catch (InterruptedException e) {
12793                            }
12794                        }
12795                    }
12796                    if (conn.mContainerService == null) {
12797                        return;
12798                    }
12799
12800                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12801                    clearDirectory(conn.mContainerService,
12802                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12803                    if (allData) {
12804                        clearDirectory(conn.mContainerService,
12805                                userEnv.buildExternalStorageAppDataDirs(packageName));
12806                        clearDirectory(conn.mContainerService,
12807                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12808                    }
12809                }
12810            } finally {
12811                mContext.unbindService(conn);
12812            }
12813        }
12814    }
12815
12816    @Override
12817    public void clearApplicationUserData(final String packageName,
12818            final IPackageDataObserver observer, final int userId) {
12819        mContext.enforceCallingOrSelfPermission(
12820                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12821        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12822        // Queue up an async operation since the package deletion may take a little while.
12823        mHandler.post(new Runnable() {
12824            public void run() {
12825                mHandler.removeCallbacks(this);
12826                final boolean succeeded;
12827                synchronized (mInstallLock) {
12828                    succeeded = clearApplicationUserDataLI(packageName, userId);
12829                }
12830                clearExternalStorageDataSync(packageName, userId, true);
12831                if (succeeded) {
12832                    // invoke DeviceStorageMonitor's update method to clear any notifications
12833                    DeviceStorageMonitorInternal
12834                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12835                    if (dsm != null) {
12836                        dsm.checkMemory();
12837                    }
12838                }
12839                if(observer != null) {
12840                    try {
12841                        observer.onRemoveCompleted(packageName, succeeded);
12842                    } catch (RemoteException e) {
12843                        Log.i(TAG, "Observer no longer exists.");
12844                    }
12845                } //end if observer
12846            } //end run
12847        });
12848    }
12849
12850    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12851        if (packageName == null) {
12852            Slog.w(TAG, "Attempt to delete null packageName.");
12853            return false;
12854        }
12855
12856        // Try finding details about the requested package
12857        PackageParser.Package pkg;
12858        synchronized (mPackages) {
12859            pkg = mPackages.get(packageName);
12860            if (pkg == null) {
12861                final PackageSetting ps = mSettings.mPackages.get(packageName);
12862                if (ps != null) {
12863                    pkg = ps.pkg;
12864                }
12865            }
12866
12867            if (pkg == null) {
12868                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12869                return false;
12870            }
12871
12872            PackageSetting ps = (PackageSetting) pkg.mExtras;
12873            PermissionsState permissionsState = ps.getPermissionsState();
12874            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
12875        }
12876
12877        // Always delete data directories for package, even if we found no other
12878        // record of app. This helps users recover from UID mismatches without
12879        // resorting to a full data wipe.
12880        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12881        if (retCode < 0) {
12882            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12883            return false;
12884        }
12885
12886        final int appId = pkg.applicationInfo.uid;
12887        removeKeystoreDataIfNeeded(userId, appId);
12888
12889        // Create a native library symlink only if we have native libraries
12890        // and if the native libraries are 32 bit libraries. We do not provide
12891        // this symlink for 64 bit libraries.
12892        if (pkg.applicationInfo.primaryCpuAbi != null &&
12893                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12894            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12895            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12896                    nativeLibPath, userId) < 0) {
12897                Slog.w(TAG, "Failed linking native library dir");
12898                return false;
12899            }
12900        }
12901
12902        return true;
12903    }
12904
12905
12906    /**
12907     * Revokes granted runtime permissions and clears resettable flags
12908     * which are flags that can be set by a user interaction.
12909     *
12910     * @param permissionsState The permission state to reset.
12911     * @param userId The device user for which to do a reset.
12912     */
12913    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
12914            PermissionsState permissionsState, int userId) {
12915        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
12916                | PackageManager.FLAG_PERMISSION_USER_FIXED
12917                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12918
12919        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags);
12920    }
12921
12922    /**
12923     * Revokes granted runtime permissions and clears all flags.
12924     *
12925     * @param permissionsState The permission state to reset.
12926     * @param userId The device user for which to do a reset.
12927     */
12928    private void revokeRuntimePermissionsAndClearAllFlagsLocked(
12929            PermissionsState permissionsState, int userId) {
12930        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId,
12931                PackageManager.MASK_PERMISSION_FLAGS);
12932    }
12933
12934    /**
12935     * Revokes granted runtime permissions and clears certain flags.
12936     *
12937     * @param permissionsState The permission state to reset.
12938     * @param userId The device user for which to do a reset.
12939     * @param flags The flags that is going to be reset.
12940     */
12941    private void revokeRuntimePermissionsAndClearFlagsLocked(
12942            PermissionsState permissionsState, int userId, int flags) {
12943        boolean needsWrite = false;
12944
12945        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
12946            BasePermission bp = mSettings.mPermissions.get(state.getName());
12947            if (bp != null) {
12948                permissionsState.revokeRuntimePermission(bp, userId);
12949                permissionsState.updatePermissionFlags(bp, userId, flags, 0);
12950                needsWrite = true;
12951            }
12952        }
12953
12954        // Ensure default permissions are never cleared.
12955        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
12956
12957        if (needsWrite) {
12958            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
12959        }
12960    }
12961
12962    /**
12963     * Remove entries from the keystore daemon. Will only remove it if the
12964     * {@code appId} is valid.
12965     */
12966    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12967        if (appId < 0) {
12968            return;
12969        }
12970
12971        final KeyStore keyStore = KeyStore.getInstance();
12972        if (keyStore != null) {
12973            if (userId == UserHandle.USER_ALL) {
12974                for (final int individual : sUserManager.getUserIds()) {
12975                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12976                }
12977            } else {
12978                keyStore.clearUid(UserHandle.getUid(userId, appId));
12979            }
12980        } else {
12981            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12982        }
12983    }
12984
12985    @Override
12986    public void deleteApplicationCacheFiles(final String packageName,
12987            final IPackageDataObserver observer) {
12988        mContext.enforceCallingOrSelfPermission(
12989                android.Manifest.permission.DELETE_CACHE_FILES, null);
12990        // Queue up an async operation since the package deletion may take a little while.
12991        final int userId = UserHandle.getCallingUserId();
12992        mHandler.post(new Runnable() {
12993            public void run() {
12994                mHandler.removeCallbacks(this);
12995                final boolean succeded;
12996                synchronized (mInstallLock) {
12997                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12998                }
12999                clearExternalStorageDataSync(packageName, userId, false);
13000                if (observer != null) {
13001                    try {
13002                        observer.onRemoveCompleted(packageName, succeded);
13003                    } catch (RemoteException e) {
13004                        Log.i(TAG, "Observer no longer exists.");
13005                    }
13006                } //end if observer
13007            } //end run
13008        });
13009    }
13010
13011    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13012        if (packageName == null) {
13013            Slog.w(TAG, "Attempt to delete null packageName.");
13014            return false;
13015        }
13016        PackageParser.Package p;
13017        synchronized (mPackages) {
13018            p = mPackages.get(packageName);
13019        }
13020        if (p == null) {
13021            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13022            return false;
13023        }
13024        final ApplicationInfo applicationInfo = p.applicationInfo;
13025        if (applicationInfo == null) {
13026            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13027            return false;
13028        }
13029        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13030        if (retCode < 0) {
13031            Slog.w(TAG, "Couldn't remove cache files for package: "
13032                       + packageName + " u" + userId);
13033            return false;
13034        }
13035        return true;
13036    }
13037
13038    @Override
13039    public void getPackageSizeInfo(final String packageName, int userHandle,
13040            final IPackageStatsObserver observer) {
13041        mContext.enforceCallingOrSelfPermission(
13042                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13043        if (packageName == null) {
13044            throw new IllegalArgumentException("Attempt to get size of null packageName");
13045        }
13046
13047        PackageStats stats = new PackageStats(packageName, userHandle);
13048
13049        /*
13050         * Queue up an async operation since the package measurement may take a
13051         * little while.
13052         */
13053        Message msg = mHandler.obtainMessage(INIT_COPY);
13054        msg.obj = new MeasureParams(stats, observer);
13055        mHandler.sendMessage(msg);
13056    }
13057
13058    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13059            PackageStats pStats) {
13060        if (packageName == null) {
13061            Slog.w(TAG, "Attempt to get size of null packageName.");
13062            return false;
13063        }
13064        PackageParser.Package p;
13065        boolean dataOnly = false;
13066        String libDirRoot = null;
13067        String asecPath = null;
13068        PackageSetting ps = null;
13069        synchronized (mPackages) {
13070            p = mPackages.get(packageName);
13071            ps = mSettings.mPackages.get(packageName);
13072            if(p == null) {
13073                dataOnly = true;
13074                if((ps == null) || (ps.pkg == null)) {
13075                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13076                    return false;
13077                }
13078                p = ps.pkg;
13079            }
13080            if (ps != null) {
13081                libDirRoot = ps.legacyNativeLibraryPathString;
13082            }
13083            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13084                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13085                if (secureContainerId != null) {
13086                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13087                }
13088            }
13089        }
13090        String publicSrcDir = null;
13091        if(!dataOnly) {
13092            final ApplicationInfo applicationInfo = p.applicationInfo;
13093            if (applicationInfo == null) {
13094                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13095                return false;
13096            }
13097            if (p.isForwardLocked()) {
13098                publicSrcDir = applicationInfo.getBaseResourcePath();
13099            }
13100        }
13101        // TODO: extend to measure size of split APKs
13102        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13103        // not just the first level.
13104        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13105        // just the primary.
13106        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13107        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13108                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13109        if (res < 0) {
13110            return false;
13111        }
13112
13113        // Fix-up for forward-locked applications in ASEC containers.
13114        if (!isExternal(p)) {
13115            pStats.codeSize += pStats.externalCodeSize;
13116            pStats.externalCodeSize = 0L;
13117        }
13118
13119        return true;
13120    }
13121
13122
13123    @Override
13124    public void addPackageToPreferred(String packageName) {
13125        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13126    }
13127
13128    @Override
13129    public void removePackageFromPreferred(String packageName) {
13130        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13131    }
13132
13133    @Override
13134    public List<PackageInfo> getPreferredPackages(int flags) {
13135        return new ArrayList<PackageInfo>();
13136    }
13137
13138    private int getUidTargetSdkVersionLockedLPr(int uid) {
13139        Object obj = mSettings.getUserIdLPr(uid);
13140        if (obj instanceof SharedUserSetting) {
13141            final SharedUserSetting sus = (SharedUserSetting) obj;
13142            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13143            final Iterator<PackageSetting> it = sus.packages.iterator();
13144            while (it.hasNext()) {
13145                final PackageSetting ps = it.next();
13146                if (ps.pkg != null) {
13147                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13148                    if (v < vers) vers = v;
13149                }
13150            }
13151            return vers;
13152        } else if (obj instanceof PackageSetting) {
13153            final PackageSetting ps = (PackageSetting) obj;
13154            if (ps.pkg != null) {
13155                return ps.pkg.applicationInfo.targetSdkVersion;
13156            }
13157        }
13158        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13159    }
13160
13161    @Override
13162    public void addPreferredActivity(IntentFilter filter, int match,
13163            ComponentName[] set, ComponentName activity, int userId) {
13164        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13165                "Adding preferred");
13166    }
13167
13168    private void addPreferredActivityInternal(IntentFilter filter, int match,
13169            ComponentName[] set, ComponentName activity, boolean always, int userId,
13170            String opname) {
13171        // writer
13172        int callingUid = Binder.getCallingUid();
13173        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13174        if (filter.countActions() == 0) {
13175            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13176            return;
13177        }
13178        synchronized (mPackages) {
13179            if (mContext.checkCallingOrSelfPermission(
13180                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13181                    != PackageManager.PERMISSION_GRANTED) {
13182                if (getUidTargetSdkVersionLockedLPr(callingUid)
13183                        < Build.VERSION_CODES.FROYO) {
13184                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13185                            + callingUid);
13186                    return;
13187                }
13188                mContext.enforceCallingOrSelfPermission(
13189                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13190            }
13191
13192            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13193            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13194                    + userId + ":");
13195            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13196            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13197            scheduleWritePackageRestrictionsLocked(userId);
13198        }
13199    }
13200
13201    @Override
13202    public void replacePreferredActivity(IntentFilter filter, int match,
13203            ComponentName[] set, ComponentName activity, int userId) {
13204        if (filter.countActions() != 1) {
13205            throw new IllegalArgumentException(
13206                    "replacePreferredActivity expects filter to have only 1 action.");
13207        }
13208        if (filter.countDataAuthorities() != 0
13209                || filter.countDataPaths() != 0
13210                || filter.countDataSchemes() > 1
13211                || filter.countDataTypes() != 0) {
13212            throw new IllegalArgumentException(
13213                    "replacePreferredActivity expects filter to have no data authorities, " +
13214                    "paths, or types; and at most one scheme.");
13215        }
13216
13217        final int callingUid = Binder.getCallingUid();
13218        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13219        synchronized (mPackages) {
13220            if (mContext.checkCallingOrSelfPermission(
13221                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13222                    != PackageManager.PERMISSION_GRANTED) {
13223                if (getUidTargetSdkVersionLockedLPr(callingUid)
13224                        < Build.VERSION_CODES.FROYO) {
13225                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13226                            + Binder.getCallingUid());
13227                    return;
13228                }
13229                mContext.enforceCallingOrSelfPermission(
13230                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13231            }
13232
13233            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13234            if (pir != null) {
13235                // Get all of the existing entries that exactly match this filter.
13236                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13237                if (existing != null && existing.size() == 1) {
13238                    PreferredActivity cur = existing.get(0);
13239                    if (DEBUG_PREFERRED) {
13240                        Slog.i(TAG, "Checking replace of preferred:");
13241                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13242                        if (!cur.mPref.mAlways) {
13243                            Slog.i(TAG, "  -- CUR; not mAlways!");
13244                        } else {
13245                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13246                            Slog.i(TAG, "  -- CUR: mSet="
13247                                    + Arrays.toString(cur.mPref.mSetComponents));
13248                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13249                            Slog.i(TAG, "  -- NEW: mMatch="
13250                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13251                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13252                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13253                        }
13254                    }
13255                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13256                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13257                            && cur.mPref.sameSet(set)) {
13258                        // Setting the preferred activity to what it happens to be already
13259                        if (DEBUG_PREFERRED) {
13260                            Slog.i(TAG, "Replacing with same preferred activity "
13261                                    + cur.mPref.mShortComponent + " for user "
13262                                    + userId + ":");
13263                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13264                        }
13265                        return;
13266                    }
13267                }
13268
13269                if (existing != null) {
13270                    if (DEBUG_PREFERRED) {
13271                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13272                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13273                    }
13274                    for (int i = 0; i < existing.size(); i++) {
13275                        PreferredActivity pa = existing.get(i);
13276                        if (DEBUG_PREFERRED) {
13277                            Slog.i(TAG, "Removing existing preferred activity "
13278                                    + pa.mPref.mComponent + ":");
13279                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13280                        }
13281                        pir.removeFilter(pa);
13282                    }
13283                }
13284            }
13285            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13286                    "Replacing preferred");
13287        }
13288    }
13289
13290    @Override
13291    public void clearPackagePreferredActivities(String packageName) {
13292        final int uid = Binder.getCallingUid();
13293        // writer
13294        synchronized (mPackages) {
13295            PackageParser.Package pkg = mPackages.get(packageName);
13296            if (pkg == null || pkg.applicationInfo.uid != uid) {
13297                if (mContext.checkCallingOrSelfPermission(
13298                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13299                        != PackageManager.PERMISSION_GRANTED) {
13300                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13301                            < Build.VERSION_CODES.FROYO) {
13302                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13303                                + Binder.getCallingUid());
13304                        return;
13305                    }
13306                    mContext.enforceCallingOrSelfPermission(
13307                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13308                }
13309            }
13310
13311            int user = UserHandle.getCallingUserId();
13312            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13313                scheduleWritePackageRestrictionsLocked(user);
13314            }
13315        }
13316    }
13317
13318    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13319    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13320        ArrayList<PreferredActivity> removed = null;
13321        boolean changed = false;
13322        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13323            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13324            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13325            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13326                continue;
13327            }
13328            Iterator<PreferredActivity> it = pir.filterIterator();
13329            while (it.hasNext()) {
13330                PreferredActivity pa = it.next();
13331                // Mark entry for removal only if it matches the package name
13332                // and the entry is of type "always".
13333                if (packageName == null ||
13334                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13335                                && pa.mPref.mAlways)) {
13336                    if (removed == null) {
13337                        removed = new ArrayList<PreferredActivity>();
13338                    }
13339                    removed.add(pa);
13340                }
13341            }
13342            if (removed != null) {
13343                for (int j=0; j<removed.size(); j++) {
13344                    PreferredActivity pa = removed.get(j);
13345                    pir.removeFilter(pa);
13346                }
13347                changed = true;
13348            }
13349        }
13350        return changed;
13351    }
13352
13353    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13354    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13355        if (userId == UserHandle.USER_ALL) {
13356            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13357                    sUserManager.getUserIds())) {
13358                for (int oneUserId : sUserManager.getUserIds()) {
13359                    scheduleWritePackageRestrictionsLocked(oneUserId);
13360                }
13361            }
13362        } else {
13363            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13364                scheduleWritePackageRestrictionsLocked(userId);
13365            }
13366        }
13367    }
13368
13369
13370    void clearDefaultBrowserIfNeeded(String packageName) {
13371        for (int oneUserId : sUserManager.getUserIds()) {
13372            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13373            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13374            if (packageName.equals(defaultBrowserPackageName)) {
13375                setDefaultBrowserPackageName(null, oneUserId);
13376            }
13377        }
13378    }
13379
13380    @Override
13381    public void resetPreferredActivities(int userId) {
13382        /* TODO: Actually use userId. Why is it being passed in? */
13383        mContext.enforceCallingOrSelfPermission(
13384                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13385        // writer
13386        synchronized (mPackages) {
13387            int user = UserHandle.getCallingUserId();
13388            clearPackagePreferredActivitiesLPw(null, user);
13389            mSettings.readDefaultPreferredAppsLPw(this, user);
13390            scheduleWritePackageRestrictionsLocked(user);
13391        }
13392    }
13393
13394    @Override
13395    public int getPreferredActivities(List<IntentFilter> outFilters,
13396            List<ComponentName> outActivities, String packageName) {
13397
13398        int num = 0;
13399        final int userId = UserHandle.getCallingUserId();
13400        // reader
13401        synchronized (mPackages) {
13402            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13403            if (pir != null) {
13404                final Iterator<PreferredActivity> it = pir.filterIterator();
13405                while (it.hasNext()) {
13406                    final PreferredActivity pa = it.next();
13407                    if (packageName == null
13408                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13409                                    && pa.mPref.mAlways)) {
13410                        if (outFilters != null) {
13411                            outFilters.add(new IntentFilter(pa));
13412                        }
13413                        if (outActivities != null) {
13414                            outActivities.add(pa.mPref.mComponent);
13415                        }
13416                    }
13417                }
13418            }
13419        }
13420
13421        return num;
13422    }
13423
13424    @Override
13425    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13426            int userId) {
13427        int callingUid = Binder.getCallingUid();
13428        if (callingUid != Process.SYSTEM_UID) {
13429            throw new SecurityException(
13430                    "addPersistentPreferredActivity can only be run by the system");
13431        }
13432        if (filter.countActions() == 0) {
13433            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13434            return;
13435        }
13436        synchronized (mPackages) {
13437            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13438                    " :");
13439            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13440            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13441                    new PersistentPreferredActivity(filter, activity));
13442            scheduleWritePackageRestrictionsLocked(userId);
13443        }
13444    }
13445
13446    @Override
13447    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13448        int callingUid = Binder.getCallingUid();
13449        if (callingUid != Process.SYSTEM_UID) {
13450            throw new SecurityException(
13451                    "clearPackagePersistentPreferredActivities can only be run by the system");
13452        }
13453        ArrayList<PersistentPreferredActivity> removed = null;
13454        boolean changed = false;
13455        synchronized (mPackages) {
13456            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13457                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13458                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13459                        .valueAt(i);
13460                if (userId != thisUserId) {
13461                    continue;
13462                }
13463                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13464                while (it.hasNext()) {
13465                    PersistentPreferredActivity ppa = it.next();
13466                    // Mark entry for removal only if it matches the package name.
13467                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13468                        if (removed == null) {
13469                            removed = new ArrayList<PersistentPreferredActivity>();
13470                        }
13471                        removed.add(ppa);
13472                    }
13473                }
13474                if (removed != null) {
13475                    for (int j=0; j<removed.size(); j++) {
13476                        PersistentPreferredActivity ppa = removed.get(j);
13477                        ppir.removeFilter(ppa);
13478                    }
13479                    changed = true;
13480                }
13481            }
13482
13483            if (changed) {
13484                scheduleWritePackageRestrictionsLocked(userId);
13485            }
13486        }
13487    }
13488
13489    /**
13490     * Common machinery for picking apart a restored XML blob and passing
13491     * it to a caller-supplied functor to be applied to the running system.
13492     */
13493    private void restoreFromXml(XmlPullParser parser, int userId,
13494            String expectedStartTag, BlobXmlRestorer functor)
13495            throws IOException, XmlPullParserException {
13496        int type;
13497        while ((type = parser.next()) != XmlPullParser.START_TAG
13498                && type != XmlPullParser.END_DOCUMENT) {
13499        }
13500        if (type != XmlPullParser.START_TAG) {
13501            // oops didn't find a start tag?!
13502            if (DEBUG_BACKUP) {
13503                Slog.e(TAG, "Didn't find start tag during restore");
13504            }
13505            return;
13506        }
13507
13508        // this is supposed to be TAG_PREFERRED_BACKUP
13509        if (!expectedStartTag.equals(parser.getName())) {
13510            if (DEBUG_BACKUP) {
13511                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13512            }
13513            return;
13514        }
13515
13516        // skip interfering stuff, then we're aligned with the backing implementation
13517        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13518        functor.apply(parser, userId);
13519    }
13520
13521    private interface BlobXmlRestorer {
13522        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13523    }
13524
13525    /**
13526     * Non-Binder method, support for the backup/restore mechanism: write the
13527     * full set of preferred activities in its canonical XML format.  Returns the
13528     * XML output as a byte array, or null if there is none.
13529     */
13530    @Override
13531    public byte[] getPreferredActivityBackup(int userId) {
13532        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13533            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13534        }
13535
13536        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13537        try {
13538            final XmlSerializer serializer = new FastXmlSerializer();
13539            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13540            serializer.startDocument(null, true);
13541            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13542
13543            synchronized (mPackages) {
13544                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13545            }
13546
13547            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13548            serializer.endDocument();
13549            serializer.flush();
13550        } catch (Exception e) {
13551            if (DEBUG_BACKUP) {
13552                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13553            }
13554            return null;
13555        }
13556
13557        return dataStream.toByteArray();
13558    }
13559
13560    @Override
13561    public void restorePreferredActivities(byte[] backup, int userId) {
13562        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13563            throw new SecurityException("Only the system may call restorePreferredActivities()");
13564        }
13565
13566        try {
13567            final XmlPullParser parser = Xml.newPullParser();
13568            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13569            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13570                    new BlobXmlRestorer() {
13571                        @Override
13572                        public void apply(XmlPullParser parser, int userId)
13573                                throws XmlPullParserException, IOException {
13574                            synchronized (mPackages) {
13575                                mSettings.readPreferredActivitiesLPw(parser, userId);
13576                            }
13577                        }
13578                    } );
13579        } catch (Exception e) {
13580            if (DEBUG_BACKUP) {
13581                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13582            }
13583        }
13584    }
13585
13586    /**
13587     * Non-Binder method, support for the backup/restore mechanism: write the
13588     * default browser (etc) settings in its canonical XML format.  Returns the default
13589     * browser XML representation as a byte array, or null if there is none.
13590     */
13591    @Override
13592    public byte[] getDefaultAppsBackup(int userId) {
13593        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13594            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13595        }
13596
13597        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13598        try {
13599            final XmlSerializer serializer = new FastXmlSerializer();
13600            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13601            serializer.startDocument(null, true);
13602            serializer.startTag(null, TAG_DEFAULT_APPS);
13603
13604            synchronized (mPackages) {
13605                mSettings.writeDefaultAppsLPr(serializer, userId);
13606            }
13607
13608            serializer.endTag(null, TAG_DEFAULT_APPS);
13609            serializer.endDocument();
13610            serializer.flush();
13611        } catch (Exception e) {
13612            if (DEBUG_BACKUP) {
13613                Slog.e(TAG, "Unable to write default apps for backup", e);
13614            }
13615            return null;
13616        }
13617
13618        return dataStream.toByteArray();
13619    }
13620
13621    @Override
13622    public void restoreDefaultApps(byte[] backup, int userId) {
13623        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13624            throw new SecurityException("Only the system may call restoreDefaultApps()");
13625        }
13626
13627        try {
13628            final XmlPullParser parser = Xml.newPullParser();
13629            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13630            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13631                    new BlobXmlRestorer() {
13632                        @Override
13633                        public void apply(XmlPullParser parser, int userId)
13634                                throws XmlPullParserException, IOException {
13635                            synchronized (mPackages) {
13636                                mSettings.readDefaultAppsLPw(parser, userId);
13637                            }
13638                        }
13639                    } );
13640        } catch (Exception e) {
13641            if (DEBUG_BACKUP) {
13642                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13643            }
13644        }
13645    }
13646
13647    @Override
13648    public byte[] getIntentFilterVerificationBackup(int userId) {
13649        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13650            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
13651        }
13652
13653        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13654        try {
13655            final XmlSerializer serializer = new FastXmlSerializer();
13656            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13657            serializer.startDocument(null, true);
13658            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
13659
13660            synchronized (mPackages) {
13661                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
13662            }
13663
13664            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
13665            serializer.endDocument();
13666            serializer.flush();
13667        } catch (Exception e) {
13668            if (DEBUG_BACKUP) {
13669                Slog.e(TAG, "Unable to write default apps for backup", e);
13670            }
13671            return null;
13672        }
13673
13674        return dataStream.toByteArray();
13675    }
13676
13677    @Override
13678    public void restoreIntentFilterVerification(byte[] backup, int userId) {
13679        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13680            throw new SecurityException("Only the system may call restorePreferredActivities()");
13681        }
13682
13683        try {
13684            final XmlPullParser parser = Xml.newPullParser();
13685            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13686            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
13687                    new BlobXmlRestorer() {
13688                        @Override
13689                        public void apply(XmlPullParser parser, int userId)
13690                                throws XmlPullParserException, IOException {
13691                            synchronized (mPackages) {
13692                                mSettings.readAllDomainVerificationsLPr(parser, userId);
13693                                mSettings.writeLPr();
13694                            }
13695                        }
13696                    } );
13697        } catch (Exception e) {
13698            if (DEBUG_BACKUP) {
13699                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13700            }
13701        }
13702    }
13703
13704    @Override
13705    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13706            int sourceUserId, int targetUserId, int flags) {
13707        mContext.enforceCallingOrSelfPermission(
13708                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13709        int callingUid = Binder.getCallingUid();
13710        enforceOwnerRights(ownerPackage, callingUid);
13711        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13712        if (intentFilter.countActions() == 0) {
13713            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13714            return;
13715        }
13716        synchronized (mPackages) {
13717            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13718                    ownerPackage, targetUserId, flags);
13719            CrossProfileIntentResolver resolver =
13720                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13721            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13722            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13723            if (existing != null) {
13724                int size = existing.size();
13725                for (int i = 0; i < size; i++) {
13726                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13727                        return;
13728                    }
13729                }
13730            }
13731            resolver.addFilter(newFilter);
13732            scheduleWritePackageRestrictionsLocked(sourceUserId);
13733        }
13734    }
13735
13736    @Override
13737    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13738        mContext.enforceCallingOrSelfPermission(
13739                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13740        int callingUid = Binder.getCallingUid();
13741        enforceOwnerRights(ownerPackage, callingUid);
13742        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13743        synchronized (mPackages) {
13744            CrossProfileIntentResolver resolver =
13745                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13746            ArraySet<CrossProfileIntentFilter> set =
13747                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13748            for (CrossProfileIntentFilter filter : set) {
13749                if (filter.getOwnerPackage().equals(ownerPackage)) {
13750                    resolver.removeFilter(filter);
13751                }
13752            }
13753            scheduleWritePackageRestrictionsLocked(sourceUserId);
13754        }
13755    }
13756
13757    // Enforcing that callingUid is owning pkg on userId
13758    private void enforceOwnerRights(String pkg, int callingUid) {
13759        // The system owns everything.
13760        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13761            return;
13762        }
13763        int callingUserId = UserHandle.getUserId(callingUid);
13764        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13765        if (pi == null) {
13766            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13767                    + callingUserId);
13768        }
13769        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13770            throw new SecurityException("Calling uid " + callingUid
13771                    + " does not own package " + pkg);
13772        }
13773    }
13774
13775    @Override
13776    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13777        Intent intent = new Intent(Intent.ACTION_MAIN);
13778        intent.addCategory(Intent.CATEGORY_HOME);
13779
13780        final int callingUserId = UserHandle.getCallingUserId();
13781        List<ResolveInfo> list = queryIntentActivities(intent, null,
13782                PackageManager.GET_META_DATA, callingUserId);
13783        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13784                true, false, false, callingUserId);
13785
13786        allHomeCandidates.clear();
13787        if (list != null) {
13788            for (ResolveInfo ri : list) {
13789                allHomeCandidates.add(ri);
13790            }
13791        }
13792        return (preferred == null || preferred.activityInfo == null)
13793                ? null
13794                : new ComponentName(preferred.activityInfo.packageName,
13795                        preferred.activityInfo.name);
13796    }
13797
13798    @Override
13799    public void setApplicationEnabledSetting(String appPackageName,
13800            int newState, int flags, int userId, String callingPackage) {
13801        if (!sUserManager.exists(userId)) return;
13802        if (callingPackage == null) {
13803            callingPackage = Integer.toString(Binder.getCallingUid());
13804        }
13805        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13806    }
13807
13808    @Override
13809    public void setComponentEnabledSetting(ComponentName componentName,
13810            int newState, int flags, int userId) {
13811        if (!sUserManager.exists(userId)) return;
13812        setEnabledSetting(componentName.getPackageName(),
13813                componentName.getClassName(), newState, flags, userId, null);
13814    }
13815
13816    private void setEnabledSetting(final String packageName, String className, int newState,
13817            final int flags, int userId, String callingPackage) {
13818        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13819              || newState == COMPONENT_ENABLED_STATE_ENABLED
13820              || newState == COMPONENT_ENABLED_STATE_DISABLED
13821              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13822              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13823            throw new IllegalArgumentException("Invalid new component state: "
13824                    + newState);
13825        }
13826        PackageSetting pkgSetting;
13827        final int uid = Binder.getCallingUid();
13828        final int permission = mContext.checkCallingOrSelfPermission(
13829                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13830        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13831        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13832        boolean sendNow = false;
13833        boolean isApp = (className == null);
13834        String componentName = isApp ? packageName : className;
13835        int packageUid = -1;
13836        ArrayList<String> components;
13837
13838        // writer
13839        synchronized (mPackages) {
13840            pkgSetting = mSettings.mPackages.get(packageName);
13841            if (pkgSetting == null) {
13842                if (className == null) {
13843                    throw new IllegalArgumentException(
13844                            "Unknown package: " + packageName);
13845                }
13846                throw new IllegalArgumentException(
13847                        "Unknown component: " + packageName
13848                        + "/" + className);
13849            }
13850            // Allow root and verify that userId is not being specified by a different user
13851            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13852                throw new SecurityException(
13853                        "Permission Denial: attempt to change component state from pid="
13854                        + Binder.getCallingPid()
13855                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13856            }
13857            if (className == null) {
13858                // We're dealing with an application/package level state change
13859                if (pkgSetting.getEnabled(userId) == newState) {
13860                    // Nothing to do
13861                    return;
13862                }
13863                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13864                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13865                    // Don't care about who enables an app.
13866                    callingPackage = null;
13867                }
13868                pkgSetting.setEnabled(newState, userId, callingPackage);
13869                // pkgSetting.pkg.mSetEnabled = newState;
13870            } else {
13871                // We're dealing with a component level state change
13872                // First, verify that this is a valid class name.
13873                PackageParser.Package pkg = pkgSetting.pkg;
13874                if (pkg == null || !pkg.hasComponentClassName(className)) {
13875                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13876                        throw new IllegalArgumentException("Component class " + className
13877                                + " does not exist in " + packageName);
13878                    } else {
13879                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13880                                + className + " does not exist in " + packageName);
13881                    }
13882                }
13883                switch (newState) {
13884                case COMPONENT_ENABLED_STATE_ENABLED:
13885                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13886                        return;
13887                    }
13888                    break;
13889                case COMPONENT_ENABLED_STATE_DISABLED:
13890                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13891                        return;
13892                    }
13893                    break;
13894                case COMPONENT_ENABLED_STATE_DEFAULT:
13895                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13896                        return;
13897                    }
13898                    break;
13899                default:
13900                    Slog.e(TAG, "Invalid new component state: " + newState);
13901                    return;
13902                }
13903            }
13904            scheduleWritePackageRestrictionsLocked(userId);
13905            components = mPendingBroadcasts.get(userId, packageName);
13906            final boolean newPackage = components == null;
13907            if (newPackage) {
13908                components = new ArrayList<String>();
13909            }
13910            if (!components.contains(componentName)) {
13911                components.add(componentName);
13912            }
13913            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
13914                sendNow = true;
13915                // Purge entry from pending broadcast list if another one exists already
13916                // since we are sending one right away.
13917                mPendingBroadcasts.remove(userId, packageName);
13918            } else {
13919                if (newPackage) {
13920                    mPendingBroadcasts.put(userId, packageName, components);
13921                }
13922                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
13923                    // Schedule a message
13924                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
13925                }
13926            }
13927        }
13928
13929        long callingId = Binder.clearCallingIdentity();
13930        try {
13931            if (sendNow) {
13932                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13933                sendPackageChangedBroadcast(packageName,
13934                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13935            }
13936        } finally {
13937            Binder.restoreCallingIdentity(callingId);
13938        }
13939    }
13940
13941    private void sendPackageChangedBroadcast(String packageName,
13942            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13943        if (DEBUG_INSTALL)
13944            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13945                    + componentNames);
13946        Bundle extras = new Bundle(4);
13947        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13948        String nameList[] = new String[componentNames.size()];
13949        componentNames.toArray(nameList);
13950        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13951        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13952        extras.putInt(Intent.EXTRA_UID, packageUid);
13953        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13954                new int[] {UserHandle.getUserId(packageUid)});
13955    }
13956
13957    @Override
13958    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13959        if (!sUserManager.exists(userId)) return;
13960        final int uid = Binder.getCallingUid();
13961        final int permission = mContext.checkCallingOrSelfPermission(
13962                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13963        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13964        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13965        // writer
13966        synchronized (mPackages) {
13967            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
13968                    allowedByPermission, uid, userId)) {
13969                scheduleWritePackageRestrictionsLocked(userId);
13970            }
13971        }
13972    }
13973
13974    @Override
13975    public String getInstallerPackageName(String packageName) {
13976        // reader
13977        synchronized (mPackages) {
13978            return mSettings.getInstallerPackageNameLPr(packageName);
13979        }
13980    }
13981
13982    @Override
13983    public int getApplicationEnabledSetting(String packageName, int userId) {
13984        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13985        int uid = Binder.getCallingUid();
13986        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13987        // reader
13988        synchronized (mPackages) {
13989            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13990        }
13991    }
13992
13993    @Override
13994    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13995        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13996        int uid = Binder.getCallingUid();
13997        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13998        // reader
13999        synchronized (mPackages) {
14000            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14001        }
14002    }
14003
14004    @Override
14005    public void enterSafeMode() {
14006        enforceSystemOrRoot("Only the system can request entering safe mode");
14007
14008        if (!mSystemReady) {
14009            mSafeMode = true;
14010        }
14011    }
14012
14013    @Override
14014    public void systemReady() {
14015        mSystemReady = true;
14016
14017        // Read the compatibilty setting when the system is ready.
14018        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14019                mContext.getContentResolver(),
14020                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14021        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14022        if (DEBUG_SETTINGS) {
14023            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14024        }
14025
14026        synchronized (mPackages) {
14027            // Verify that all of the preferred activity components actually
14028            // exist.  It is possible for applications to be updated and at
14029            // that point remove a previously declared activity component that
14030            // had been set as a preferred activity.  We try to clean this up
14031            // the next time we encounter that preferred activity, but it is
14032            // possible for the user flow to never be able to return to that
14033            // situation so here we do a sanity check to make sure we haven't
14034            // left any junk around.
14035            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14036            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14037                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14038                removed.clear();
14039                for (PreferredActivity pa : pir.filterSet()) {
14040                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14041                        removed.add(pa);
14042                    }
14043                }
14044                if (removed.size() > 0) {
14045                    for (int r=0; r<removed.size(); r++) {
14046                        PreferredActivity pa = removed.get(r);
14047                        Slog.w(TAG, "Removing dangling preferred activity: "
14048                                + pa.mPref.mComponent);
14049                        pir.removeFilter(pa);
14050                    }
14051                    mSettings.writePackageRestrictionsLPr(
14052                            mSettings.mPreferredActivities.keyAt(i));
14053                }
14054            }
14055        }
14056        sUserManager.systemReady();
14057
14058        // If we upgraded grant all default permissions before kicking off.
14059        if (isFirstBoot() || (CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE && mIsUpgrade)) {
14060            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
14061            for (int userId : UserManagerService.getInstance().getUserIds()) {
14062                mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14063            }
14064        }
14065
14066        // Kick off any messages waiting for system ready
14067        if (mPostSystemReadyMessages != null) {
14068            for (Message msg : mPostSystemReadyMessages) {
14069                msg.sendToTarget();
14070            }
14071            mPostSystemReadyMessages = null;
14072        }
14073
14074        // Watch for external volumes that come and go over time
14075        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14076        storage.registerListener(mStorageListener);
14077
14078        mInstallerService.systemReady();
14079        mPackageDexOptimizer.systemReady();
14080    }
14081
14082    @Override
14083    public boolean isSafeMode() {
14084        return mSafeMode;
14085    }
14086
14087    @Override
14088    public boolean hasSystemUidErrors() {
14089        return mHasSystemUidErrors;
14090    }
14091
14092    static String arrayToString(int[] array) {
14093        StringBuffer buf = new StringBuffer(128);
14094        buf.append('[');
14095        if (array != null) {
14096            for (int i=0; i<array.length; i++) {
14097                if (i > 0) buf.append(", ");
14098                buf.append(array[i]);
14099            }
14100        }
14101        buf.append(']');
14102        return buf.toString();
14103    }
14104
14105    static class DumpState {
14106        public static final int DUMP_LIBS = 1 << 0;
14107        public static final int DUMP_FEATURES = 1 << 1;
14108        public static final int DUMP_RESOLVERS = 1 << 2;
14109        public static final int DUMP_PERMISSIONS = 1 << 3;
14110        public static final int DUMP_PACKAGES = 1 << 4;
14111        public static final int DUMP_SHARED_USERS = 1 << 5;
14112        public static final int DUMP_MESSAGES = 1 << 6;
14113        public static final int DUMP_PROVIDERS = 1 << 7;
14114        public static final int DUMP_VERIFIERS = 1 << 8;
14115        public static final int DUMP_PREFERRED = 1 << 9;
14116        public static final int DUMP_PREFERRED_XML = 1 << 10;
14117        public static final int DUMP_KEYSETS = 1 << 11;
14118        public static final int DUMP_VERSION = 1 << 12;
14119        public static final int DUMP_INSTALLS = 1 << 13;
14120        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14121        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14122
14123        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14124
14125        private int mTypes;
14126
14127        private int mOptions;
14128
14129        private boolean mTitlePrinted;
14130
14131        private SharedUserSetting mSharedUser;
14132
14133        public boolean isDumping(int type) {
14134            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14135                return true;
14136            }
14137
14138            return (mTypes & type) != 0;
14139        }
14140
14141        public void setDump(int type) {
14142            mTypes |= type;
14143        }
14144
14145        public boolean isOptionEnabled(int option) {
14146            return (mOptions & option) != 0;
14147        }
14148
14149        public void setOptionEnabled(int option) {
14150            mOptions |= option;
14151        }
14152
14153        public boolean onTitlePrinted() {
14154            final boolean printed = mTitlePrinted;
14155            mTitlePrinted = true;
14156            return printed;
14157        }
14158
14159        public boolean getTitlePrinted() {
14160            return mTitlePrinted;
14161        }
14162
14163        public void setTitlePrinted(boolean enabled) {
14164            mTitlePrinted = enabled;
14165        }
14166
14167        public SharedUserSetting getSharedUser() {
14168            return mSharedUser;
14169        }
14170
14171        public void setSharedUser(SharedUserSetting user) {
14172            mSharedUser = user;
14173        }
14174    }
14175
14176    @Override
14177    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14178        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14179                != PackageManager.PERMISSION_GRANTED) {
14180            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14181                    + Binder.getCallingPid()
14182                    + ", uid=" + Binder.getCallingUid()
14183                    + " without permission "
14184                    + android.Manifest.permission.DUMP);
14185            return;
14186        }
14187
14188        DumpState dumpState = new DumpState();
14189        boolean fullPreferred = false;
14190        boolean checkin = false;
14191
14192        String packageName = null;
14193
14194        int opti = 0;
14195        while (opti < args.length) {
14196            String opt = args[opti];
14197            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14198                break;
14199            }
14200            opti++;
14201
14202            if ("-a".equals(opt)) {
14203                // Right now we only know how to print all.
14204            } else if ("-h".equals(opt)) {
14205                pw.println("Package manager dump options:");
14206                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14207                pw.println("    --checkin: dump for a checkin");
14208                pw.println("    -f: print details of intent filters");
14209                pw.println("    -h: print this help");
14210                pw.println("  cmd may be one of:");
14211                pw.println("    l[ibraries]: list known shared libraries");
14212                pw.println("    f[ibraries]: list device features");
14213                pw.println("    k[eysets]: print known keysets");
14214                pw.println("    r[esolvers]: dump intent resolvers");
14215                pw.println("    perm[issions]: dump permissions");
14216                pw.println("    pref[erred]: print preferred package settings");
14217                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14218                pw.println("    prov[iders]: dump content providers");
14219                pw.println("    p[ackages]: dump installed packages");
14220                pw.println("    s[hared-users]: dump shared user IDs");
14221                pw.println("    m[essages]: print collected runtime messages");
14222                pw.println("    v[erifiers]: print package verifier info");
14223                pw.println("    version: print database version info");
14224                pw.println("    write: write current settings now");
14225                pw.println("    <package.name>: info about given package");
14226                pw.println("    installs: details about install sessions");
14227                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14228                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14229                return;
14230            } else if ("--checkin".equals(opt)) {
14231                checkin = true;
14232            } else if ("-f".equals(opt)) {
14233                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14234            } else {
14235                pw.println("Unknown argument: " + opt + "; use -h for help");
14236            }
14237        }
14238
14239        // Is the caller requesting to dump a particular piece of data?
14240        if (opti < args.length) {
14241            String cmd = args[opti];
14242            opti++;
14243            // Is this a package name?
14244            if ("android".equals(cmd) || cmd.contains(".")) {
14245                packageName = cmd;
14246                // When dumping a single package, we always dump all of its
14247                // filter information since the amount of data will be reasonable.
14248                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14249            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14250                dumpState.setDump(DumpState.DUMP_LIBS);
14251            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14252                dumpState.setDump(DumpState.DUMP_FEATURES);
14253            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14254                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14255            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14256                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14257            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14258                dumpState.setDump(DumpState.DUMP_PREFERRED);
14259            } else if ("preferred-xml".equals(cmd)) {
14260                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14261                if (opti < args.length && "--full".equals(args[opti])) {
14262                    fullPreferred = true;
14263                    opti++;
14264                }
14265            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14266                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14267            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14268                dumpState.setDump(DumpState.DUMP_PACKAGES);
14269            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14270                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14271            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14272                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14273            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14274                dumpState.setDump(DumpState.DUMP_MESSAGES);
14275            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14276                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14277            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14278                    || "intent-filter-verifiers".equals(cmd)) {
14279                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14280            } else if ("version".equals(cmd)) {
14281                dumpState.setDump(DumpState.DUMP_VERSION);
14282            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14283                dumpState.setDump(DumpState.DUMP_KEYSETS);
14284            } else if ("installs".equals(cmd)) {
14285                dumpState.setDump(DumpState.DUMP_INSTALLS);
14286            } else if ("write".equals(cmd)) {
14287                synchronized (mPackages) {
14288                    mSettings.writeLPr();
14289                    pw.println("Settings written.");
14290                    return;
14291                }
14292            }
14293        }
14294
14295        if (checkin) {
14296            pw.println("vers,1");
14297        }
14298
14299        // reader
14300        synchronized (mPackages) {
14301            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14302                if (!checkin) {
14303                    if (dumpState.onTitlePrinted())
14304                        pw.println();
14305                    pw.println("Database versions:");
14306                    pw.print("  SDK Version:");
14307                    pw.print(" internal=");
14308                    pw.print(mSettings.mInternalSdkPlatform);
14309                    pw.print(" external=");
14310                    pw.println(mSettings.mExternalSdkPlatform);
14311                    pw.print("  DB Version:");
14312                    pw.print(" internal=");
14313                    pw.print(mSettings.mInternalDatabaseVersion);
14314                    pw.print(" external=");
14315                    pw.println(mSettings.mExternalDatabaseVersion);
14316                }
14317            }
14318
14319            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14320                if (!checkin) {
14321                    if (dumpState.onTitlePrinted())
14322                        pw.println();
14323                    pw.println("Verifiers:");
14324                    pw.print("  Required: ");
14325                    pw.print(mRequiredVerifierPackage);
14326                    pw.print(" (uid=");
14327                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14328                    pw.println(")");
14329                } else if (mRequiredVerifierPackage != null) {
14330                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14331                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14332                }
14333            }
14334
14335            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14336                    packageName == null) {
14337                if (mIntentFilterVerifierComponent != null) {
14338                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14339                    if (!checkin) {
14340                        if (dumpState.onTitlePrinted())
14341                            pw.println();
14342                        pw.println("Intent Filter Verifier:");
14343                        pw.print("  Using: ");
14344                        pw.print(verifierPackageName);
14345                        pw.print(" (uid=");
14346                        pw.print(getPackageUid(verifierPackageName, 0));
14347                        pw.println(")");
14348                    } else if (verifierPackageName != null) {
14349                        pw.print("ifv,"); pw.print(verifierPackageName);
14350                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14351                    }
14352                } else {
14353                    pw.println();
14354                    pw.println("No Intent Filter Verifier available!");
14355                }
14356            }
14357
14358            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14359                boolean printedHeader = false;
14360                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14361                while (it.hasNext()) {
14362                    String name = it.next();
14363                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14364                    if (!checkin) {
14365                        if (!printedHeader) {
14366                            if (dumpState.onTitlePrinted())
14367                                pw.println();
14368                            pw.println("Libraries:");
14369                            printedHeader = true;
14370                        }
14371                        pw.print("  ");
14372                    } else {
14373                        pw.print("lib,");
14374                    }
14375                    pw.print(name);
14376                    if (!checkin) {
14377                        pw.print(" -> ");
14378                    }
14379                    if (ent.path != null) {
14380                        if (!checkin) {
14381                            pw.print("(jar) ");
14382                            pw.print(ent.path);
14383                        } else {
14384                            pw.print(",jar,");
14385                            pw.print(ent.path);
14386                        }
14387                    } else {
14388                        if (!checkin) {
14389                            pw.print("(apk) ");
14390                            pw.print(ent.apk);
14391                        } else {
14392                            pw.print(",apk,");
14393                            pw.print(ent.apk);
14394                        }
14395                    }
14396                    pw.println();
14397                }
14398            }
14399
14400            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14401                if (dumpState.onTitlePrinted())
14402                    pw.println();
14403                if (!checkin) {
14404                    pw.println("Features:");
14405                }
14406                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14407                while (it.hasNext()) {
14408                    String name = it.next();
14409                    if (!checkin) {
14410                        pw.print("  ");
14411                    } else {
14412                        pw.print("feat,");
14413                    }
14414                    pw.println(name);
14415                }
14416            }
14417
14418            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14419                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14420                        : "Activity Resolver Table:", "  ", packageName,
14421                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14422                    dumpState.setTitlePrinted(true);
14423                }
14424                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14425                        : "Receiver Resolver Table:", "  ", packageName,
14426                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14427                    dumpState.setTitlePrinted(true);
14428                }
14429                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14430                        : "Service Resolver Table:", "  ", packageName,
14431                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14432                    dumpState.setTitlePrinted(true);
14433                }
14434                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14435                        : "Provider Resolver Table:", "  ", packageName,
14436                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14437                    dumpState.setTitlePrinted(true);
14438                }
14439            }
14440
14441            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14442                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14443                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14444                    int user = mSettings.mPreferredActivities.keyAt(i);
14445                    if (pir.dump(pw,
14446                            dumpState.getTitlePrinted()
14447                                ? "\nPreferred Activities User " + user + ":"
14448                                : "Preferred Activities User " + user + ":", "  ",
14449                            packageName, true, false)) {
14450                        dumpState.setTitlePrinted(true);
14451                    }
14452                }
14453            }
14454
14455            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14456                pw.flush();
14457                FileOutputStream fout = new FileOutputStream(fd);
14458                BufferedOutputStream str = new BufferedOutputStream(fout);
14459                XmlSerializer serializer = new FastXmlSerializer();
14460                try {
14461                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14462                    serializer.startDocument(null, true);
14463                    serializer.setFeature(
14464                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14465                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14466                    serializer.endDocument();
14467                    serializer.flush();
14468                } catch (IllegalArgumentException e) {
14469                    pw.println("Failed writing: " + e);
14470                } catch (IllegalStateException e) {
14471                    pw.println("Failed writing: " + e);
14472                } catch (IOException e) {
14473                    pw.println("Failed writing: " + e);
14474                }
14475            }
14476
14477            if (!checkin
14478                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14479                    && packageName == null) {
14480                pw.println();
14481                int count = mSettings.mPackages.size();
14482                if (count == 0) {
14483                    pw.println("No domain preferred apps!");
14484                    pw.println();
14485                } else {
14486                    final String prefix = "  ";
14487                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14488                    if (allPackageSettings.size() == 0) {
14489                        pw.println("No domain preferred apps!");
14490                        pw.println();
14491                    } else {
14492                        pw.println("Domain preferred apps status:");
14493                        pw.println();
14494                        count = 0;
14495                        for (PackageSetting ps : allPackageSettings) {
14496                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14497                            if (ivi == null || ivi.getPackageName() == null) continue;
14498                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14499                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14500                            pw.println(prefix + "Status: " + ivi.getStatusString());
14501                            pw.println();
14502                            count++;
14503                        }
14504                        if (count == 0) {
14505                            pw.println(prefix + "No domain preferred app status!");
14506                            pw.println();
14507                        }
14508                        for (int userId : sUserManager.getUserIds()) {
14509                            pw.println("Domain preferred apps for User " + userId + ":");
14510                            pw.println();
14511                            count = 0;
14512                            for (PackageSetting ps : allPackageSettings) {
14513                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14514                                if (ivi == null || ivi.getPackageName() == null) {
14515                                    continue;
14516                                }
14517                                final int status = ps.getDomainVerificationStatusForUser(userId);
14518                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14519                                    continue;
14520                                }
14521                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14522                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14523                                String statusStr = IntentFilterVerificationInfo.
14524                                        getStatusStringFromValue(status);
14525                                pw.println(prefix + "Status: " + statusStr);
14526                                pw.println();
14527                                count++;
14528                            }
14529                            if (count == 0) {
14530                                pw.println(prefix + "No domain preferred apps!");
14531                                pw.println();
14532                            }
14533                        }
14534                    }
14535                }
14536            }
14537
14538            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14539                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
14540                if (packageName == null) {
14541                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14542                        if (iperm == 0) {
14543                            if (dumpState.onTitlePrinted())
14544                                pw.println();
14545                            pw.println("AppOp Permissions:");
14546                        }
14547                        pw.print("  AppOp Permission ");
14548                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14549                        pw.println(":");
14550                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14551                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14552                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14553                        }
14554                    }
14555                }
14556            }
14557
14558            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14559                boolean printedSomething = false;
14560                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14561                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14562                        continue;
14563                    }
14564                    if (!printedSomething) {
14565                        if (dumpState.onTitlePrinted())
14566                            pw.println();
14567                        pw.println("Registered ContentProviders:");
14568                        printedSomething = true;
14569                    }
14570                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14571                    pw.print("    "); pw.println(p.toString());
14572                }
14573                printedSomething = false;
14574                for (Map.Entry<String, PackageParser.Provider> entry :
14575                        mProvidersByAuthority.entrySet()) {
14576                    PackageParser.Provider p = entry.getValue();
14577                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14578                        continue;
14579                    }
14580                    if (!printedSomething) {
14581                        if (dumpState.onTitlePrinted())
14582                            pw.println();
14583                        pw.println("ContentProvider Authorities:");
14584                        printedSomething = true;
14585                    }
14586                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14587                    pw.print("    "); pw.println(p.toString());
14588                    if (p.info != null && p.info.applicationInfo != null) {
14589                        final String appInfo = p.info.applicationInfo.toString();
14590                        pw.print("      applicationInfo="); pw.println(appInfo);
14591                    }
14592                }
14593            }
14594
14595            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14596                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14597            }
14598
14599            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14600                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
14601            }
14602
14603            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14604                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
14605            }
14606
14607            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14608                // XXX should handle packageName != null by dumping only install data that
14609                // the given package is involved with.
14610                if (dumpState.onTitlePrinted()) pw.println();
14611                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14612            }
14613
14614            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14615                if (dumpState.onTitlePrinted()) pw.println();
14616                mSettings.dumpReadMessagesLPr(pw, dumpState);
14617
14618                pw.println();
14619                pw.println("Package warning messages:");
14620                BufferedReader in = null;
14621                String line = null;
14622                try {
14623                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14624                    while ((line = in.readLine()) != null) {
14625                        if (line.contains("ignored: updated version")) continue;
14626                        pw.println(line);
14627                    }
14628                } catch (IOException ignored) {
14629                } finally {
14630                    IoUtils.closeQuietly(in);
14631                }
14632            }
14633
14634            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14635                BufferedReader in = null;
14636                String line = null;
14637                try {
14638                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14639                    while ((line = in.readLine()) != null) {
14640                        if (line.contains("ignored: updated version")) continue;
14641                        pw.print("msg,");
14642                        pw.println(line);
14643                    }
14644                } catch (IOException ignored) {
14645                } finally {
14646                    IoUtils.closeQuietly(in);
14647                }
14648            }
14649        }
14650    }
14651
14652    // ------- apps on sdcard specific code -------
14653    static final boolean DEBUG_SD_INSTALL = false;
14654
14655    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14656
14657    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14658
14659    private boolean mMediaMounted = false;
14660
14661    static String getEncryptKey() {
14662        try {
14663            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14664                    SD_ENCRYPTION_KEYSTORE_NAME);
14665            if (sdEncKey == null) {
14666                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14667                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14668                if (sdEncKey == null) {
14669                    Slog.e(TAG, "Failed to create encryption keys");
14670                    return null;
14671                }
14672            }
14673            return sdEncKey;
14674        } catch (NoSuchAlgorithmException nsae) {
14675            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14676            return null;
14677        } catch (IOException ioe) {
14678            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14679            return null;
14680        }
14681    }
14682
14683    /*
14684     * Update media status on PackageManager.
14685     */
14686    @Override
14687    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14688        int callingUid = Binder.getCallingUid();
14689        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14690            throw new SecurityException("Media status can only be updated by the system");
14691        }
14692        // reader; this apparently protects mMediaMounted, but should probably
14693        // be a different lock in that case.
14694        synchronized (mPackages) {
14695            Log.i(TAG, "Updating external media status from "
14696                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14697                    + (mediaStatus ? "mounted" : "unmounted"));
14698            if (DEBUG_SD_INSTALL)
14699                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14700                        + ", mMediaMounted=" + mMediaMounted);
14701            if (mediaStatus == mMediaMounted) {
14702                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14703                        : 0, -1);
14704                mHandler.sendMessage(msg);
14705                return;
14706            }
14707            mMediaMounted = mediaStatus;
14708        }
14709        // Queue up an async operation since the package installation may take a
14710        // little while.
14711        mHandler.post(new Runnable() {
14712            public void run() {
14713                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14714            }
14715        });
14716    }
14717
14718    /**
14719     * Called by MountService when the initial ASECs to scan are available.
14720     * Should block until all the ASEC containers are finished being scanned.
14721     */
14722    public void scanAvailableAsecs() {
14723        updateExternalMediaStatusInner(true, false, false);
14724        if (mShouldRestoreconData) {
14725            SELinuxMMAC.setRestoreconDone();
14726            mShouldRestoreconData = false;
14727        }
14728    }
14729
14730    /*
14731     * Collect information of applications on external media, map them against
14732     * existing containers and update information based on current mount status.
14733     * Please note that we always have to report status if reportStatus has been
14734     * set to true especially when unloading packages.
14735     */
14736    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14737            boolean externalStorage) {
14738        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14739        int[] uidArr = EmptyArray.INT;
14740
14741        final String[] list = PackageHelper.getSecureContainerList();
14742        if (ArrayUtils.isEmpty(list)) {
14743            Log.i(TAG, "No secure containers found");
14744        } else {
14745            // Process list of secure containers and categorize them
14746            // as active or stale based on their package internal state.
14747
14748            // reader
14749            synchronized (mPackages) {
14750                for (String cid : list) {
14751                    // Leave stages untouched for now; installer service owns them
14752                    if (PackageInstallerService.isStageName(cid)) continue;
14753
14754                    if (DEBUG_SD_INSTALL)
14755                        Log.i(TAG, "Processing container " + cid);
14756                    String pkgName = getAsecPackageName(cid);
14757                    if (pkgName == null) {
14758                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14759                        continue;
14760                    }
14761                    if (DEBUG_SD_INSTALL)
14762                        Log.i(TAG, "Looking for pkg : " + pkgName);
14763
14764                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14765                    if (ps == null) {
14766                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14767                        continue;
14768                    }
14769
14770                    /*
14771                     * Skip packages that are not external if we're unmounting
14772                     * external storage.
14773                     */
14774                    if (externalStorage && !isMounted && !isExternal(ps)) {
14775                        continue;
14776                    }
14777
14778                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14779                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14780                    // The package status is changed only if the code path
14781                    // matches between settings and the container id.
14782                    if (ps.codePathString != null
14783                            && ps.codePathString.startsWith(args.getCodePath())) {
14784                        if (DEBUG_SD_INSTALL) {
14785                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14786                                    + " at code path: " + ps.codePathString);
14787                        }
14788
14789                        // We do have a valid package installed on sdcard
14790                        processCids.put(args, ps.codePathString);
14791                        final int uid = ps.appId;
14792                        if (uid != -1) {
14793                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14794                        }
14795                    } else {
14796                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14797                                + ps.codePathString);
14798                    }
14799                }
14800            }
14801
14802            Arrays.sort(uidArr);
14803        }
14804
14805        // Process packages with valid entries.
14806        if (isMounted) {
14807            if (DEBUG_SD_INSTALL)
14808                Log.i(TAG, "Loading packages");
14809            loadMediaPackages(processCids, uidArr);
14810            startCleaningPackages();
14811            mInstallerService.onSecureContainersAvailable();
14812        } else {
14813            if (DEBUG_SD_INSTALL)
14814                Log.i(TAG, "Unloading packages");
14815            unloadMediaPackages(processCids, uidArr, reportStatus);
14816        }
14817    }
14818
14819    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14820            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14821        final int size = infos.size();
14822        final String[] packageNames = new String[size];
14823        final int[] packageUids = new int[size];
14824        for (int i = 0; i < size; i++) {
14825            final ApplicationInfo info = infos.get(i);
14826            packageNames[i] = info.packageName;
14827            packageUids[i] = info.uid;
14828        }
14829        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14830                finishedReceiver);
14831    }
14832
14833    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14834            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14835        sendResourcesChangedBroadcast(mediaStatus, replacing,
14836                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14837    }
14838
14839    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14840            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14841        int size = pkgList.length;
14842        if (size > 0) {
14843            // Send broadcasts here
14844            Bundle extras = new Bundle();
14845            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14846            if (uidArr != null) {
14847                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14848            }
14849            if (replacing) {
14850                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14851            }
14852            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14853                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14854            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14855        }
14856    }
14857
14858   /*
14859     * Look at potentially valid container ids from processCids If package
14860     * information doesn't match the one on record or package scanning fails,
14861     * the cid is added to list of removeCids. We currently don't delete stale
14862     * containers.
14863     */
14864    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14865        ArrayList<String> pkgList = new ArrayList<String>();
14866        Set<AsecInstallArgs> keys = processCids.keySet();
14867
14868        for (AsecInstallArgs args : keys) {
14869            String codePath = processCids.get(args);
14870            if (DEBUG_SD_INSTALL)
14871                Log.i(TAG, "Loading container : " + args.cid);
14872            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14873            try {
14874                // Make sure there are no container errors first.
14875                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14876                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14877                            + " when installing from sdcard");
14878                    continue;
14879                }
14880                // Check code path here.
14881                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14882                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14883                            + " does not match one in settings " + codePath);
14884                    continue;
14885                }
14886                // Parse package
14887                int parseFlags = mDefParseFlags;
14888                if (args.isExternalAsec()) {
14889                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
14890                }
14891                if (args.isFwdLocked()) {
14892                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
14893                }
14894
14895                synchronized (mInstallLock) {
14896                    PackageParser.Package pkg = null;
14897                    try {
14898                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
14899                    } catch (PackageManagerException e) {
14900                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
14901                    }
14902                    // Scan the package
14903                    if (pkg != null) {
14904                        /*
14905                         * TODO why is the lock being held? doPostInstall is
14906                         * called in other places without the lock. This needs
14907                         * to be straightened out.
14908                         */
14909                        // writer
14910                        synchronized (mPackages) {
14911                            retCode = PackageManager.INSTALL_SUCCEEDED;
14912                            pkgList.add(pkg.packageName);
14913                            // Post process args
14914                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
14915                                    pkg.applicationInfo.uid);
14916                        }
14917                    } else {
14918                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
14919                    }
14920                }
14921
14922            } finally {
14923                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
14924                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
14925                }
14926            }
14927        }
14928        // writer
14929        synchronized (mPackages) {
14930            // If the platform SDK has changed since the last time we booted,
14931            // we need to re-grant app permission to catch any new ones that
14932            // appear. This is really a hack, and means that apps can in some
14933            // cases get permissions that the user didn't initially explicitly
14934            // allow... it would be nice to have some better way to handle
14935            // this situation.
14936            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
14937            if (regrantPermissions)
14938                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
14939                        + mSdkVersion + "; regranting permissions for external storage");
14940            mSettings.mExternalSdkPlatform = mSdkVersion;
14941
14942            // Make sure group IDs have been assigned, and any permission
14943            // changes in other apps are accounted for
14944            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14945                    | (regrantPermissions
14946                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14947                            : 0));
14948
14949            mSettings.updateExternalDatabaseVersion();
14950
14951            // can downgrade to reader
14952            // Persist settings
14953            mSettings.writeLPr();
14954        }
14955        // Send a broadcast to let everyone know we are done processing
14956        if (pkgList.size() > 0) {
14957            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14958        }
14959    }
14960
14961   /*
14962     * Utility method to unload a list of specified containers
14963     */
14964    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14965        // Just unmount all valid containers.
14966        for (AsecInstallArgs arg : cidArgs) {
14967            synchronized (mInstallLock) {
14968                arg.doPostDeleteLI(false);
14969           }
14970       }
14971   }
14972
14973    /*
14974     * Unload packages mounted on external media. This involves deleting package
14975     * data from internal structures, sending broadcasts about diabled packages,
14976     * gc'ing to free up references, unmounting all secure containers
14977     * corresponding to packages on external media, and posting a
14978     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14979     * that we always have to post this message if status has been requested no
14980     * matter what.
14981     */
14982    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14983            final boolean reportStatus) {
14984        if (DEBUG_SD_INSTALL)
14985            Log.i(TAG, "unloading media packages");
14986        ArrayList<String> pkgList = new ArrayList<String>();
14987        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14988        final Set<AsecInstallArgs> keys = processCids.keySet();
14989        for (AsecInstallArgs args : keys) {
14990            String pkgName = args.getPackageName();
14991            if (DEBUG_SD_INSTALL)
14992                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14993            // Delete package internally
14994            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14995            synchronized (mInstallLock) {
14996                boolean res = deletePackageLI(pkgName, null, false, null, null,
14997                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14998                if (res) {
14999                    pkgList.add(pkgName);
15000                } else {
15001                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15002                    failedList.add(args);
15003                }
15004            }
15005        }
15006
15007        // reader
15008        synchronized (mPackages) {
15009            // We didn't update the settings after removing each package;
15010            // write them now for all packages.
15011            mSettings.writeLPr();
15012        }
15013
15014        // We have to absolutely send UPDATED_MEDIA_STATUS only
15015        // after confirming that all the receivers processed the ordered
15016        // broadcast when packages get disabled, force a gc to clean things up.
15017        // and unload all the containers.
15018        if (pkgList.size() > 0) {
15019            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15020                    new IIntentReceiver.Stub() {
15021                public void performReceive(Intent intent, int resultCode, String data,
15022                        Bundle extras, boolean ordered, boolean sticky,
15023                        int sendingUser) throws RemoteException {
15024                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15025                            reportStatus ? 1 : 0, 1, keys);
15026                    mHandler.sendMessage(msg);
15027                }
15028            });
15029        } else {
15030            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15031                    keys);
15032            mHandler.sendMessage(msg);
15033        }
15034    }
15035
15036    private void loadPrivatePackages(VolumeInfo vol) {
15037        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15038        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15039        synchronized (mInstallLock) {
15040        synchronized (mPackages) {
15041            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15042            for (PackageSetting ps : packages) {
15043                final PackageParser.Package pkg;
15044                try {
15045                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15046                    loaded.add(pkg.applicationInfo);
15047                } catch (PackageManagerException e) {
15048                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15049                }
15050            }
15051
15052            // TODO: regrant any permissions that changed based since original install
15053
15054            mSettings.writeLPr();
15055        }
15056        }
15057
15058        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15059        sendResourcesChangedBroadcast(true, false, loaded, null);
15060    }
15061
15062    private void unloadPrivatePackages(VolumeInfo vol) {
15063        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15064        synchronized (mInstallLock) {
15065        synchronized (mPackages) {
15066            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15067            for (PackageSetting ps : packages) {
15068                if (ps.pkg == null) continue;
15069
15070                final ApplicationInfo info = ps.pkg.applicationInfo;
15071                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15072                if (deletePackageLI(ps.name, null, false, null, null,
15073                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15074                    unloaded.add(info);
15075                } else {
15076                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15077                }
15078            }
15079
15080            mSettings.writeLPr();
15081        }
15082        }
15083
15084        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15085        sendResourcesChangedBroadcast(false, false, unloaded, null);
15086    }
15087
15088    private void unfreezePackage(String packageName) {
15089        synchronized (mPackages) {
15090            final PackageSetting ps = mSettings.mPackages.get(packageName);
15091            if (ps != null) {
15092                ps.frozen = false;
15093            }
15094        }
15095    }
15096
15097    @Override
15098    public int movePackage(final String packageName, final String volumeUuid) {
15099        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15100
15101        final int moveId = mNextMoveId.getAndIncrement();
15102        try {
15103            movePackageInternal(packageName, volumeUuid, moveId);
15104        } catch (PackageManagerException e) {
15105            Slog.w(TAG, "Failed to move " + packageName, e);
15106            mMoveCallbacks.notifyStatusChanged(moveId,
15107                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15108        }
15109        return moveId;
15110    }
15111
15112    private void movePackageInternal(final String packageName, final String volumeUuid,
15113            final int moveId) throws PackageManagerException {
15114        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15115        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15116        final PackageManager pm = mContext.getPackageManager();
15117
15118        final boolean currentAsec;
15119        final String currentVolumeUuid;
15120        final File codeFile;
15121        final String installerPackageName;
15122        final String packageAbiOverride;
15123        final int appId;
15124        final String seinfo;
15125        final String label;
15126
15127        // reader
15128        synchronized (mPackages) {
15129            final PackageParser.Package pkg = mPackages.get(packageName);
15130            final PackageSetting ps = mSettings.mPackages.get(packageName);
15131            if (pkg == null || ps == null) {
15132                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15133            }
15134
15135            if (pkg.applicationInfo.isSystemApp()) {
15136                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15137                        "Cannot move system application");
15138            }
15139
15140            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15141                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15142                        "Package already moved to " + volumeUuid);
15143            }
15144
15145            final File probe = new File(pkg.codePath);
15146            final File probeOat = new File(probe, "oat");
15147            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15148                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15149                        "Move only supported for modern cluster style installs");
15150            }
15151
15152            if (ps.frozen) {
15153                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15154                        "Failed to move already frozen package");
15155            }
15156            ps.frozen = true;
15157
15158            currentAsec = pkg.applicationInfo.isForwardLocked()
15159                    || pkg.applicationInfo.isExternalAsec();
15160            currentVolumeUuid = ps.volumeUuid;
15161            codeFile = new File(pkg.codePath);
15162            installerPackageName = ps.installerPackageName;
15163            packageAbiOverride = ps.cpuAbiOverrideString;
15164            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15165            seinfo = pkg.applicationInfo.seinfo;
15166            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15167        }
15168
15169        // Now that we're guarded by frozen state, kill app during move
15170        killApplication(packageName, appId, "move pkg");
15171
15172        final Bundle extras = new Bundle();
15173        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15174        extras.putString(Intent.EXTRA_TITLE, label);
15175        mMoveCallbacks.notifyCreated(moveId, extras);
15176
15177        int installFlags;
15178        final boolean moveCompleteApp;
15179        final File measurePath;
15180
15181        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15182            installFlags = INSTALL_INTERNAL;
15183            moveCompleteApp = !currentAsec;
15184            measurePath = Environment.getDataAppDirectory(volumeUuid);
15185        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15186            installFlags = INSTALL_EXTERNAL;
15187            moveCompleteApp = false;
15188            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15189        } else {
15190            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15191            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15192                    || !volume.isMountedWritable()) {
15193                unfreezePackage(packageName);
15194                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15195                        "Move location not mounted private volume");
15196            }
15197
15198            Preconditions.checkState(!currentAsec);
15199
15200            installFlags = INSTALL_INTERNAL;
15201            moveCompleteApp = true;
15202            measurePath = Environment.getDataAppDirectory(volumeUuid);
15203        }
15204
15205        final PackageStats stats = new PackageStats(null, -1);
15206        synchronized (mInstaller) {
15207            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15208                unfreezePackage(packageName);
15209                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15210                        "Failed to measure package size");
15211            }
15212        }
15213
15214        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15215                + stats.dataSize);
15216
15217        final long startFreeBytes = measurePath.getFreeSpace();
15218        final long sizeBytes;
15219        if (moveCompleteApp) {
15220            sizeBytes = stats.codeSize + stats.dataSize;
15221        } else {
15222            sizeBytes = stats.codeSize;
15223        }
15224
15225        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15226            unfreezePackage(packageName);
15227            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15228                    "Not enough free space to move");
15229        }
15230
15231        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15232
15233        final CountDownLatch installedLatch = new CountDownLatch(1);
15234        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15235            @Override
15236            public void onUserActionRequired(Intent intent) throws RemoteException {
15237                throw new IllegalStateException();
15238            }
15239
15240            @Override
15241            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15242                    Bundle extras) throws RemoteException {
15243                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15244                        + PackageManager.installStatusToString(returnCode, msg));
15245
15246                installedLatch.countDown();
15247
15248                // Regardless of success or failure of the move operation,
15249                // always unfreeze the package
15250                unfreezePackage(packageName);
15251
15252                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15253                switch (status) {
15254                    case PackageInstaller.STATUS_SUCCESS:
15255                        mMoveCallbacks.notifyStatusChanged(moveId,
15256                                PackageManager.MOVE_SUCCEEDED);
15257                        break;
15258                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15259                        mMoveCallbacks.notifyStatusChanged(moveId,
15260                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15261                        break;
15262                    default:
15263                        mMoveCallbacks.notifyStatusChanged(moveId,
15264                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15265                        break;
15266                }
15267            }
15268        };
15269
15270        final MoveInfo move;
15271        if (moveCompleteApp) {
15272            // Kick off a thread to report progress estimates
15273            new Thread() {
15274                @Override
15275                public void run() {
15276                    while (true) {
15277                        try {
15278                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15279                                break;
15280                            }
15281                        } catch (InterruptedException ignored) {
15282                        }
15283
15284                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15285                        final int progress = 10 + (int) MathUtils.constrain(
15286                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15287                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15288                    }
15289                }
15290            }.start();
15291
15292            final String dataAppName = codeFile.getName();
15293            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15294                    dataAppName, appId, seinfo);
15295        } else {
15296            move = null;
15297        }
15298
15299        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15300
15301        final Message msg = mHandler.obtainMessage(INIT_COPY);
15302        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15303        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15304                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15305        mHandler.sendMessage(msg);
15306    }
15307
15308    @Override
15309    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15310        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15311
15312        final int realMoveId = mNextMoveId.getAndIncrement();
15313        final Bundle extras = new Bundle();
15314        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15315        mMoveCallbacks.notifyCreated(realMoveId, extras);
15316
15317        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15318            @Override
15319            public void onCreated(int moveId, Bundle extras) {
15320                // Ignored
15321            }
15322
15323            @Override
15324            public void onStatusChanged(int moveId, int status, long estMillis) {
15325                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15326            }
15327        };
15328
15329        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15330        storage.setPrimaryStorageUuid(volumeUuid, callback);
15331        return realMoveId;
15332    }
15333
15334    @Override
15335    public int getMoveStatus(int moveId) {
15336        mContext.enforceCallingOrSelfPermission(
15337                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15338        return mMoveCallbacks.mLastStatus.get(moveId);
15339    }
15340
15341    @Override
15342    public void registerMoveCallback(IPackageMoveObserver callback) {
15343        mContext.enforceCallingOrSelfPermission(
15344                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15345        mMoveCallbacks.register(callback);
15346    }
15347
15348    @Override
15349    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15350        mContext.enforceCallingOrSelfPermission(
15351                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15352        mMoveCallbacks.unregister(callback);
15353    }
15354
15355    @Override
15356    public boolean setInstallLocation(int loc) {
15357        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15358                null);
15359        if (getInstallLocation() == loc) {
15360            return true;
15361        }
15362        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15363                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15364            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15365                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15366            return true;
15367        }
15368        return false;
15369   }
15370
15371    @Override
15372    public int getInstallLocation() {
15373        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15374                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15375                PackageHelper.APP_INSTALL_AUTO);
15376    }
15377
15378    /** Called by UserManagerService */
15379    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15380        mDirtyUsers.remove(userHandle);
15381        mSettings.removeUserLPw(userHandle);
15382        mPendingBroadcasts.remove(userHandle);
15383        if (mInstaller != null) {
15384            // Technically, we shouldn't be doing this with the package lock
15385            // held.  However, this is very rare, and there is already so much
15386            // other disk I/O going on, that we'll let it slide for now.
15387            final StorageManager storage = StorageManager.from(mContext);
15388            final List<VolumeInfo> vols = storage.getVolumes();
15389            for (VolumeInfo vol : vols) {
15390                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
15391                    final String volumeUuid = vol.getFsUuid();
15392                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15393                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15394                }
15395            }
15396        }
15397        mUserNeedsBadging.delete(userHandle);
15398        removeUnusedPackagesLILPw(userManager, userHandle);
15399    }
15400
15401    /**
15402     * We're removing userHandle and would like to remove any downloaded packages
15403     * that are no longer in use by any other user.
15404     * @param userHandle the user being removed
15405     */
15406    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15407        final boolean DEBUG_CLEAN_APKS = false;
15408        int [] users = userManager.getUserIdsLPr();
15409        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15410        while (psit.hasNext()) {
15411            PackageSetting ps = psit.next();
15412            if (ps.pkg == null) {
15413                continue;
15414            }
15415            final String packageName = ps.pkg.packageName;
15416            // Skip over if system app
15417            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15418                continue;
15419            }
15420            if (DEBUG_CLEAN_APKS) {
15421                Slog.i(TAG, "Checking package " + packageName);
15422            }
15423            boolean keep = false;
15424            for (int i = 0; i < users.length; i++) {
15425                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15426                    keep = true;
15427                    if (DEBUG_CLEAN_APKS) {
15428                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15429                                + users[i]);
15430                    }
15431                    break;
15432                }
15433            }
15434            if (!keep) {
15435                if (DEBUG_CLEAN_APKS) {
15436                    Slog.i(TAG, "  Removing package " + packageName);
15437                }
15438                mHandler.post(new Runnable() {
15439                    public void run() {
15440                        deletePackageX(packageName, userHandle, 0);
15441                    } //end run
15442                });
15443            }
15444        }
15445    }
15446
15447    /** Called by UserManagerService */
15448    void createNewUserLILPw(int userHandle, File path) {
15449        if (mInstaller != null) {
15450            mInstaller.createUserConfig(userHandle);
15451            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
15452        }
15453    }
15454
15455    void newUserCreatedLILPw(final int userHandle) {
15456        // We cannot grant the default permissions with a lock held as
15457        // we query providers from other components for default handlers
15458        // such as enabled IMEs, etc.
15459        mHandler.post(new Runnable() {
15460            @Override
15461            public void run() {
15462                mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15463            }
15464        });
15465    }
15466
15467    @Override
15468    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15469        mContext.enforceCallingOrSelfPermission(
15470                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15471                "Only package verification agents can read the verifier device identity");
15472
15473        synchronized (mPackages) {
15474            return mSettings.getVerifierDeviceIdentityLPw();
15475        }
15476    }
15477
15478    @Override
15479    public void setPermissionEnforced(String permission, boolean enforced) {
15480        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15481        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15482            synchronized (mPackages) {
15483                if (mSettings.mReadExternalStorageEnforced == null
15484                        || mSettings.mReadExternalStorageEnforced != enforced) {
15485                    mSettings.mReadExternalStorageEnforced = enforced;
15486                    mSettings.writeLPr();
15487                }
15488            }
15489            // kill any non-foreground processes so we restart them and
15490            // grant/revoke the GID.
15491            final IActivityManager am = ActivityManagerNative.getDefault();
15492            if (am != null) {
15493                final long token = Binder.clearCallingIdentity();
15494                try {
15495                    am.killProcessesBelowForeground("setPermissionEnforcement");
15496                } catch (RemoteException e) {
15497                } finally {
15498                    Binder.restoreCallingIdentity(token);
15499                }
15500            }
15501        } else {
15502            throw new IllegalArgumentException("No selective enforcement for " + permission);
15503        }
15504    }
15505
15506    @Override
15507    @Deprecated
15508    public boolean isPermissionEnforced(String permission) {
15509        return true;
15510    }
15511
15512    @Override
15513    public boolean isStorageLow() {
15514        final long token = Binder.clearCallingIdentity();
15515        try {
15516            final DeviceStorageMonitorInternal
15517                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15518            if (dsm != null) {
15519                return dsm.isMemoryLow();
15520            } else {
15521                return false;
15522            }
15523        } finally {
15524            Binder.restoreCallingIdentity(token);
15525        }
15526    }
15527
15528    @Override
15529    public IPackageInstaller getPackageInstaller() {
15530        return mInstallerService;
15531    }
15532
15533    private boolean userNeedsBadging(int userId) {
15534        int index = mUserNeedsBadging.indexOfKey(userId);
15535        if (index < 0) {
15536            final UserInfo userInfo;
15537            final long token = Binder.clearCallingIdentity();
15538            try {
15539                userInfo = sUserManager.getUserInfo(userId);
15540            } finally {
15541                Binder.restoreCallingIdentity(token);
15542            }
15543            final boolean b;
15544            if (userInfo != null && userInfo.isManagedProfile()) {
15545                b = true;
15546            } else {
15547                b = false;
15548            }
15549            mUserNeedsBadging.put(userId, b);
15550            return b;
15551        }
15552        return mUserNeedsBadging.valueAt(index);
15553    }
15554
15555    @Override
15556    public KeySet getKeySetByAlias(String packageName, String alias) {
15557        if (packageName == null || alias == null) {
15558            return null;
15559        }
15560        synchronized(mPackages) {
15561            final PackageParser.Package pkg = mPackages.get(packageName);
15562            if (pkg == null) {
15563                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15564                throw new IllegalArgumentException("Unknown package: " + packageName);
15565            }
15566            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15567            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15568        }
15569    }
15570
15571    @Override
15572    public KeySet getSigningKeySet(String packageName) {
15573        if (packageName == null) {
15574            return null;
15575        }
15576        synchronized(mPackages) {
15577            final PackageParser.Package pkg = mPackages.get(packageName);
15578            if (pkg == null) {
15579                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15580                throw new IllegalArgumentException("Unknown package: " + packageName);
15581            }
15582            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15583                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15584                throw new SecurityException("May not access signing KeySet of other apps.");
15585            }
15586            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15587            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15588        }
15589    }
15590
15591    @Override
15592    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15593        if (packageName == null || ks == null) {
15594            return false;
15595        }
15596        synchronized(mPackages) {
15597            final PackageParser.Package pkg = mPackages.get(packageName);
15598            if (pkg == null) {
15599                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15600                throw new IllegalArgumentException("Unknown package: " + packageName);
15601            }
15602            IBinder ksh = ks.getToken();
15603            if (ksh instanceof KeySetHandle) {
15604                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15605                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15606            }
15607            return false;
15608        }
15609    }
15610
15611    @Override
15612    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15613        if (packageName == null || ks == null) {
15614            return false;
15615        }
15616        synchronized(mPackages) {
15617            final PackageParser.Package pkg = mPackages.get(packageName);
15618            if (pkg == null) {
15619                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15620                throw new IllegalArgumentException("Unknown package: " + packageName);
15621            }
15622            IBinder ksh = ks.getToken();
15623            if (ksh instanceof KeySetHandle) {
15624                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15625                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15626            }
15627            return false;
15628        }
15629    }
15630
15631    public void getUsageStatsIfNoPackageUsageInfo() {
15632        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15633            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15634            if (usm == null) {
15635                throw new IllegalStateException("UsageStatsManager must be initialized");
15636            }
15637            long now = System.currentTimeMillis();
15638            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15639            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15640                String packageName = entry.getKey();
15641                PackageParser.Package pkg = mPackages.get(packageName);
15642                if (pkg == null) {
15643                    continue;
15644                }
15645                UsageStats usage = entry.getValue();
15646                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15647                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15648            }
15649        }
15650    }
15651
15652    /**
15653     * Check and throw if the given before/after packages would be considered a
15654     * downgrade.
15655     */
15656    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15657            throws PackageManagerException {
15658        if (after.versionCode < before.mVersionCode) {
15659            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15660                    "Update version code " + after.versionCode + " is older than current "
15661                    + before.mVersionCode);
15662        } else if (after.versionCode == before.mVersionCode) {
15663            if (after.baseRevisionCode < before.baseRevisionCode) {
15664                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15665                        "Update base revision code " + after.baseRevisionCode
15666                        + " is older than current " + before.baseRevisionCode);
15667            }
15668
15669            if (!ArrayUtils.isEmpty(after.splitNames)) {
15670                for (int i = 0; i < after.splitNames.length; i++) {
15671                    final String splitName = after.splitNames[i];
15672                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15673                    if (j != -1) {
15674                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15675                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15676                                    "Update split " + splitName + " revision code "
15677                                    + after.splitRevisionCodes[i] + " is older than current "
15678                                    + before.splitRevisionCodes[j]);
15679                        }
15680                    }
15681                }
15682            }
15683        }
15684    }
15685
15686    private static class MoveCallbacks extends Handler {
15687        private static final int MSG_CREATED = 1;
15688        private static final int MSG_STATUS_CHANGED = 2;
15689
15690        private final RemoteCallbackList<IPackageMoveObserver>
15691                mCallbacks = new RemoteCallbackList<>();
15692
15693        private final SparseIntArray mLastStatus = new SparseIntArray();
15694
15695        public MoveCallbacks(Looper looper) {
15696            super(looper);
15697        }
15698
15699        public void register(IPackageMoveObserver callback) {
15700            mCallbacks.register(callback);
15701        }
15702
15703        public void unregister(IPackageMoveObserver callback) {
15704            mCallbacks.unregister(callback);
15705        }
15706
15707        @Override
15708        public void handleMessage(Message msg) {
15709            final SomeArgs args = (SomeArgs) msg.obj;
15710            final int n = mCallbacks.beginBroadcast();
15711            for (int i = 0; i < n; i++) {
15712                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15713                try {
15714                    invokeCallback(callback, msg.what, args);
15715                } catch (RemoteException ignored) {
15716                }
15717            }
15718            mCallbacks.finishBroadcast();
15719            args.recycle();
15720        }
15721
15722        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15723                throws RemoteException {
15724            switch (what) {
15725                case MSG_CREATED: {
15726                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15727                    break;
15728                }
15729                case MSG_STATUS_CHANGED: {
15730                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15731                    break;
15732                }
15733            }
15734        }
15735
15736        private void notifyCreated(int moveId, Bundle extras) {
15737            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15738
15739            final SomeArgs args = SomeArgs.obtain();
15740            args.argi1 = moveId;
15741            args.arg2 = extras;
15742            obtainMessage(MSG_CREATED, args).sendToTarget();
15743        }
15744
15745        private void notifyStatusChanged(int moveId, int status) {
15746            notifyStatusChanged(moveId, status, -1);
15747        }
15748
15749        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15750            Slog.v(TAG, "Move " + moveId + " status " + status);
15751
15752            final SomeArgs args = SomeArgs.obtain();
15753            args.argi1 = moveId;
15754            args.argi2 = status;
15755            args.arg3 = estMillis;
15756            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15757
15758            synchronized (mLastStatus) {
15759                mLastStatus.put(moveId, status);
15760            }
15761        }
15762    }
15763
15764    private final class OnPermissionChangeListeners extends Handler {
15765        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
15766
15767        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
15768                new RemoteCallbackList<>();
15769
15770        public OnPermissionChangeListeners(Looper looper) {
15771            super(looper);
15772        }
15773
15774        @Override
15775        public void handleMessage(Message msg) {
15776            switch (msg.what) {
15777                case MSG_ON_PERMISSIONS_CHANGED: {
15778                    final int uid = msg.arg1;
15779                    handleOnPermissionsChanged(uid);
15780                } break;
15781            }
15782        }
15783
15784        public void addListenerLocked(IOnPermissionsChangeListener listener) {
15785            mPermissionListeners.register(listener);
15786
15787        }
15788
15789        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
15790            mPermissionListeners.unregister(listener);
15791        }
15792
15793        public void onPermissionsChanged(int uid) {
15794            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
15795                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
15796            }
15797        }
15798
15799        private void handleOnPermissionsChanged(int uid) {
15800            final int count = mPermissionListeners.beginBroadcast();
15801            try {
15802                for (int i = 0; i < count; i++) {
15803                    IOnPermissionsChangeListener callback = mPermissionListeners
15804                            .getBroadcastItem(i);
15805                    try {
15806                        callback.onPermissionsChanged(uid);
15807                    } catch (RemoteException e) {
15808                        Log.e(TAG, "Permission listener is dead", e);
15809                    }
15810                }
15811            } finally {
15812                mPermissionListeners.finishBroadcast();
15813            }
15814        }
15815    }
15816
15817    private class PackageManagerInternalImpl extends PackageManagerInternal {
15818        @Override
15819        public void setLocationPackagesProvider(PackagesProvider provider) {
15820            synchronized (mPackages) {
15821                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
15822            }
15823        }
15824
15825        @Override
15826        public void setImePackagesProvider(PackagesProvider provider) {
15827            synchronized (mPackages) {
15828                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
15829            }
15830        }
15831
15832        @Override
15833        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
15834            synchronized (mPackages) {
15835                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
15836            }
15837        }
15838    }
15839
15840    @Override
15841    public void grantDefaultPermissions(final int userId) {
15842        enforceSystemOrPhoneCaller("grantDefaultPermissions");
15843        long token = Binder.clearCallingIdentity();
15844        try {
15845            // We cannot grant the default permissions with a lock held as
15846            // we query providers from other components for default handlers
15847            // such as enabled IMEs, etc.
15848            mHandler.post(new Runnable() {
15849                @Override
15850                public void run() {
15851                    mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15852                }
15853            });
15854        } finally {
15855            Binder.restoreCallingIdentity(token);
15856        }
15857    }
15858
15859    @Override
15860    public void setCarrierAppPackagesProvider(final IPackagesProvider provider) {
15861        enforceSystemOrPhoneCaller("setCarrierAppPackagesProvider");
15862        long token = Binder.clearCallingIdentity();
15863        try {
15864            PackageManagerInternal.PackagesProvider wrapper =
15865                    new PackageManagerInternal.PackagesProvider() {
15866                @Override
15867                public String[] getPackages(int userId) {
15868                    try {
15869                        return provider.getPackages(userId);
15870                    } catch (RemoteException e) {
15871                        return null;
15872                    }
15873                }
15874            };
15875            synchronized (mPackages) {
15876                mDefaultPermissionPolicy.setCarrierAppPackagesProviderLPw(wrapper);
15877            }
15878        } finally {
15879            Binder.restoreCallingIdentity(token);
15880        }
15881    }
15882
15883    private static void enforceSystemOrPhoneCaller(String tag) {
15884        int callingUid = Binder.getCallingUid();
15885        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
15886            throw new SecurityException(
15887                    "Cannot call " + tag + " from UID " + callingUid);
15888        }
15889    }
15890}
15891