PackageManagerService.java revision 8bcb80ca90c1d1f2c04d9e3d6e52f8381dad0c26
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
22import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
34import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
60import static android.content.pm.PackageManager.MATCH_ALL;
61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
65import static android.content.pm.PackageManager.PERMISSION_GRANTED;
66import static android.content.pm.PackageParser.isApkFile;
67import static android.os.Process.PACKAGE_INFO_GID;
68import static android.os.Process.SYSTEM_UID;
69import static android.system.OsConstants.O_CREAT;
70import static android.system.OsConstants.O_RDWR;
71import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
73import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
74import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
75import static com.android.internal.util.ArrayUtils.appendInt;
76import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
77import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
79import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
80import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
81import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
84
85import android.Manifest;
86import android.app.ActivityManager;
87import android.app.ActivityManagerNative;
88import android.app.AppGlobals;
89import android.app.IActivityManager;
90import android.app.admin.IDevicePolicyManager;
91import android.app.backup.IBackupManager;
92import android.app.usage.UsageStats;
93import android.app.usage.UsageStatsManager;
94import android.content.BroadcastReceiver;
95import android.content.ComponentName;
96import android.content.Context;
97import android.content.IIntentReceiver;
98import android.content.Intent;
99import android.content.IntentFilter;
100import android.content.IntentSender;
101import android.content.IntentSender.SendIntentException;
102import android.content.ServiceConnection;
103import android.content.pm.ActivityInfo;
104import android.content.pm.ApplicationInfo;
105import android.content.pm.FeatureInfo;
106import android.content.pm.IOnPermissionsChangeListener;
107import android.content.pm.IPackageDataObserver;
108import android.content.pm.IPackageDeleteObserver;
109import android.content.pm.IPackageDeleteObserver2;
110import android.content.pm.IPackageInstallObserver2;
111import android.content.pm.IPackageInstaller;
112import android.content.pm.IPackageManager;
113import android.content.pm.IPackageMoveObserver;
114import android.content.pm.IPackageStatsObserver;
115import android.content.pm.InstrumentationInfo;
116import android.content.pm.IntentFilterVerificationInfo;
117import android.content.pm.KeySet;
118import android.content.pm.ManifestDigest;
119import android.content.pm.PackageCleanItem;
120import android.content.pm.PackageInfo;
121import android.content.pm.PackageInfoLite;
122import android.content.pm.PackageInstaller;
123import android.content.pm.PackageManager;
124import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
125import android.content.pm.PackageManagerInternal;
126import android.content.pm.PackageParser;
127import android.content.pm.PackageParser.ActivityIntentInfo;
128import android.content.pm.PackageParser.PackageLite;
129import android.content.pm.PackageParser.PackageParserException;
130import android.content.pm.PackageStats;
131import android.content.pm.PackageUserState;
132import android.content.pm.ParceledListSlice;
133import android.content.pm.PermissionGroupInfo;
134import android.content.pm.PermissionInfo;
135import android.content.pm.ProviderInfo;
136import android.content.pm.ResolveInfo;
137import android.content.pm.ServiceInfo;
138import android.content.pm.Signature;
139import android.content.pm.UserInfo;
140import android.content.pm.VerificationParams;
141import android.content.pm.VerifierDeviceIdentity;
142import android.content.pm.VerifierInfo;
143import android.content.res.Resources;
144import android.hardware.display.DisplayManager;
145import android.net.Uri;
146import android.os.Binder;
147import android.os.Build;
148import android.os.Bundle;
149import android.os.Environment;
150import android.os.Environment.UserEnvironment;
151import android.os.FileUtils;
152import android.os.Handler;
153import android.os.IBinder;
154import android.os.Looper;
155import android.os.Message;
156import android.os.Parcel;
157import android.os.ParcelFileDescriptor;
158import android.os.Process;
159import android.os.RemoteCallbackList;
160import android.os.RemoteException;
161import android.os.SELinux;
162import android.os.ServiceManager;
163import android.os.SystemClock;
164import android.os.SystemProperties;
165import android.os.UserHandle;
166import android.os.UserManager;
167import android.os.storage.IMountService;
168import android.os.storage.StorageEventListener;
169import android.os.storage.StorageManager;
170import android.os.storage.VolumeInfo;
171import android.os.storage.VolumeRecord;
172import android.security.KeyStore;
173import android.security.SystemKeyStore;
174import android.system.ErrnoException;
175import android.system.Os;
176import android.system.StructStat;
177import android.text.TextUtils;
178import android.text.format.DateUtils;
179import android.util.ArrayMap;
180import android.util.ArraySet;
181import android.util.AtomicFile;
182import android.util.DisplayMetrics;
183import android.util.EventLog;
184import android.util.ExceptionUtils;
185import android.util.Log;
186import android.util.LogPrinter;
187import android.util.MathUtils;
188import android.util.PrintStreamPrinter;
189import android.util.Slog;
190import android.util.SparseArray;
191import android.util.SparseBooleanArray;
192import android.util.SparseIntArray;
193import android.util.Xml;
194import android.view.Display;
195
196import dalvik.system.DexFile;
197import dalvik.system.VMRuntime;
198
199import libcore.io.IoUtils;
200import libcore.util.EmptyArray;
201
202import com.android.internal.R;
203import com.android.internal.annotations.GuardedBy;
204import com.android.internal.app.IMediaContainerService;
205import com.android.internal.app.ResolverActivity;
206import com.android.internal.content.NativeLibraryHelper;
207import com.android.internal.content.PackageHelper;
208import com.android.internal.os.IParcelFileDescriptorFactory;
209import com.android.internal.os.SomeArgs;
210import com.android.internal.os.Zygote;
211import com.android.internal.util.ArrayUtils;
212import com.android.internal.util.FastPrintWriter;
213import com.android.internal.util.FastXmlSerializer;
214import com.android.internal.util.IndentingPrintWriter;
215import com.android.internal.util.Preconditions;
216import com.android.server.EventLogTags;
217import com.android.server.FgThread;
218import com.android.server.IntentResolver;
219import com.android.server.LocalServices;
220import com.android.server.ServiceThread;
221import com.android.server.SystemConfig;
222import com.android.server.Watchdog;
223import com.android.server.pm.PermissionsState.PermissionState;
224import com.android.server.pm.Settings.DatabaseVersion;
225import com.android.server.storage.DeviceStorageMonitorInternal;
226
227import org.xmlpull.v1.XmlPullParser;
228import org.xmlpull.v1.XmlPullParserException;
229import org.xmlpull.v1.XmlSerializer;
230
231import java.io.BufferedInputStream;
232import java.io.BufferedOutputStream;
233import java.io.BufferedReader;
234import java.io.ByteArrayInputStream;
235import java.io.ByteArrayOutputStream;
236import java.io.File;
237import java.io.FileDescriptor;
238import java.io.FileNotFoundException;
239import java.io.FileOutputStream;
240import java.io.FileReader;
241import java.io.FilenameFilter;
242import java.io.IOException;
243import java.io.InputStream;
244import java.io.PrintWriter;
245import java.nio.charset.StandardCharsets;
246import java.security.NoSuchAlgorithmException;
247import java.security.PublicKey;
248import java.security.cert.CertificateEncodingException;
249import java.security.cert.CertificateException;
250import java.text.SimpleDateFormat;
251import java.util.ArrayList;
252import java.util.Arrays;
253import java.util.Collection;
254import java.util.Collections;
255import java.util.Comparator;
256import java.util.Date;
257import java.util.Iterator;
258import java.util.List;
259import java.util.Map;
260import java.util.Objects;
261import java.util.Set;
262import java.util.concurrent.CountDownLatch;
263import java.util.concurrent.TimeUnit;
264import java.util.concurrent.atomic.AtomicBoolean;
265import java.util.concurrent.atomic.AtomicInteger;
266import java.util.concurrent.atomic.AtomicLong;
267
268/**
269 * Keep track of all those .apks everywhere.
270 *
271 * This is very central to the platform's security; please run the unit
272 * tests whenever making modifications here:
273 *
274runtest -c android.content.pm.PackageManagerTests frameworks-core
275 *
276 * {@hide}
277 */
278public class PackageManagerService extends IPackageManager.Stub {
279    static final String TAG = "PackageManager";
280    static final boolean DEBUG_SETTINGS = false;
281    static final boolean DEBUG_PREFERRED = false;
282    static final boolean DEBUG_UPGRADE = false;
283    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
284    private static final boolean DEBUG_BACKUP = false;
285    private static final boolean DEBUG_INSTALL = false;
286    private static final boolean DEBUG_REMOVE = false;
287    private static final boolean DEBUG_BROADCASTS = false;
288    private static final boolean DEBUG_SHOW_INFO = false;
289    private static final boolean DEBUG_PACKAGE_INFO = false;
290    private static final boolean DEBUG_INTENT_MATCHING = false;
291    private static final boolean DEBUG_PACKAGE_SCANNING = false;
292    private static final boolean DEBUG_VERIFY = false;
293    private static final boolean DEBUG_DEXOPT = false;
294    private static final boolean DEBUG_ABI_SELECTION = false;
295
296    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
297
298    private static final int RADIO_UID = Process.PHONE_UID;
299    private static final int LOG_UID = Process.LOG_UID;
300    private static final int NFC_UID = Process.NFC_UID;
301    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
302    private static final int SHELL_UID = Process.SHELL_UID;
303
304    // Cap the size of permission trees that 3rd party apps can define
305    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
306
307    // Suffix used during package installation when copying/moving
308    // package apks to install directory.
309    private static final String INSTALL_PACKAGE_SUFFIX = "-";
310
311    static final int SCAN_NO_DEX = 1<<1;
312    static final int SCAN_FORCE_DEX = 1<<2;
313    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
314    static final int SCAN_NEW_INSTALL = 1<<4;
315    static final int SCAN_NO_PATHS = 1<<5;
316    static final int SCAN_UPDATE_TIME = 1<<6;
317    static final int SCAN_DEFER_DEX = 1<<7;
318    static final int SCAN_BOOTING = 1<<8;
319    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
320    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
321    static final int SCAN_REQUIRE_KNOWN = 1<<12;
322    static final int SCAN_MOVE = 1<<13;
323    static final int SCAN_INITIAL = 1<<14;
324
325    static final int REMOVE_CHATTY = 1<<16;
326
327    private static final int[] EMPTY_INT_ARRAY = new int[0];
328
329    /**
330     * Timeout (in milliseconds) after which the watchdog should declare that
331     * our handler thread is wedged.  The usual default for such things is one
332     * minute but we sometimes do very lengthy I/O operations on this thread,
333     * such as installing multi-gigabyte applications, so ours needs to be longer.
334     */
335    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
336
337    /**
338     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
339     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
340     * settings entry if available, otherwise we use the hardcoded default.  If it's been
341     * more than this long since the last fstrim, we force one during the boot sequence.
342     *
343     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
344     * one gets run at the next available charging+idle time.  This final mandatory
345     * no-fstrim check kicks in only of the other scheduling criteria is never met.
346     */
347    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
348
349    /**
350     * Whether verification is enabled by default.
351     */
352    private static final boolean DEFAULT_VERIFY_ENABLE = true;
353
354    /**
355     * The default maximum time to wait for the verification agent to return in
356     * milliseconds.
357     */
358    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
359
360    /**
361     * The default response for package verification timeout.
362     *
363     * This can be either PackageManager.VERIFICATION_ALLOW or
364     * PackageManager.VERIFICATION_REJECT.
365     */
366    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
367
368    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
369
370    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
371            DEFAULT_CONTAINER_PACKAGE,
372            "com.android.defcontainer.DefaultContainerService");
373
374    private static final String KILL_APP_REASON_GIDS_CHANGED =
375            "permission grant or revoke changed gids";
376
377    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
378            "permissions revoked";
379
380    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
381
382    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
383
384    /** Permission grant: not grant the permission. */
385    private static final int GRANT_DENIED = 1;
386
387    /** Permission grant: grant the permission as an install permission. */
388    private static final int GRANT_INSTALL = 2;
389
390    /** Permission grant: grant the permission as an install permission for a legacy app. */
391    private static final int GRANT_INSTALL_LEGACY = 3;
392
393    /** Permission grant: grant the permission as a runtime one. */
394    private static final int GRANT_RUNTIME = 4;
395
396    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
397    private static final int GRANT_UPGRADE = 5;
398
399    /** Canonical intent used to identify what counts as a "web browser" app */
400    private static final Intent sBrowserIntent;
401    static {
402        sBrowserIntent = new Intent();
403        sBrowserIntent.setAction(Intent.ACTION_VIEW);
404        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
405        sBrowserIntent.setData(Uri.parse("http:"));
406    }
407
408    final ServiceThread mHandlerThread;
409
410    final PackageHandler mHandler;
411
412    /**
413     * Messages for {@link #mHandler} that need to wait for system ready before
414     * being dispatched.
415     */
416    private ArrayList<Message> mPostSystemReadyMessages;
417
418    final int mSdkVersion = Build.VERSION.SDK_INT;
419
420    final Context mContext;
421    final boolean mFactoryTest;
422    final boolean mOnlyCore;
423    final boolean mLazyDexOpt;
424    final long mDexOptLRUThresholdInMills;
425    final DisplayMetrics mMetrics;
426    final int mDefParseFlags;
427    final String[] mSeparateProcesses;
428    final boolean mIsUpgrade;
429
430    // This is where all application persistent data goes.
431    final File mAppDataDir;
432
433    // This is where all application persistent data goes for secondary users.
434    final File mUserAppDataDir;
435
436    /** The location for ASEC container files on internal storage. */
437    final String mAsecInternalPath;
438
439    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
440    // LOCK HELD.  Can be called with mInstallLock held.
441    @GuardedBy("mInstallLock")
442    final Installer mInstaller;
443
444    /** Directory where installed third-party apps stored */
445    final File mAppInstallDir;
446
447    /**
448     * Directory to which applications installed internally have their
449     * 32 bit native libraries copied.
450     */
451    private File mAppLib32InstallDir;
452
453    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
454    // apps.
455    final File mDrmAppPrivateInstallDir;
456
457    // ----------------------------------------------------------------
458
459    // Lock for state used when installing and doing other long running
460    // operations.  Methods that must be called with this lock held have
461    // the suffix "LI".
462    final Object mInstallLock = new Object();
463
464    // ----------------------------------------------------------------
465
466    // Keys are String (package name), values are Package.  This also serves
467    // as the lock for the global state.  Methods that must be called with
468    // this lock held have the prefix "LP".
469    @GuardedBy("mPackages")
470    final ArrayMap<String, PackageParser.Package> mPackages =
471            new ArrayMap<String, PackageParser.Package>();
472
473    // Tracks available target package names -> overlay package paths.
474    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
475        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
476
477    /**
478     * Tracks new system packages [receiving in an OTA] that we expect to
479     * find updated user-installed versions. Keys are package name, values
480     * are package location.
481     */
482    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
483
484    final Settings mSettings;
485    boolean mRestoredSettings;
486
487    // System configuration read by SystemConfig.
488    final int[] mGlobalGids;
489    final SparseArray<ArraySet<String>> mSystemPermissions;
490    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
491
492    // If mac_permissions.xml was found for seinfo labeling.
493    boolean mFoundPolicyFile;
494
495    // If a recursive restorecon of /data/data/<pkg> is needed.
496    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
497
498    public static final class SharedLibraryEntry {
499        public final String path;
500        public final String apk;
501
502        SharedLibraryEntry(String _path, String _apk) {
503            path = _path;
504            apk = _apk;
505        }
506    }
507
508    // Currently known shared libraries.
509    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
510            new ArrayMap<String, SharedLibraryEntry>();
511
512    // All available activities, for your resolving pleasure.
513    final ActivityIntentResolver mActivities =
514            new ActivityIntentResolver();
515
516    // All available receivers, for your resolving pleasure.
517    final ActivityIntentResolver mReceivers =
518            new ActivityIntentResolver();
519
520    // All available services, for your resolving pleasure.
521    final ServiceIntentResolver mServices = new ServiceIntentResolver();
522
523    // All available providers, for your resolving pleasure.
524    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
525
526    // Mapping from provider base names (first directory in content URI codePath)
527    // to the provider information.
528    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
529            new ArrayMap<String, PackageParser.Provider>();
530
531    // Mapping from instrumentation class names to info about them.
532    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
533            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
534
535    // Mapping from permission names to info about them.
536    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
537            new ArrayMap<String, PackageParser.PermissionGroup>();
538
539    // Packages whose data we have transfered into another package, thus
540    // should no longer exist.
541    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
542
543    // Broadcast actions that are only available to the system.
544    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
545
546    /** List of packages waiting for verification. */
547    final SparseArray<PackageVerificationState> mPendingVerification
548            = new SparseArray<PackageVerificationState>();
549
550    /** Set of packages associated with each app op permission. */
551    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
552
553    final PackageInstallerService mInstallerService;
554
555    private final PackageDexOptimizer mPackageDexOptimizer;
556
557    private AtomicInteger mNextMoveId = new AtomicInteger();
558    private final MoveCallbacks mMoveCallbacks;
559
560    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
561
562    // Cache of users who need badging.
563    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
564
565    /** Token for keys in mPendingVerification. */
566    private int mPendingVerificationToken = 0;
567
568    volatile boolean mSystemReady;
569    volatile boolean mSafeMode;
570    volatile boolean mHasSystemUidErrors;
571
572    ApplicationInfo mAndroidApplication;
573    final ActivityInfo mResolveActivity = new ActivityInfo();
574    final ResolveInfo mResolveInfo = new ResolveInfo();
575    ComponentName mResolveComponentName;
576    PackageParser.Package mPlatformPackage;
577    ComponentName mCustomResolverComponentName;
578
579    boolean mResolverReplaced = false;
580
581    private final ComponentName mIntentFilterVerifierComponent;
582    private int mIntentFilterVerificationToken = 0;
583
584    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
585            = new SparseArray<IntentFilterVerificationState>();
586
587    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
588            new DefaultPermissionGrantPolicy(this);
589
590    private static class IFVerificationParams {
591        PackageParser.Package pkg;
592        boolean replacing;
593        int userId;
594        int verifierUid;
595
596        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
597                int _userId, int _verifierUid) {
598            pkg = _pkg;
599            replacing = _replacing;
600            userId = _userId;
601            replacing = _replacing;
602            verifierUid = _verifierUid;
603        }
604    }
605
606    private interface IntentFilterVerifier<T extends IntentFilter> {
607        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
608                                               T filter, String packageName);
609        void startVerifications(int userId);
610        void receiveVerificationResponse(int verificationId);
611    }
612
613    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
614        private Context mContext;
615        private ComponentName mIntentFilterVerifierComponent;
616        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
617
618        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
619            mContext = context;
620            mIntentFilterVerifierComponent = verifierComponent;
621        }
622
623        private String getDefaultScheme() {
624            return IntentFilter.SCHEME_HTTPS;
625        }
626
627        @Override
628        public void startVerifications(int userId) {
629            // Launch verifications requests
630            int count = mCurrentIntentFilterVerifications.size();
631            for (int n=0; n<count; n++) {
632                int verificationId = mCurrentIntentFilterVerifications.get(n);
633                final IntentFilterVerificationState ivs =
634                        mIntentFilterVerificationStates.get(verificationId);
635
636                String packageName = ivs.getPackageName();
637
638                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
639                final int filterCount = filters.size();
640                ArraySet<String> domainsSet = new ArraySet<>();
641                for (int m=0; m<filterCount; m++) {
642                    PackageParser.ActivityIntentInfo filter = filters.get(m);
643                    domainsSet.addAll(filter.getHostsList());
644                }
645                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
646                synchronized (mPackages) {
647                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
648                            packageName, domainsList) != null) {
649                        scheduleWriteSettingsLocked();
650                    }
651                }
652                sendVerificationRequest(userId, verificationId, ivs);
653            }
654            mCurrentIntentFilterVerifications.clear();
655        }
656
657        private void sendVerificationRequest(int userId, int verificationId,
658                IntentFilterVerificationState ivs) {
659
660            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
661            verificationIntent.putExtra(
662                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
663                    verificationId);
664            verificationIntent.putExtra(
665                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
666                    getDefaultScheme());
667            verificationIntent.putExtra(
668                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
669                    ivs.getHostsString());
670            verificationIntent.putExtra(
671                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
672                    ivs.getPackageName());
673            verificationIntent.setComponent(mIntentFilterVerifierComponent);
674            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
675
676            UserHandle user = new UserHandle(userId);
677            mContext.sendBroadcastAsUser(verificationIntent, user);
678            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
679                    "Sending IntentFilter verification broadcast");
680        }
681
682        public void receiveVerificationResponse(int verificationId) {
683            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
684
685            final boolean verified = ivs.isVerified();
686
687            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
688            final int count = filters.size();
689            if (DEBUG_DOMAIN_VERIFICATION) {
690                Slog.i(TAG, "Received verification response " + verificationId
691                        + " for " + count + " filters, verified=" + verified);
692            }
693            for (int n=0; n<count; n++) {
694                PackageParser.ActivityIntentInfo filter = filters.get(n);
695                filter.setVerified(verified);
696
697                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
698                        + " verified with result:" + verified + " and hosts:"
699                        + ivs.getHostsString());
700            }
701
702            mIntentFilterVerificationStates.remove(verificationId);
703
704            final String packageName = ivs.getPackageName();
705            IntentFilterVerificationInfo ivi = null;
706
707            synchronized (mPackages) {
708                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
709            }
710            if (ivi == null) {
711                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
712                        + verificationId + " packageName:" + packageName);
713                return;
714            }
715            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
716                    "Updating IntentFilterVerificationInfo for package " + packageName
717                            +" verificationId:" + verificationId);
718
719            synchronized (mPackages) {
720                if (verified) {
721                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
722                } else {
723                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
724                }
725                scheduleWriteSettingsLocked();
726
727                final int userId = ivs.getUserId();
728                if (userId != UserHandle.USER_ALL) {
729                    final int userStatus =
730                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
731
732                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
733                    boolean needUpdate = false;
734
735                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
736                    // already been set by the User thru the Disambiguation dialog
737                    switch (userStatus) {
738                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
739                            if (verified) {
740                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
741                            } else {
742                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
743                            }
744                            needUpdate = true;
745                            break;
746
747                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
748                            if (verified) {
749                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
750                                needUpdate = true;
751                            }
752                            break;
753
754                        default:
755                            // Nothing to do
756                    }
757
758                    if (needUpdate) {
759                        mSettings.updateIntentFilterVerificationStatusLPw(
760                                packageName, updatedStatus, userId);
761                        scheduleWritePackageRestrictionsLocked(userId);
762                    }
763                }
764            }
765        }
766
767        @Override
768        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
769                    ActivityIntentInfo filter, String packageName) {
770            if (!hasValidDomains(filter)) {
771                return false;
772            }
773            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
774            if (ivs == null) {
775                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
776                        packageName);
777            }
778            if (DEBUG_DOMAIN_VERIFICATION) {
779                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
780            }
781            ivs.addFilter(filter);
782            return true;
783        }
784
785        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
786                int userId, int verificationId, String packageName) {
787            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
788                    verifierUid, userId, packageName);
789            ivs.setPendingState();
790            synchronized (mPackages) {
791                mIntentFilterVerificationStates.append(verificationId, ivs);
792                mCurrentIntentFilterVerifications.add(verificationId);
793            }
794            return ivs;
795        }
796    }
797
798    private static boolean hasValidDomains(ActivityIntentInfo filter) {
799        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
800                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
801        if (!hasHTTPorHTTPS) {
802            return false;
803        }
804        return true;
805    }
806
807    private IntentFilterVerifier mIntentFilterVerifier;
808
809    // Set of pending broadcasts for aggregating enable/disable of components.
810    static class PendingPackageBroadcasts {
811        // for each user id, a map of <package name -> components within that package>
812        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
813
814        public PendingPackageBroadcasts() {
815            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
816        }
817
818        public ArrayList<String> get(int userId, String packageName) {
819            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
820            return packages.get(packageName);
821        }
822
823        public void put(int userId, String packageName, ArrayList<String> components) {
824            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
825            packages.put(packageName, components);
826        }
827
828        public void remove(int userId, String packageName) {
829            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
830            if (packages != null) {
831                packages.remove(packageName);
832            }
833        }
834
835        public void remove(int userId) {
836            mUidMap.remove(userId);
837        }
838
839        public int userIdCount() {
840            return mUidMap.size();
841        }
842
843        public int userIdAt(int n) {
844            return mUidMap.keyAt(n);
845        }
846
847        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
848            return mUidMap.get(userId);
849        }
850
851        public int size() {
852            // total number of pending broadcast entries across all userIds
853            int num = 0;
854            for (int i = 0; i< mUidMap.size(); i++) {
855                num += mUidMap.valueAt(i).size();
856            }
857            return num;
858        }
859
860        public void clear() {
861            mUidMap.clear();
862        }
863
864        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
865            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
866            if (map == null) {
867                map = new ArrayMap<String, ArrayList<String>>();
868                mUidMap.put(userId, map);
869            }
870            return map;
871        }
872    }
873    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
874
875    // Service Connection to remote media container service to copy
876    // package uri's from external media onto secure containers
877    // or internal storage.
878    private IMediaContainerService mContainerService = null;
879
880    static final int SEND_PENDING_BROADCAST = 1;
881    static final int MCS_BOUND = 3;
882    static final int END_COPY = 4;
883    static final int INIT_COPY = 5;
884    static final int MCS_UNBIND = 6;
885    static final int START_CLEANING_PACKAGE = 7;
886    static final int FIND_INSTALL_LOC = 8;
887    static final int POST_INSTALL = 9;
888    static final int MCS_RECONNECT = 10;
889    static final int MCS_GIVE_UP = 11;
890    static final int UPDATED_MEDIA_STATUS = 12;
891    static final int WRITE_SETTINGS = 13;
892    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
893    static final int PACKAGE_VERIFIED = 15;
894    static final int CHECK_PENDING_VERIFICATION = 16;
895    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
896    static final int INTENT_FILTER_VERIFIED = 18;
897
898    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
899
900    // Delay time in millisecs
901    static final int BROADCAST_DELAY = 10 * 1000;
902
903    static UserManagerService sUserManager;
904
905    // Stores a list of users whose package restrictions file needs to be updated
906    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
907
908    final private DefaultContainerConnection mDefContainerConn =
909            new DefaultContainerConnection();
910    class DefaultContainerConnection implements ServiceConnection {
911        public void onServiceConnected(ComponentName name, IBinder service) {
912            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
913            IMediaContainerService imcs =
914                IMediaContainerService.Stub.asInterface(service);
915            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
916        }
917
918        public void onServiceDisconnected(ComponentName name) {
919            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
920        }
921    }
922
923    // Recordkeeping of restore-after-install operations that are currently in flight
924    // between the Package Manager and the Backup Manager
925    class PostInstallData {
926        public InstallArgs args;
927        public PackageInstalledInfo res;
928
929        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
930            args = _a;
931            res = _r;
932        }
933    }
934
935    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
936    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
937
938    // XML tags for backup/restore of various bits of state
939    private static final String TAG_PREFERRED_BACKUP = "pa";
940    private static final String TAG_DEFAULT_APPS = "da";
941    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
942
943    final String mRequiredVerifierPackage;
944    final String mRequiredInstallerPackage;
945
946    private final PackageUsage mPackageUsage = new PackageUsage();
947
948    private class PackageUsage {
949        private static final int WRITE_INTERVAL
950            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
951
952        private final Object mFileLock = new Object();
953        private final AtomicLong mLastWritten = new AtomicLong(0);
954        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
955
956        private boolean mIsHistoricalPackageUsageAvailable = true;
957
958        boolean isHistoricalPackageUsageAvailable() {
959            return mIsHistoricalPackageUsageAvailable;
960        }
961
962        void write(boolean force) {
963            if (force) {
964                writeInternal();
965                return;
966            }
967            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
968                && !DEBUG_DEXOPT) {
969                return;
970            }
971            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
972                new Thread("PackageUsage_DiskWriter") {
973                    @Override
974                    public void run() {
975                        try {
976                            writeInternal();
977                        } finally {
978                            mBackgroundWriteRunning.set(false);
979                        }
980                    }
981                }.start();
982            }
983        }
984
985        private void writeInternal() {
986            synchronized (mPackages) {
987                synchronized (mFileLock) {
988                    AtomicFile file = getFile();
989                    FileOutputStream f = null;
990                    try {
991                        f = file.startWrite();
992                        BufferedOutputStream out = new BufferedOutputStream(f);
993                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
994                        StringBuilder sb = new StringBuilder();
995                        for (PackageParser.Package pkg : mPackages.values()) {
996                            if (pkg.mLastPackageUsageTimeInMills == 0) {
997                                continue;
998                            }
999                            sb.setLength(0);
1000                            sb.append(pkg.packageName);
1001                            sb.append(' ');
1002                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1003                            sb.append('\n');
1004                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1005                        }
1006                        out.flush();
1007                        file.finishWrite(f);
1008                    } catch (IOException e) {
1009                        if (f != null) {
1010                            file.failWrite(f);
1011                        }
1012                        Log.e(TAG, "Failed to write package usage times", e);
1013                    }
1014                }
1015            }
1016            mLastWritten.set(SystemClock.elapsedRealtime());
1017        }
1018
1019        void readLP() {
1020            synchronized (mFileLock) {
1021                AtomicFile file = getFile();
1022                BufferedInputStream in = null;
1023                try {
1024                    in = new BufferedInputStream(file.openRead());
1025                    StringBuffer sb = new StringBuffer();
1026                    while (true) {
1027                        String packageName = readToken(in, sb, ' ');
1028                        if (packageName == null) {
1029                            break;
1030                        }
1031                        String timeInMillisString = readToken(in, sb, '\n');
1032                        if (timeInMillisString == null) {
1033                            throw new IOException("Failed to find last usage time for package "
1034                                                  + packageName);
1035                        }
1036                        PackageParser.Package pkg = mPackages.get(packageName);
1037                        if (pkg == null) {
1038                            continue;
1039                        }
1040                        long timeInMillis;
1041                        try {
1042                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1043                        } catch (NumberFormatException e) {
1044                            throw new IOException("Failed to parse " + timeInMillisString
1045                                                  + " as a long.", e);
1046                        }
1047                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1048                    }
1049                } catch (FileNotFoundException expected) {
1050                    mIsHistoricalPackageUsageAvailable = false;
1051                } catch (IOException e) {
1052                    Log.w(TAG, "Failed to read package usage times", e);
1053                } finally {
1054                    IoUtils.closeQuietly(in);
1055                }
1056            }
1057            mLastWritten.set(SystemClock.elapsedRealtime());
1058        }
1059
1060        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1061                throws IOException {
1062            sb.setLength(0);
1063            while (true) {
1064                int ch = in.read();
1065                if (ch == -1) {
1066                    if (sb.length() == 0) {
1067                        return null;
1068                    }
1069                    throw new IOException("Unexpected EOF");
1070                }
1071                if (ch == endOfToken) {
1072                    return sb.toString();
1073                }
1074                sb.append((char)ch);
1075            }
1076        }
1077
1078        private AtomicFile getFile() {
1079            File dataDir = Environment.getDataDirectory();
1080            File systemDir = new File(dataDir, "system");
1081            File fname = new File(systemDir, "package-usage.list");
1082            return new AtomicFile(fname);
1083        }
1084    }
1085
1086    class PackageHandler extends Handler {
1087        private boolean mBound = false;
1088        final ArrayList<HandlerParams> mPendingInstalls =
1089            new ArrayList<HandlerParams>();
1090
1091        private boolean connectToService() {
1092            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1093                    " DefaultContainerService");
1094            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1095            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1096            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1097                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1098                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1099                mBound = true;
1100                return true;
1101            }
1102            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1103            return false;
1104        }
1105
1106        private void disconnectService() {
1107            mContainerService = null;
1108            mBound = false;
1109            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1110            mContext.unbindService(mDefContainerConn);
1111            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1112        }
1113
1114        PackageHandler(Looper looper) {
1115            super(looper);
1116        }
1117
1118        public void handleMessage(Message msg) {
1119            try {
1120                doHandleMessage(msg);
1121            } finally {
1122                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1123            }
1124        }
1125
1126        void doHandleMessage(Message msg) {
1127            switch (msg.what) {
1128                case INIT_COPY: {
1129                    HandlerParams params = (HandlerParams) msg.obj;
1130                    int idx = mPendingInstalls.size();
1131                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1132                    // If a bind was already initiated we dont really
1133                    // need to do anything. The pending install
1134                    // will be processed later on.
1135                    if (!mBound) {
1136                        // If this is the only one pending we might
1137                        // have to bind to the service again.
1138                        if (!connectToService()) {
1139                            Slog.e(TAG, "Failed to bind to media container service");
1140                            params.serviceError();
1141                            return;
1142                        } else {
1143                            // Once we bind to the service, the first
1144                            // pending request will be processed.
1145                            mPendingInstalls.add(idx, params);
1146                        }
1147                    } else {
1148                        mPendingInstalls.add(idx, params);
1149                        // Already bound to the service. Just make
1150                        // sure we trigger off processing the first request.
1151                        if (idx == 0) {
1152                            mHandler.sendEmptyMessage(MCS_BOUND);
1153                        }
1154                    }
1155                    break;
1156                }
1157                case MCS_BOUND: {
1158                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1159                    if (msg.obj != null) {
1160                        mContainerService = (IMediaContainerService) msg.obj;
1161                    }
1162                    if (mContainerService == null) {
1163                        if (!mBound) {
1164                            // Something seriously wrong since we are not bound and we are not
1165                            // waiting for connection. Bail out.
1166                            Slog.e(TAG, "Cannot bind to media container service");
1167                            for (HandlerParams params : mPendingInstalls) {
1168                                // Indicate service bind error
1169                                params.serviceError();
1170                            }
1171                            mPendingInstalls.clear();
1172                        } else {
1173                            Slog.w(TAG, "Waiting to connect to media container service");
1174                        }
1175                    } else if (mPendingInstalls.size() > 0) {
1176                        HandlerParams params = mPendingInstalls.get(0);
1177                        if (params != null) {
1178                            if (params.startCopy()) {
1179                                // We are done...  look for more work or to
1180                                // go idle.
1181                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1182                                        "Checking for more work or unbind...");
1183                                // Delete pending install
1184                                if (mPendingInstalls.size() > 0) {
1185                                    mPendingInstalls.remove(0);
1186                                }
1187                                if (mPendingInstalls.size() == 0) {
1188                                    if (mBound) {
1189                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1190                                                "Posting delayed MCS_UNBIND");
1191                                        removeMessages(MCS_UNBIND);
1192                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1193                                        // Unbind after a little delay, to avoid
1194                                        // continual thrashing.
1195                                        sendMessageDelayed(ubmsg, 10000);
1196                                    }
1197                                } else {
1198                                    // There are more pending requests in queue.
1199                                    // Just post MCS_BOUND message to trigger processing
1200                                    // of next pending install.
1201                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1202                                            "Posting MCS_BOUND for next work");
1203                                    mHandler.sendEmptyMessage(MCS_BOUND);
1204                                }
1205                            }
1206                        }
1207                    } else {
1208                        // Should never happen ideally.
1209                        Slog.w(TAG, "Empty queue");
1210                    }
1211                    break;
1212                }
1213                case MCS_RECONNECT: {
1214                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1215                    if (mPendingInstalls.size() > 0) {
1216                        if (mBound) {
1217                            disconnectService();
1218                        }
1219                        if (!connectToService()) {
1220                            Slog.e(TAG, "Failed to bind to media container service");
1221                            for (HandlerParams params : mPendingInstalls) {
1222                                // Indicate service bind error
1223                                params.serviceError();
1224                            }
1225                            mPendingInstalls.clear();
1226                        }
1227                    }
1228                    break;
1229                }
1230                case MCS_UNBIND: {
1231                    // If there is no actual work left, then time to unbind.
1232                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1233
1234                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1235                        if (mBound) {
1236                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1237
1238                            disconnectService();
1239                        }
1240                    } else if (mPendingInstalls.size() > 0) {
1241                        // There are more pending requests in queue.
1242                        // Just post MCS_BOUND message to trigger processing
1243                        // of next pending install.
1244                        mHandler.sendEmptyMessage(MCS_BOUND);
1245                    }
1246
1247                    break;
1248                }
1249                case MCS_GIVE_UP: {
1250                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1251                    mPendingInstalls.remove(0);
1252                    break;
1253                }
1254                case SEND_PENDING_BROADCAST: {
1255                    String packages[];
1256                    ArrayList<String> components[];
1257                    int size = 0;
1258                    int uids[];
1259                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1260                    synchronized (mPackages) {
1261                        if (mPendingBroadcasts == null) {
1262                            return;
1263                        }
1264                        size = mPendingBroadcasts.size();
1265                        if (size <= 0) {
1266                            // Nothing to be done. Just return
1267                            return;
1268                        }
1269                        packages = new String[size];
1270                        components = new ArrayList[size];
1271                        uids = new int[size];
1272                        int i = 0;  // filling out the above arrays
1273
1274                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1275                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1276                            Iterator<Map.Entry<String, ArrayList<String>>> it
1277                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1278                                            .entrySet().iterator();
1279                            while (it.hasNext() && i < size) {
1280                                Map.Entry<String, ArrayList<String>> ent = it.next();
1281                                packages[i] = ent.getKey();
1282                                components[i] = ent.getValue();
1283                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1284                                uids[i] = (ps != null)
1285                                        ? UserHandle.getUid(packageUserId, ps.appId)
1286                                        : -1;
1287                                i++;
1288                            }
1289                        }
1290                        size = i;
1291                        mPendingBroadcasts.clear();
1292                    }
1293                    // Send broadcasts
1294                    for (int i = 0; i < size; i++) {
1295                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1296                    }
1297                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1298                    break;
1299                }
1300                case START_CLEANING_PACKAGE: {
1301                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1302                    final String packageName = (String)msg.obj;
1303                    final int userId = msg.arg1;
1304                    final boolean andCode = msg.arg2 != 0;
1305                    synchronized (mPackages) {
1306                        if (userId == UserHandle.USER_ALL) {
1307                            int[] users = sUserManager.getUserIds();
1308                            for (int user : users) {
1309                                mSettings.addPackageToCleanLPw(
1310                                        new PackageCleanItem(user, packageName, andCode));
1311                            }
1312                        } else {
1313                            mSettings.addPackageToCleanLPw(
1314                                    new PackageCleanItem(userId, packageName, andCode));
1315                        }
1316                    }
1317                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1318                    startCleaningPackages();
1319                } break;
1320                case POST_INSTALL: {
1321                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1322                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1323                    mRunningInstalls.delete(msg.arg1);
1324                    boolean deleteOld = false;
1325
1326                    if (data != null) {
1327                        InstallArgs args = data.args;
1328                        PackageInstalledInfo res = data.res;
1329
1330                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1331                            final String packageName = res.pkg.applicationInfo.packageName;
1332                            res.removedInfo.sendBroadcast(false, true, false);
1333                            Bundle extras = new Bundle(1);
1334                            extras.putInt(Intent.EXTRA_UID, res.uid);
1335
1336                            // Now that we successfully installed the package, grant runtime
1337                            // permissions if requested before broadcasting the install.
1338                            if ((args.installFlags
1339                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1340                                grantRequestedRuntimePermissions(res.pkg,
1341                                        args.user.getIdentifier());
1342                            }
1343
1344                            // Determine the set of users who are adding this
1345                            // package for the first time vs. those who are seeing
1346                            // an update.
1347                            int[] firstUsers;
1348                            int[] updateUsers = new int[0];
1349                            if (res.origUsers == null || res.origUsers.length == 0) {
1350                                firstUsers = res.newUsers;
1351                            } else {
1352                                firstUsers = new int[0];
1353                                for (int i=0; i<res.newUsers.length; i++) {
1354                                    int user = res.newUsers[i];
1355                                    boolean isNew = true;
1356                                    for (int j=0; j<res.origUsers.length; j++) {
1357                                        if (res.origUsers[j] == user) {
1358                                            isNew = false;
1359                                            break;
1360                                        }
1361                                    }
1362                                    if (isNew) {
1363                                        int[] newFirst = new int[firstUsers.length+1];
1364                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1365                                                firstUsers.length);
1366                                        newFirst[firstUsers.length] = user;
1367                                        firstUsers = newFirst;
1368                                    } else {
1369                                        int[] newUpdate = new int[updateUsers.length+1];
1370                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1371                                                updateUsers.length);
1372                                        newUpdate[updateUsers.length] = user;
1373                                        updateUsers = newUpdate;
1374                                    }
1375                                }
1376                            }
1377                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1378                                    packageName, extras, null, null, firstUsers);
1379                            final boolean update = res.removedInfo.removedPackage != null;
1380                            if (update) {
1381                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1382                            }
1383                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1384                                    packageName, extras, null, null, updateUsers);
1385                            if (update) {
1386                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1387                                        packageName, extras, null, null, updateUsers);
1388                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1389                                        null, null, packageName, null, updateUsers);
1390
1391                                // treat asec-hosted packages like removable media on upgrade
1392                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1393                                    if (DEBUG_INSTALL) {
1394                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1395                                                + " is ASEC-hosted -> AVAILABLE");
1396                                    }
1397                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1398                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1399                                    pkgList.add(packageName);
1400                                    sendResourcesChangedBroadcast(true, true,
1401                                            pkgList,uidArray, null);
1402                                }
1403                            }
1404                            if (res.removedInfo.args != null) {
1405                                // Remove the replaced package's older resources safely now
1406                                deleteOld = true;
1407                            }
1408
1409                            // If this app is a browser and it's newly-installed for some
1410                            // users, clear any default-browser state in those users
1411                            if (firstUsers.length > 0) {
1412                                // the app's nature doesn't depend on the user, so we can just
1413                                // check its browser nature in any user and generalize.
1414                                if (packageIsBrowser(packageName, firstUsers[0])) {
1415                                    synchronized (mPackages) {
1416                                        for (int userId : firstUsers) {
1417                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1418                                        }
1419                                    }
1420                                }
1421                            }
1422                            // Log current value of "unknown sources" setting
1423                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1424                                getUnknownSourcesSettings());
1425                        }
1426                        // Force a gc to clear up things
1427                        Runtime.getRuntime().gc();
1428                        // We delete after a gc for applications  on sdcard.
1429                        if (deleteOld) {
1430                            synchronized (mInstallLock) {
1431                                res.removedInfo.args.doPostDeleteLI(true);
1432                            }
1433                        }
1434                        if (args.observer != null) {
1435                            try {
1436                                Bundle extras = extrasForInstallResult(res);
1437                                args.observer.onPackageInstalled(res.name, res.returnCode,
1438                                        res.returnMsg, extras);
1439                            } catch (RemoteException e) {
1440                                Slog.i(TAG, "Observer no longer exists.");
1441                            }
1442                        }
1443                    } else {
1444                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1445                    }
1446                } break;
1447                case UPDATED_MEDIA_STATUS: {
1448                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1449                    boolean reportStatus = msg.arg1 == 1;
1450                    boolean doGc = msg.arg2 == 1;
1451                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1452                    if (doGc) {
1453                        // Force a gc to clear up stale containers.
1454                        Runtime.getRuntime().gc();
1455                    }
1456                    if (msg.obj != null) {
1457                        @SuppressWarnings("unchecked")
1458                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1459                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1460                        // Unload containers
1461                        unloadAllContainers(args);
1462                    }
1463                    if (reportStatus) {
1464                        try {
1465                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1466                            PackageHelper.getMountService().finishMediaUpdate();
1467                        } catch (RemoteException e) {
1468                            Log.e(TAG, "MountService not running?");
1469                        }
1470                    }
1471                } break;
1472                case WRITE_SETTINGS: {
1473                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1474                    synchronized (mPackages) {
1475                        removeMessages(WRITE_SETTINGS);
1476                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1477                        mSettings.writeLPr();
1478                        mDirtyUsers.clear();
1479                    }
1480                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1481                } break;
1482                case WRITE_PACKAGE_RESTRICTIONS: {
1483                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1484                    synchronized (mPackages) {
1485                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1486                        for (int userId : mDirtyUsers) {
1487                            mSettings.writePackageRestrictionsLPr(userId);
1488                        }
1489                        mDirtyUsers.clear();
1490                    }
1491                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1492                } break;
1493                case CHECK_PENDING_VERIFICATION: {
1494                    final int verificationId = msg.arg1;
1495                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1496
1497                    if ((state != null) && !state.timeoutExtended()) {
1498                        final InstallArgs args = state.getInstallArgs();
1499                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1500
1501                        Slog.i(TAG, "Verification timed out for " + originUri);
1502                        mPendingVerification.remove(verificationId);
1503
1504                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1505
1506                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1507                            Slog.i(TAG, "Continuing with installation of " + originUri);
1508                            state.setVerifierResponse(Binder.getCallingUid(),
1509                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1510                            broadcastPackageVerified(verificationId, originUri,
1511                                    PackageManager.VERIFICATION_ALLOW,
1512                                    state.getInstallArgs().getUser());
1513                            try {
1514                                ret = args.copyApk(mContainerService, true);
1515                            } catch (RemoteException e) {
1516                                Slog.e(TAG, "Could not contact the ContainerService");
1517                            }
1518                        } else {
1519                            broadcastPackageVerified(verificationId, originUri,
1520                                    PackageManager.VERIFICATION_REJECT,
1521                                    state.getInstallArgs().getUser());
1522                        }
1523
1524                        processPendingInstall(args, ret);
1525                        mHandler.sendEmptyMessage(MCS_UNBIND);
1526                    }
1527                    break;
1528                }
1529                case PACKAGE_VERIFIED: {
1530                    final int verificationId = msg.arg1;
1531
1532                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1533                    if (state == null) {
1534                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1535                        break;
1536                    }
1537
1538                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1539
1540                    state.setVerifierResponse(response.callerUid, response.code);
1541
1542                    if (state.isVerificationComplete()) {
1543                        mPendingVerification.remove(verificationId);
1544
1545                        final InstallArgs args = state.getInstallArgs();
1546                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1547
1548                        int ret;
1549                        if (state.isInstallAllowed()) {
1550                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1551                            broadcastPackageVerified(verificationId, originUri,
1552                                    response.code, state.getInstallArgs().getUser());
1553                            try {
1554                                ret = args.copyApk(mContainerService, true);
1555                            } catch (RemoteException e) {
1556                                Slog.e(TAG, "Could not contact the ContainerService");
1557                            }
1558                        } else {
1559                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1560                        }
1561
1562                        processPendingInstall(args, ret);
1563
1564                        mHandler.sendEmptyMessage(MCS_UNBIND);
1565                    }
1566
1567                    break;
1568                }
1569                case START_INTENT_FILTER_VERIFICATIONS: {
1570                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1571                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1572                            params.replacing, params.pkg);
1573                    break;
1574                }
1575                case INTENT_FILTER_VERIFIED: {
1576                    final int verificationId = msg.arg1;
1577
1578                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1579                            verificationId);
1580                    if (state == null) {
1581                        Slog.w(TAG, "Invalid IntentFilter verification token "
1582                                + verificationId + " received");
1583                        break;
1584                    }
1585
1586                    final int userId = state.getUserId();
1587
1588                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1589                            "Processing IntentFilter verification with token:"
1590                            + verificationId + " and userId:" + userId);
1591
1592                    final IntentFilterVerificationResponse response =
1593                            (IntentFilterVerificationResponse) msg.obj;
1594
1595                    state.setVerifierResponse(response.callerUid, response.code);
1596
1597                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1598                            "IntentFilter verification with token:" + verificationId
1599                            + " and userId:" + userId
1600                            + " is settings verifier response with response code:"
1601                            + response.code);
1602
1603                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1604                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1605                                + response.getFailedDomainsString());
1606                    }
1607
1608                    if (state.isVerificationComplete()) {
1609                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1610                    } else {
1611                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1612                                "IntentFilter verification with token:" + verificationId
1613                                + " was not said to be complete");
1614                    }
1615
1616                    break;
1617                }
1618            }
1619        }
1620    }
1621
1622    private StorageEventListener mStorageListener = new StorageEventListener() {
1623        @Override
1624        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1625            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1626                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1627                    final String volumeUuid = vol.getFsUuid();
1628
1629                    // Clean up any users or apps that were removed or recreated
1630                    // while this volume was missing
1631                    reconcileUsers(volumeUuid);
1632                    reconcileApps(volumeUuid);
1633
1634                    // Clean up any install sessions that expired or were
1635                    // cancelled while this volume was missing
1636                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1637
1638                    loadPrivatePackages(vol);
1639
1640                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1641                    unloadPrivatePackages(vol);
1642                }
1643            }
1644
1645            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1646                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1647                    updateExternalMediaStatus(true, false);
1648                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1649                    updateExternalMediaStatus(false, false);
1650                }
1651            }
1652        }
1653
1654        @Override
1655        public void onVolumeForgotten(String fsUuid) {
1656            // Remove any apps installed on the forgotten volume
1657            synchronized (mPackages) {
1658                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1659                for (PackageSetting ps : packages) {
1660                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1661                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1662                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1663                }
1664
1665                mSettings.writeLPr();
1666            }
1667        }
1668    };
1669
1670    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1671        if (userId >= UserHandle.USER_OWNER) {
1672            grantRequestedRuntimePermissionsForUser(pkg, userId);
1673        } else if (userId == UserHandle.USER_ALL) {
1674            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1675                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1676            }
1677        }
1678
1679        // We could have touched GID membership, so flush out packages.list
1680        synchronized (mPackages) {
1681            mSettings.writePackageListLPr();
1682        }
1683    }
1684
1685    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1686        SettingBase sb = (SettingBase) pkg.mExtras;
1687        if (sb == null) {
1688            return;
1689        }
1690
1691        PermissionsState permissionsState = sb.getPermissionsState();
1692
1693        for (String permission : pkg.requestedPermissions) {
1694            BasePermission bp = mSettings.mPermissions.get(permission);
1695            if (bp != null && bp.isRuntime()) {
1696                permissionsState.grantRuntimePermission(bp, userId);
1697            }
1698        }
1699    }
1700
1701    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1702        Bundle extras = null;
1703        switch (res.returnCode) {
1704            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1705                extras = new Bundle();
1706                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1707                        res.origPermission);
1708                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1709                        res.origPackage);
1710                break;
1711            }
1712            case PackageManager.INSTALL_SUCCEEDED: {
1713                extras = new Bundle();
1714                extras.putBoolean(Intent.EXTRA_REPLACING,
1715                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1716                break;
1717            }
1718        }
1719        return extras;
1720    }
1721
1722    void scheduleWriteSettingsLocked() {
1723        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1724            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1725        }
1726    }
1727
1728    void scheduleWritePackageRestrictionsLocked(int userId) {
1729        if (!sUserManager.exists(userId)) return;
1730        mDirtyUsers.add(userId);
1731        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1732            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1733        }
1734    }
1735
1736    public static PackageManagerService main(Context context, Installer installer,
1737            boolean factoryTest, boolean onlyCore) {
1738        PackageManagerService m = new PackageManagerService(context, installer,
1739                factoryTest, onlyCore);
1740        ServiceManager.addService("package", m);
1741        return m;
1742    }
1743
1744    static String[] splitString(String str, char sep) {
1745        int count = 1;
1746        int i = 0;
1747        while ((i=str.indexOf(sep, i)) >= 0) {
1748            count++;
1749            i++;
1750        }
1751
1752        String[] res = new String[count];
1753        i=0;
1754        count = 0;
1755        int lastI=0;
1756        while ((i=str.indexOf(sep, i)) >= 0) {
1757            res[count] = str.substring(lastI, i);
1758            count++;
1759            i++;
1760            lastI = i;
1761        }
1762        res[count] = str.substring(lastI, str.length());
1763        return res;
1764    }
1765
1766    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1767        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1768                Context.DISPLAY_SERVICE);
1769        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1770    }
1771
1772    public PackageManagerService(Context context, Installer installer,
1773            boolean factoryTest, boolean onlyCore) {
1774        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1775                SystemClock.uptimeMillis());
1776
1777        if (mSdkVersion <= 0) {
1778            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1779        }
1780
1781        mContext = context;
1782        mFactoryTest = factoryTest;
1783        mOnlyCore = onlyCore;
1784        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1785        mMetrics = new DisplayMetrics();
1786        mSettings = new Settings(mPackages);
1787        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1788                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1789        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1790                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1791        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1792                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1793        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1794                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1795        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1796                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1797        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1798                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1799
1800        // TODO: add a property to control this?
1801        long dexOptLRUThresholdInMinutes;
1802        if (mLazyDexOpt) {
1803            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1804        } else {
1805            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1806        }
1807        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1808
1809        String separateProcesses = SystemProperties.get("debug.separate_processes");
1810        if (separateProcesses != null && separateProcesses.length() > 0) {
1811            if ("*".equals(separateProcesses)) {
1812                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1813                mSeparateProcesses = null;
1814                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1815            } else {
1816                mDefParseFlags = 0;
1817                mSeparateProcesses = separateProcesses.split(",");
1818                Slog.w(TAG, "Running with debug.separate_processes: "
1819                        + separateProcesses);
1820            }
1821        } else {
1822            mDefParseFlags = 0;
1823            mSeparateProcesses = null;
1824        }
1825
1826        mInstaller = installer;
1827        mPackageDexOptimizer = new PackageDexOptimizer(this);
1828        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1829
1830        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1831                FgThread.get().getLooper());
1832
1833        getDefaultDisplayMetrics(context, mMetrics);
1834
1835        SystemConfig systemConfig = SystemConfig.getInstance();
1836        mGlobalGids = systemConfig.getGlobalGids();
1837        mSystemPermissions = systemConfig.getSystemPermissions();
1838        mAvailableFeatures = systemConfig.getAvailableFeatures();
1839
1840        synchronized (mInstallLock) {
1841        // writer
1842        synchronized (mPackages) {
1843            mHandlerThread = new ServiceThread(TAG,
1844                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1845            mHandlerThread.start();
1846            mHandler = new PackageHandler(mHandlerThread.getLooper());
1847            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1848
1849            File dataDir = Environment.getDataDirectory();
1850            mAppDataDir = new File(dataDir, "data");
1851            mAppInstallDir = new File(dataDir, "app");
1852            mAppLib32InstallDir = new File(dataDir, "app-lib");
1853            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1854            mUserAppDataDir = new File(dataDir, "user");
1855            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1856
1857            sUserManager = new UserManagerService(context, this,
1858                    mInstallLock, mPackages);
1859
1860            // Propagate permission configuration in to package manager.
1861            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1862                    = systemConfig.getPermissions();
1863            for (int i=0; i<permConfig.size(); i++) {
1864                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1865                BasePermission bp = mSettings.mPermissions.get(perm.name);
1866                if (bp == null) {
1867                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1868                    mSettings.mPermissions.put(perm.name, bp);
1869                }
1870                if (perm.gids != null) {
1871                    bp.setGids(perm.gids, perm.perUser);
1872                }
1873            }
1874
1875            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1876            for (int i=0; i<libConfig.size(); i++) {
1877                mSharedLibraries.put(libConfig.keyAt(i),
1878                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1879            }
1880
1881            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1882
1883            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1884                    mSdkVersion, mOnlyCore);
1885
1886            String customResolverActivity = Resources.getSystem().getString(
1887                    R.string.config_customResolverActivity);
1888            if (TextUtils.isEmpty(customResolverActivity)) {
1889                customResolverActivity = null;
1890            } else {
1891                mCustomResolverComponentName = ComponentName.unflattenFromString(
1892                        customResolverActivity);
1893            }
1894
1895            long startTime = SystemClock.uptimeMillis();
1896
1897            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1898                    startTime);
1899
1900            // Set flag to monitor and not change apk file paths when
1901            // scanning install directories.
1902            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1903
1904            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1905
1906            /**
1907             * Add everything in the in the boot class path to the
1908             * list of process files because dexopt will have been run
1909             * if necessary during zygote startup.
1910             */
1911            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1912            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1913
1914            if (bootClassPath != null) {
1915                String[] bootClassPathElements = splitString(bootClassPath, ':');
1916                for (String element : bootClassPathElements) {
1917                    alreadyDexOpted.add(element);
1918                }
1919            } else {
1920                Slog.w(TAG, "No BOOTCLASSPATH found!");
1921            }
1922
1923            if (systemServerClassPath != null) {
1924                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1925                for (String element : systemServerClassPathElements) {
1926                    alreadyDexOpted.add(element);
1927                }
1928            } else {
1929                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1930            }
1931
1932            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1933            final String[] dexCodeInstructionSets =
1934                    getDexCodeInstructionSets(
1935                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1936
1937            /**
1938             * Ensure all external libraries have had dexopt run on them.
1939             */
1940            if (mSharedLibraries.size() > 0) {
1941                // NOTE: For now, we're compiling these system "shared libraries"
1942                // (and framework jars) into all available architectures. It's possible
1943                // to compile them only when we come across an app that uses them (there's
1944                // already logic for that in scanPackageLI) but that adds some complexity.
1945                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1946                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1947                        final String lib = libEntry.path;
1948                        if (lib == null) {
1949                            continue;
1950                        }
1951
1952                        try {
1953                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1954                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1955                                alreadyDexOpted.add(lib);
1956                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1957                            }
1958                        } catch (FileNotFoundException e) {
1959                            Slog.w(TAG, "Library not found: " + lib);
1960                        } catch (IOException e) {
1961                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1962                                    + e.getMessage());
1963                        }
1964                    }
1965                }
1966            }
1967
1968            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1969
1970            // Gross hack for now: we know this file doesn't contain any
1971            // code, so don't dexopt it to avoid the resulting log spew.
1972            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1973
1974            // Gross hack for now: we know this file is only part of
1975            // the boot class path for art, so don't dexopt it to
1976            // avoid the resulting log spew.
1977            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1978
1979            /**
1980             * There are a number of commands implemented in Java, which
1981             * we currently need to do the dexopt on so that they can be
1982             * run from a non-root shell.
1983             */
1984            String[] frameworkFiles = frameworkDir.list();
1985            if (frameworkFiles != null) {
1986                // TODO: We could compile these only for the most preferred ABI. We should
1987                // first double check that the dex files for these commands are not referenced
1988                // by other system apps.
1989                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1990                    for (int i=0; i<frameworkFiles.length; i++) {
1991                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1992                        String path = libPath.getPath();
1993                        // Skip the file if we already did it.
1994                        if (alreadyDexOpted.contains(path)) {
1995                            continue;
1996                        }
1997                        // Skip the file if it is not a type we want to dexopt.
1998                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1999                            continue;
2000                        }
2001                        try {
2002                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2003                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2004                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2005                            }
2006                        } catch (FileNotFoundException e) {
2007                            Slog.w(TAG, "Jar not found: " + path);
2008                        } catch (IOException e) {
2009                            Slog.w(TAG, "Exception reading jar: " + path, e);
2010                        }
2011                    }
2012                }
2013            }
2014
2015            // Collect vendor overlay packages.
2016            // (Do this before scanning any apps.)
2017            // For security and version matching reason, only consider
2018            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2019            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2020            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2021                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2022
2023            // Find base frameworks (resource packages without code).
2024            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2025                    | PackageParser.PARSE_IS_SYSTEM_DIR
2026                    | PackageParser.PARSE_IS_PRIVILEGED,
2027                    scanFlags | SCAN_NO_DEX, 0);
2028
2029            // Collected privileged system packages.
2030            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2031            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2032                    | PackageParser.PARSE_IS_SYSTEM_DIR
2033                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2034
2035            // Collect ordinary system packages.
2036            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2037            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2038                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2039
2040            // Collect all vendor packages.
2041            File vendorAppDir = new File("/vendor/app");
2042            try {
2043                vendorAppDir = vendorAppDir.getCanonicalFile();
2044            } catch (IOException e) {
2045                // failed to look up canonical path, continue with original one
2046            }
2047            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2048                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2049
2050            // Collect all OEM packages.
2051            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2052            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2053                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2054
2055            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2056            mInstaller.moveFiles();
2057
2058            // Prune any system packages that no longer exist.
2059            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2060            if (!mOnlyCore) {
2061                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2062                while (psit.hasNext()) {
2063                    PackageSetting ps = psit.next();
2064
2065                    /*
2066                     * If this is not a system app, it can't be a
2067                     * disable system app.
2068                     */
2069                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2070                        continue;
2071                    }
2072
2073                    /*
2074                     * If the package is scanned, it's not erased.
2075                     */
2076                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2077                    if (scannedPkg != null) {
2078                        /*
2079                         * If the system app is both scanned and in the
2080                         * disabled packages list, then it must have been
2081                         * added via OTA. Remove it from the currently
2082                         * scanned package so the previously user-installed
2083                         * application can be scanned.
2084                         */
2085                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2086                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2087                                    + ps.name + "; removing system app.  Last known codePath="
2088                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2089                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2090                                    + scannedPkg.mVersionCode);
2091                            removePackageLI(ps, true);
2092                            mExpectingBetter.put(ps.name, ps.codePath);
2093                        }
2094
2095                        continue;
2096                    }
2097
2098                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2099                        psit.remove();
2100                        logCriticalInfo(Log.WARN, "System package " + ps.name
2101                                + " no longer exists; wiping its data");
2102                        removeDataDirsLI(null, ps.name);
2103                    } else {
2104                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2105                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2106                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2107                        }
2108                    }
2109                }
2110            }
2111
2112            //look for any incomplete package installations
2113            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2114            //clean up list
2115            for(int i = 0; i < deletePkgsList.size(); i++) {
2116                //clean up here
2117                cleanupInstallFailedPackage(deletePkgsList.get(i));
2118            }
2119            //delete tmp files
2120            deleteTempPackageFiles();
2121
2122            // Remove any shared userIDs that have no associated packages
2123            mSettings.pruneSharedUsersLPw();
2124
2125            if (!mOnlyCore) {
2126                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2127                        SystemClock.uptimeMillis());
2128                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2129
2130                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2131                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2132
2133                /**
2134                 * Remove disable package settings for any updated system
2135                 * apps that were removed via an OTA. If they're not a
2136                 * previously-updated app, remove them completely.
2137                 * Otherwise, just revoke their system-level permissions.
2138                 */
2139                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2140                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2141                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2142
2143                    String msg;
2144                    if (deletedPkg == null) {
2145                        msg = "Updated system package " + deletedAppName
2146                                + " no longer exists; wiping its data";
2147                        removeDataDirsLI(null, deletedAppName);
2148                    } else {
2149                        msg = "Updated system app + " + deletedAppName
2150                                + " no longer present; removing system privileges for "
2151                                + deletedAppName;
2152
2153                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2154
2155                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2156                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2157                    }
2158                    logCriticalInfo(Log.WARN, msg);
2159                }
2160
2161                /**
2162                 * Make sure all system apps that we expected to appear on
2163                 * the userdata partition actually showed up. If they never
2164                 * appeared, crawl back and revive the system version.
2165                 */
2166                for (int i = 0; i < mExpectingBetter.size(); i++) {
2167                    final String packageName = mExpectingBetter.keyAt(i);
2168                    if (!mPackages.containsKey(packageName)) {
2169                        final File scanFile = mExpectingBetter.valueAt(i);
2170
2171                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2172                                + " but never showed up; reverting to system");
2173
2174                        final int reparseFlags;
2175                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2176                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2177                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2178                                    | PackageParser.PARSE_IS_PRIVILEGED;
2179                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2180                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2181                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2182                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2183                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2184                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2185                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2186                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2187                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2188                        } else {
2189                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2190                            continue;
2191                        }
2192
2193                        mSettings.enableSystemPackageLPw(packageName);
2194
2195                        try {
2196                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2197                        } catch (PackageManagerException e) {
2198                            Slog.e(TAG, "Failed to parse original system package: "
2199                                    + e.getMessage());
2200                        }
2201                    }
2202                }
2203            }
2204            mExpectingBetter.clear();
2205
2206            // Now that we know all of the shared libraries, update all clients to have
2207            // the correct library paths.
2208            updateAllSharedLibrariesLPw();
2209
2210            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2211                // NOTE: We ignore potential failures here during a system scan (like
2212                // the rest of the commands above) because there's precious little we
2213                // can do about it. A settings error is reported, though.
2214                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2215                        false /* force dexopt */, false /* defer dexopt */);
2216            }
2217
2218            // Now that we know all the packages we are keeping,
2219            // read and update their last usage times.
2220            mPackageUsage.readLP();
2221
2222            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2223                    SystemClock.uptimeMillis());
2224            Slog.i(TAG, "Time to scan packages: "
2225                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2226                    + " seconds");
2227
2228            // If the platform SDK has changed since the last time we booted,
2229            // we need to re-grant app permission to catch any new ones that
2230            // appear.  This is really a hack, and means that apps can in some
2231            // cases get permissions that the user didn't initially explicitly
2232            // allow...  it would be nice to have some better way to handle
2233            // this situation.
2234            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2235                    != mSdkVersion;
2236            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2237                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2238                    + "; regranting permissions for internal storage");
2239            mSettings.mInternalSdkPlatform = mSdkVersion;
2240
2241            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2242                    | (regrantPermissions
2243                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2244                            : 0));
2245
2246            // If this is the first boot, and it is a normal boot, then
2247            // we need to initialize the default preferred apps.
2248            if (!mRestoredSettings && !onlyCore) {
2249                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2250                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2251                primeDomainVerificationsLPw(UserHandle.USER_OWNER);
2252            }
2253
2254            // If this is first boot after an OTA, and a normal boot, then
2255            // we need to clear code cache directories.
2256            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2257            if (mIsUpgrade && !onlyCore) {
2258                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2259                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2260                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2261                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2262                }
2263                mSettings.mFingerprint = Build.FINGERPRINT;
2264            }
2265
2266            checkDefaultBrowser();
2267
2268            // All the changes are done during package scanning.
2269            mSettings.updateInternalDatabaseVersion();
2270
2271            // can downgrade to reader
2272            mSettings.writeLPr();
2273
2274            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2275                    SystemClock.uptimeMillis());
2276
2277            mRequiredVerifierPackage = getRequiredVerifierLPr();
2278            mRequiredInstallerPackage = getRequiredInstallerLPr();
2279
2280            mInstallerService = new PackageInstallerService(context, this);
2281
2282            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2283            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2284                    mIntentFilterVerifierComponent);
2285
2286        } // synchronized (mPackages)
2287        } // synchronized (mInstallLock)
2288
2289        // Now after opening every single application zip, make sure they
2290        // are all flushed.  Not really needed, but keeps things nice and
2291        // tidy.
2292        Runtime.getRuntime().gc();
2293
2294        // Expose private service for system components to use.
2295        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2296    }
2297
2298    @Override
2299    public boolean isFirstBoot() {
2300        return !mRestoredSettings;
2301    }
2302
2303    @Override
2304    public boolean isOnlyCoreApps() {
2305        return mOnlyCore;
2306    }
2307
2308    @Override
2309    public boolean isUpgrade() {
2310        return mIsUpgrade;
2311    }
2312
2313    private String getRequiredVerifierLPr() {
2314        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2315        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2316                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2317
2318        String requiredVerifier = null;
2319
2320        final int N = receivers.size();
2321        for (int i = 0; i < N; i++) {
2322            final ResolveInfo info = receivers.get(i);
2323
2324            if (info.activityInfo == null) {
2325                continue;
2326            }
2327
2328            final String packageName = info.activityInfo.packageName;
2329
2330            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2331                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2332                continue;
2333            }
2334
2335            if (requiredVerifier != null) {
2336                throw new RuntimeException("There can be only one required verifier");
2337            }
2338
2339            requiredVerifier = packageName;
2340        }
2341
2342        return requiredVerifier;
2343    }
2344
2345    private String getRequiredInstallerLPr() {
2346        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2347        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2348        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2349
2350        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2351                PACKAGE_MIME_TYPE, 0, 0);
2352
2353        String requiredInstaller = null;
2354
2355        final int N = installers.size();
2356        for (int i = 0; i < N; i++) {
2357            final ResolveInfo info = installers.get(i);
2358            final String packageName = info.activityInfo.packageName;
2359
2360            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2361                continue;
2362            }
2363
2364            if (requiredInstaller != null) {
2365                throw new RuntimeException("There must be one required installer");
2366            }
2367
2368            requiredInstaller = packageName;
2369        }
2370
2371        if (requiredInstaller == null) {
2372            throw new RuntimeException("There must be one required installer");
2373        }
2374
2375        return requiredInstaller;
2376    }
2377
2378    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2379        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2380        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2381                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2382
2383        ComponentName verifierComponentName = null;
2384
2385        int priority = -1000;
2386        final int N = receivers.size();
2387        for (int i = 0; i < N; i++) {
2388            final ResolveInfo info = receivers.get(i);
2389
2390            if (info.activityInfo == null) {
2391                continue;
2392            }
2393
2394            final String packageName = info.activityInfo.packageName;
2395
2396            final PackageSetting ps = mSettings.mPackages.get(packageName);
2397            if (ps == null) {
2398                continue;
2399            }
2400
2401            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2402                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2403                continue;
2404            }
2405
2406            // Select the IntentFilterVerifier with the highest priority
2407            if (priority < info.priority) {
2408                priority = info.priority;
2409                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2410                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2411                        + verifierComponentName + " with priority: " + info.priority);
2412            }
2413        }
2414
2415        return verifierComponentName;
2416    }
2417
2418    private void primeDomainVerificationsLPw(int userId) {
2419        if (DEBUG_DOMAIN_VERIFICATION) {
2420            Slog.d(TAG, "Priming domain verifications in user " + userId);
2421        }
2422
2423        SystemConfig systemConfig = SystemConfig.getInstance();
2424        ArraySet<String> packages = systemConfig.getLinkedApps();
2425        ArraySet<String> domains = new ArraySet<String>();
2426
2427        for (String packageName : packages) {
2428            PackageParser.Package pkg = mPackages.get(packageName);
2429            if (pkg != null) {
2430                if (!pkg.isSystemApp()) {
2431                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2432                    continue;
2433                }
2434
2435                domains.clear();
2436                for (PackageParser.Activity a : pkg.activities) {
2437                    for (ActivityIntentInfo filter : a.intents) {
2438                        if (hasValidDomains(filter)) {
2439                            domains.addAll(filter.getHostsList());
2440                        }
2441                    }
2442                }
2443
2444                if (domains.size() > 0) {
2445                    if (DEBUG_DOMAIN_VERIFICATION) {
2446                        Slog.v(TAG, "      + " + packageName);
2447                    }
2448                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2449                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2450                    // and then 'always' in the per-user state actually used for intent resolution.
2451                    final IntentFilterVerificationInfo ivi;
2452                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2453                            new ArrayList<String>(domains));
2454                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2455                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2456                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2457                } else {
2458                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2459                            + "' does not handle web links");
2460                }
2461            } else {
2462                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2463            }
2464        }
2465
2466        scheduleWritePackageRestrictionsLocked(userId);
2467        scheduleWriteSettingsLocked();
2468    }
2469
2470    private void applyFactoryDefaultBrowserLPw(int userId) {
2471        // The default browser app's package name is stored in a string resource,
2472        // with a product-specific overlay used for vendor customization.
2473        String browserPkg = mContext.getResources().getString(
2474                com.android.internal.R.string.default_browser);
2475        if (!TextUtils.isEmpty(browserPkg)) {
2476            // non-empty string => required to be a known package
2477            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2478            if (ps == null) {
2479                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2480                browserPkg = null;
2481            } else {
2482                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2483            }
2484        }
2485
2486        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2487        // default.  If there's more than one, just leave everything alone.
2488        if (browserPkg == null) {
2489            calculateDefaultBrowserLPw(userId);
2490        }
2491    }
2492
2493    private void calculateDefaultBrowserLPw(int userId) {
2494        List<String> allBrowsers = resolveAllBrowserApps(userId);
2495        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2496        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2497    }
2498
2499    private List<String> resolveAllBrowserApps(int userId) {
2500        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2501        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2502                PackageManager.MATCH_ALL, userId);
2503
2504        final int count = list.size();
2505        List<String> result = new ArrayList<String>(count);
2506        for (int i=0; i<count; i++) {
2507            ResolveInfo info = list.get(i);
2508            if (info.activityInfo == null
2509                    || !info.handleAllWebDataURI
2510                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2511                    || result.contains(info.activityInfo.packageName)) {
2512                continue;
2513            }
2514            result.add(info.activityInfo.packageName);
2515        }
2516
2517        return result;
2518    }
2519
2520    private boolean packageIsBrowser(String packageName, int userId) {
2521        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2522                PackageManager.MATCH_ALL, userId);
2523        final int N = list.size();
2524        for (int i = 0; i < N; i++) {
2525            ResolveInfo info = list.get(i);
2526            if (packageName.equals(info.activityInfo.packageName)) {
2527                return true;
2528            }
2529        }
2530        return false;
2531    }
2532
2533    private void checkDefaultBrowser() {
2534        final int myUserId = UserHandle.myUserId();
2535        final String packageName = getDefaultBrowserPackageName(myUserId);
2536        if (packageName != null) {
2537            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2538            if (info == null) {
2539                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2540                synchronized (mPackages) {
2541                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2542                }
2543            }
2544        }
2545    }
2546
2547    @Override
2548    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2549            throws RemoteException {
2550        try {
2551            return super.onTransact(code, data, reply, flags);
2552        } catch (RuntimeException e) {
2553            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2554                Slog.wtf(TAG, "Package Manager Crash", e);
2555            }
2556            throw e;
2557        }
2558    }
2559
2560    void cleanupInstallFailedPackage(PackageSetting ps) {
2561        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2562
2563        removeDataDirsLI(ps.volumeUuid, ps.name);
2564        if (ps.codePath != null) {
2565            if (ps.codePath.isDirectory()) {
2566                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2567            } else {
2568                ps.codePath.delete();
2569            }
2570        }
2571        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2572            if (ps.resourcePath.isDirectory()) {
2573                FileUtils.deleteContents(ps.resourcePath);
2574            }
2575            ps.resourcePath.delete();
2576        }
2577        mSettings.removePackageLPw(ps.name);
2578    }
2579
2580    static int[] appendInts(int[] cur, int[] add) {
2581        if (add == null) return cur;
2582        if (cur == null) return add;
2583        final int N = add.length;
2584        for (int i=0; i<N; i++) {
2585            cur = appendInt(cur, add[i]);
2586        }
2587        return cur;
2588    }
2589
2590    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2591        if (!sUserManager.exists(userId)) return null;
2592        final PackageSetting ps = (PackageSetting) p.mExtras;
2593        if (ps == null) {
2594            return null;
2595        }
2596
2597        final PermissionsState permissionsState = ps.getPermissionsState();
2598
2599        final int[] gids = permissionsState.computeGids(userId);
2600        final Set<String> permissions = permissionsState.getPermissions(userId);
2601        final PackageUserState state = ps.readUserState(userId);
2602
2603        return PackageParser.generatePackageInfo(p, gids, flags,
2604                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2605    }
2606
2607    @Override
2608    public boolean isPackageFrozen(String packageName) {
2609        synchronized (mPackages) {
2610            final PackageSetting ps = mSettings.mPackages.get(packageName);
2611            if (ps != null) {
2612                return ps.frozen;
2613            }
2614        }
2615        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2616        return true;
2617    }
2618
2619    @Override
2620    public boolean isPackageAvailable(String packageName, int userId) {
2621        if (!sUserManager.exists(userId)) return false;
2622        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2623        synchronized (mPackages) {
2624            PackageParser.Package p = mPackages.get(packageName);
2625            if (p != null) {
2626                final PackageSetting ps = (PackageSetting) p.mExtras;
2627                if (ps != null) {
2628                    final PackageUserState state = ps.readUserState(userId);
2629                    if (state != null) {
2630                        return PackageParser.isAvailable(state);
2631                    }
2632                }
2633            }
2634        }
2635        return false;
2636    }
2637
2638    @Override
2639    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2640        if (!sUserManager.exists(userId)) return null;
2641        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2642        // reader
2643        synchronized (mPackages) {
2644            PackageParser.Package p = mPackages.get(packageName);
2645            if (DEBUG_PACKAGE_INFO)
2646                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2647            if (p != null) {
2648                return generatePackageInfo(p, flags, userId);
2649            }
2650            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2651                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2652            }
2653        }
2654        return null;
2655    }
2656
2657    @Override
2658    public String[] currentToCanonicalPackageNames(String[] names) {
2659        String[] out = new String[names.length];
2660        // reader
2661        synchronized (mPackages) {
2662            for (int i=names.length-1; i>=0; i--) {
2663                PackageSetting ps = mSettings.mPackages.get(names[i]);
2664                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2665            }
2666        }
2667        return out;
2668    }
2669
2670    @Override
2671    public String[] canonicalToCurrentPackageNames(String[] names) {
2672        String[] out = new String[names.length];
2673        // reader
2674        synchronized (mPackages) {
2675            for (int i=names.length-1; i>=0; i--) {
2676                String cur = mSettings.mRenamedPackages.get(names[i]);
2677                out[i] = cur != null ? cur : names[i];
2678            }
2679        }
2680        return out;
2681    }
2682
2683    @Override
2684    public int getPackageUid(String packageName, int userId) {
2685        if (!sUserManager.exists(userId)) return -1;
2686        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2687
2688        // reader
2689        synchronized (mPackages) {
2690            PackageParser.Package p = mPackages.get(packageName);
2691            if(p != null) {
2692                return UserHandle.getUid(userId, p.applicationInfo.uid);
2693            }
2694            PackageSetting ps = mSettings.mPackages.get(packageName);
2695            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2696                return -1;
2697            }
2698            p = ps.pkg;
2699            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2700        }
2701    }
2702
2703    @Override
2704    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2705        if (!sUserManager.exists(userId)) {
2706            return null;
2707        }
2708
2709        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2710                "getPackageGids");
2711
2712        // reader
2713        synchronized (mPackages) {
2714            PackageParser.Package p = mPackages.get(packageName);
2715            if (DEBUG_PACKAGE_INFO) {
2716                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2717            }
2718            if (p != null) {
2719                PackageSetting ps = (PackageSetting) p.mExtras;
2720                return ps.getPermissionsState().computeGids(userId);
2721            }
2722        }
2723
2724        return null;
2725    }
2726
2727    @Override
2728    public int getMountExternalMode(int uid) {
2729        if (Process.isIsolated(uid)) {
2730            return Zygote.MOUNT_EXTERNAL_NONE;
2731        } else {
2732            if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
2733                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2734            } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2735                return Zygote.MOUNT_EXTERNAL_WRITE;
2736            } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2737                return Zygote.MOUNT_EXTERNAL_READ;
2738            } else {
2739                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2740            }
2741        }
2742    }
2743
2744    static PermissionInfo generatePermissionInfo(
2745            BasePermission bp, int flags) {
2746        if (bp.perm != null) {
2747            return PackageParser.generatePermissionInfo(bp.perm, flags);
2748        }
2749        PermissionInfo pi = new PermissionInfo();
2750        pi.name = bp.name;
2751        pi.packageName = bp.sourcePackage;
2752        pi.nonLocalizedLabel = bp.name;
2753        pi.protectionLevel = bp.protectionLevel;
2754        return pi;
2755    }
2756
2757    @Override
2758    public PermissionInfo getPermissionInfo(String name, int flags) {
2759        // reader
2760        synchronized (mPackages) {
2761            final BasePermission p = mSettings.mPermissions.get(name);
2762            if (p != null) {
2763                return generatePermissionInfo(p, flags);
2764            }
2765            return null;
2766        }
2767    }
2768
2769    @Override
2770    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2771        // reader
2772        synchronized (mPackages) {
2773            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2774            for (BasePermission p : mSettings.mPermissions.values()) {
2775                if (group == null) {
2776                    if (p.perm == null || p.perm.info.group == null) {
2777                        out.add(generatePermissionInfo(p, flags));
2778                    }
2779                } else {
2780                    if (p.perm != null && group.equals(p.perm.info.group)) {
2781                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2782                    }
2783                }
2784            }
2785
2786            if (out.size() > 0) {
2787                return out;
2788            }
2789            return mPermissionGroups.containsKey(group) ? out : null;
2790        }
2791    }
2792
2793    @Override
2794    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2795        // reader
2796        synchronized (mPackages) {
2797            return PackageParser.generatePermissionGroupInfo(
2798                    mPermissionGroups.get(name), flags);
2799        }
2800    }
2801
2802    @Override
2803    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2804        // reader
2805        synchronized (mPackages) {
2806            final int N = mPermissionGroups.size();
2807            ArrayList<PermissionGroupInfo> out
2808                    = new ArrayList<PermissionGroupInfo>(N);
2809            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2810                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2811            }
2812            return out;
2813        }
2814    }
2815
2816    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2817            int userId) {
2818        if (!sUserManager.exists(userId)) return null;
2819        PackageSetting ps = mSettings.mPackages.get(packageName);
2820        if (ps != null) {
2821            if (ps.pkg == null) {
2822                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2823                        flags, userId);
2824                if (pInfo != null) {
2825                    return pInfo.applicationInfo;
2826                }
2827                return null;
2828            }
2829            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2830                    ps.readUserState(userId), userId);
2831        }
2832        return null;
2833    }
2834
2835    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2836            int userId) {
2837        if (!sUserManager.exists(userId)) return null;
2838        PackageSetting ps = mSettings.mPackages.get(packageName);
2839        if (ps != null) {
2840            PackageParser.Package pkg = ps.pkg;
2841            if (pkg == null) {
2842                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2843                    return null;
2844                }
2845                // Only data remains, so we aren't worried about code paths
2846                pkg = new PackageParser.Package(packageName);
2847                pkg.applicationInfo.packageName = packageName;
2848                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2849                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2850                pkg.applicationInfo.dataDir = Environment
2851                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2852                        .getAbsolutePath();
2853                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2854                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2855            }
2856            return generatePackageInfo(pkg, flags, userId);
2857        }
2858        return null;
2859    }
2860
2861    @Override
2862    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2863        if (!sUserManager.exists(userId)) return null;
2864        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2865        // writer
2866        synchronized (mPackages) {
2867            PackageParser.Package p = mPackages.get(packageName);
2868            if (DEBUG_PACKAGE_INFO) Log.v(
2869                    TAG, "getApplicationInfo " + packageName
2870                    + ": " + p);
2871            if (p != null) {
2872                PackageSetting ps = mSettings.mPackages.get(packageName);
2873                if (ps == null) return null;
2874                // Note: isEnabledLP() does not apply here - always return info
2875                return PackageParser.generateApplicationInfo(
2876                        p, flags, ps.readUserState(userId), userId);
2877            }
2878            if ("android".equals(packageName)||"system".equals(packageName)) {
2879                return mAndroidApplication;
2880            }
2881            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2882                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2883            }
2884        }
2885        return null;
2886    }
2887
2888    @Override
2889    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2890            final IPackageDataObserver observer) {
2891        mContext.enforceCallingOrSelfPermission(
2892                android.Manifest.permission.CLEAR_APP_CACHE, null);
2893        // Queue up an async operation since clearing cache may take a little while.
2894        mHandler.post(new Runnable() {
2895            public void run() {
2896                mHandler.removeCallbacks(this);
2897                int retCode = -1;
2898                synchronized (mInstallLock) {
2899                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2900                    if (retCode < 0) {
2901                        Slog.w(TAG, "Couldn't clear application caches");
2902                    }
2903                }
2904                if (observer != null) {
2905                    try {
2906                        observer.onRemoveCompleted(null, (retCode >= 0));
2907                    } catch (RemoteException e) {
2908                        Slog.w(TAG, "RemoveException when invoking call back");
2909                    }
2910                }
2911            }
2912        });
2913    }
2914
2915    @Override
2916    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2917            final IntentSender pi) {
2918        mContext.enforceCallingOrSelfPermission(
2919                android.Manifest.permission.CLEAR_APP_CACHE, null);
2920        // Queue up an async operation since clearing cache may take a little while.
2921        mHandler.post(new Runnable() {
2922            public void run() {
2923                mHandler.removeCallbacks(this);
2924                int retCode = -1;
2925                synchronized (mInstallLock) {
2926                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2927                    if (retCode < 0) {
2928                        Slog.w(TAG, "Couldn't clear application caches");
2929                    }
2930                }
2931                if(pi != null) {
2932                    try {
2933                        // Callback via pending intent
2934                        int code = (retCode >= 0) ? 1 : 0;
2935                        pi.sendIntent(null, code, null,
2936                                null, null);
2937                    } catch (SendIntentException e1) {
2938                        Slog.i(TAG, "Failed to send pending intent");
2939                    }
2940                }
2941            }
2942        });
2943    }
2944
2945    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2946        synchronized (mInstallLock) {
2947            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2948                throw new IOException("Failed to free enough space");
2949            }
2950        }
2951    }
2952
2953    @Override
2954    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2955        if (!sUserManager.exists(userId)) return null;
2956        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2957        synchronized (mPackages) {
2958            PackageParser.Activity a = mActivities.mActivities.get(component);
2959
2960            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2961            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2962                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2963                if (ps == null) return null;
2964                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2965                        userId);
2966            }
2967            if (mResolveComponentName.equals(component)) {
2968                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2969                        new PackageUserState(), userId);
2970            }
2971        }
2972        return null;
2973    }
2974
2975    @Override
2976    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2977            String resolvedType) {
2978        synchronized (mPackages) {
2979            PackageParser.Activity a = mActivities.mActivities.get(component);
2980            if (a == null) {
2981                return false;
2982            }
2983            for (int i=0; i<a.intents.size(); i++) {
2984                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2985                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2986                    return true;
2987                }
2988            }
2989            return false;
2990        }
2991    }
2992
2993    @Override
2994    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2995        if (!sUserManager.exists(userId)) return null;
2996        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2997        synchronized (mPackages) {
2998            PackageParser.Activity a = mReceivers.mActivities.get(component);
2999            if (DEBUG_PACKAGE_INFO) Log.v(
3000                TAG, "getReceiverInfo " + component + ": " + a);
3001            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3002                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3003                if (ps == null) return null;
3004                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3005                        userId);
3006            }
3007        }
3008        return null;
3009    }
3010
3011    @Override
3012    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3013        if (!sUserManager.exists(userId)) return null;
3014        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3015        synchronized (mPackages) {
3016            PackageParser.Service s = mServices.mServices.get(component);
3017            if (DEBUG_PACKAGE_INFO) Log.v(
3018                TAG, "getServiceInfo " + component + ": " + s);
3019            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3020                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3021                if (ps == null) return null;
3022                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3023                        userId);
3024            }
3025        }
3026        return null;
3027    }
3028
3029    @Override
3030    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3031        if (!sUserManager.exists(userId)) return null;
3032        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3033        synchronized (mPackages) {
3034            PackageParser.Provider p = mProviders.mProviders.get(component);
3035            if (DEBUG_PACKAGE_INFO) Log.v(
3036                TAG, "getProviderInfo " + component + ": " + p);
3037            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3038                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3039                if (ps == null) return null;
3040                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3041                        userId);
3042            }
3043        }
3044        return null;
3045    }
3046
3047    @Override
3048    public String[] getSystemSharedLibraryNames() {
3049        Set<String> libSet;
3050        synchronized (mPackages) {
3051            libSet = mSharedLibraries.keySet();
3052            int size = libSet.size();
3053            if (size > 0) {
3054                String[] libs = new String[size];
3055                libSet.toArray(libs);
3056                return libs;
3057            }
3058        }
3059        return null;
3060    }
3061
3062    /**
3063     * @hide
3064     */
3065    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3066        synchronized (mPackages) {
3067            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3068            if (lib != null && lib.apk != null) {
3069                return mPackages.get(lib.apk);
3070            }
3071        }
3072        return null;
3073    }
3074
3075    @Override
3076    public FeatureInfo[] getSystemAvailableFeatures() {
3077        Collection<FeatureInfo> featSet;
3078        synchronized (mPackages) {
3079            featSet = mAvailableFeatures.values();
3080            int size = featSet.size();
3081            if (size > 0) {
3082                FeatureInfo[] features = new FeatureInfo[size+1];
3083                featSet.toArray(features);
3084                FeatureInfo fi = new FeatureInfo();
3085                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3086                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3087                features[size] = fi;
3088                return features;
3089            }
3090        }
3091        return null;
3092    }
3093
3094    @Override
3095    public boolean hasSystemFeature(String name) {
3096        synchronized (mPackages) {
3097            return mAvailableFeatures.containsKey(name);
3098        }
3099    }
3100
3101    private void checkValidCaller(int uid, int userId) {
3102        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3103            return;
3104
3105        throw new SecurityException("Caller uid=" + uid
3106                + " is not privileged to communicate with user=" + userId);
3107    }
3108
3109    @Override
3110    public int checkPermission(String permName, String pkgName, int userId) {
3111        if (!sUserManager.exists(userId)) {
3112            return PackageManager.PERMISSION_DENIED;
3113        }
3114
3115        synchronized (mPackages) {
3116            final PackageParser.Package p = mPackages.get(pkgName);
3117            if (p != null && p.mExtras != null) {
3118                final PackageSetting ps = (PackageSetting) p.mExtras;
3119                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3120                    return PackageManager.PERMISSION_GRANTED;
3121                }
3122            }
3123        }
3124
3125        return PackageManager.PERMISSION_DENIED;
3126    }
3127
3128    @Override
3129    public int checkUidPermission(String permName, int uid) {
3130        final int userId = UserHandle.getUserId(uid);
3131
3132        if (!sUserManager.exists(userId)) {
3133            return PackageManager.PERMISSION_DENIED;
3134        }
3135
3136        synchronized (mPackages) {
3137            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3138            if (obj != null) {
3139                final SettingBase ps = (SettingBase) obj;
3140                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3141                    return PackageManager.PERMISSION_GRANTED;
3142                }
3143            } else {
3144                ArraySet<String> perms = mSystemPermissions.get(uid);
3145                if (perms != null && perms.contains(permName)) {
3146                    return PackageManager.PERMISSION_GRANTED;
3147                }
3148            }
3149        }
3150
3151        return PackageManager.PERMISSION_DENIED;
3152    }
3153
3154    @Override
3155    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3156        if (UserHandle.getCallingUserId() != userId) {
3157            mContext.enforceCallingPermission(
3158                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3159                    "isPermissionRevokedByPolicy for user " + userId);
3160        }
3161
3162        if (checkPermission(permission, packageName, userId)
3163                == PackageManager.PERMISSION_GRANTED) {
3164            return false;
3165        }
3166
3167        final long identity = Binder.clearCallingIdentity();
3168        try {
3169            final int flags = getPermissionFlags(permission, packageName, userId);
3170            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3171        } finally {
3172            Binder.restoreCallingIdentity(identity);
3173        }
3174    }
3175
3176    /**
3177     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3178     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3179     * @param checkShell TODO(yamasani):
3180     * @param message the message to log on security exception
3181     */
3182    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3183            boolean checkShell, String message) {
3184        if (userId < 0) {
3185            throw new IllegalArgumentException("Invalid userId " + userId);
3186        }
3187        if (checkShell) {
3188            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3189        }
3190        if (userId == UserHandle.getUserId(callingUid)) return;
3191        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3192            if (requireFullPermission) {
3193                mContext.enforceCallingOrSelfPermission(
3194                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3195            } else {
3196                try {
3197                    mContext.enforceCallingOrSelfPermission(
3198                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3199                } catch (SecurityException se) {
3200                    mContext.enforceCallingOrSelfPermission(
3201                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3202                }
3203            }
3204        }
3205    }
3206
3207    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3208        if (callingUid == Process.SHELL_UID) {
3209            if (userHandle >= 0
3210                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3211                throw new SecurityException("Shell does not have permission to access user "
3212                        + userHandle);
3213            } else if (userHandle < 0) {
3214                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3215                        + Debug.getCallers(3));
3216            }
3217        }
3218    }
3219
3220    private BasePermission findPermissionTreeLP(String permName) {
3221        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3222            if (permName.startsWith(bp.name) &&
3223                    permName.length() > bp.name.length() &&
3224                    permName.charAt(bp.name.length()) == '.') {
3225                return bp;
3226            }
3227        }
3228        return null;
3229    }
3230
3231    private BasePermission checkPermissionTreeLP(String permName) {
3232        if (permName != null) {
3233            BasePermission bp = findPermissionTreeLP(permName);
3234            if (bp != null) {
3235                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3236                    return bp;
3237                }
3238                throw new SecurityException("Calling uid "
3239                        + Binder.getCallingUid()
3240                        + " is not allowed to add to permission tree "
3241                        + bp.name + " owned by uid " + bp.uid);
3242            }
3243        }
3244        throw new SecurityException("No permission tree found for " + permName);
3245    }
3246
3247    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3248        if (s1 == null) {
3249            return s2 == null;
3250        }
3251        if (s2 == null) {
3252            return false;
3253        }
3254        if (s1.getClass() != s2.getClass()) {
3255            return false;
3256        }
3257        return s1.equals(s2);
3258    }
3259
3260    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3261        if (pi1.icon != pi2.icon) return false;
3262        if (pi1.logo != pi2.logo) return false;
3263        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3264        if (!compareStrings(pi1.name, pi2.name)) return false;
3265        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3266        // We'll take care of setting this one.
3267        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3268        // These are not currently stored in settings.
3269        //if (!compareStrings(pi1.group, pi2.group)) return false;
3270        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3271        //if (pi1.labelRes != pi2.labelRes) return false;
3272        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3273        return true;
3274    }
3275
3276    int permissionInfoFootprint(PermissionInfo info) {
3277        int size = info.name.length();
3278        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3279        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3280        return size;
3281    }
3282
3283    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3284        int size = 0;
3285        for (BasePermission perm : mSettings.mPermissions.values()) {
3286            if (perm.uid == tree.uid) {
3287                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3288            }
3289        }
3290        return size;
3291    }
3292
3293    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3294        // We calculate the max size of permissions defined by this uid and throw
3295        // if that plus the size of 'info' would exceed our stated maximum.
3296        if (tree.uid != Process.SYSTEM_UID) {
3297            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3298            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3299                throw new SecurityException("Permission tree size cap exceeded");
3300            }
3301        }
3302    }
3303
3304    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3305        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3306            throw new SecurityException("Label must be specified in permission");
3307        }
3308        BasePermission tree = checkPermissionTreeLP(info.name);
3309        BasePermission bp = mSettings.mPermissions.get(info.name);
3310        boolean added = bp == null;
3311        boolean changed = true;
3312        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3313        if (added) {
3314            enforcePermissionCapLocked(info, tree);
3315            bp = new BasePermission(info.name, tree.sourcePackage,
3316                    BasePermission.TYPE_DYNAMIC);
3317        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3318            throw new SecurityException(
3319                    "Not allowed to modify non-dynamic permission "
3320                    + info.name);
3321        } else {
3322            if (bp.protectionLevel == fixedLevel
3323                    && bp.perm.owner.equals(tree.perm.owner)
3324                    && bp.uid == tree.uid
3325                    && comparePermissionInfos(bp.perm.info, info)) {
3326                changed = false;
3327            }
3328        }
3329        bp.protectionLevel = fixedLevel;
3330        info = new PermissionInfo(info);
3331        info.protectionLevel = fixedLevel;
3332        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3333        bp.perm.info.packageName = tree.perm.info.packageName;
3334        bp.uid = tree.uid;
3335        if (added) {
3336            mSettings.mPermissions.put(info.name, bp);
3337        }
3338        if (changed) {
3339            if (!async) {
3340                mSettings.writeLPr();
3341            } else {
3342                scheduleWriteSettingsLocked();
3343            }
3344        }
3345        return added;
3346    }
3347
3348    @Override
3349    public boolean addPermission(PermissionInfo info) {
3350        synchronized (mPackages) {
3351            return addPermissionLocked(info, false);
3352        }
3353    }
3354
3355    @Override
3356    public boolean addPermissionAsync(PermissionInfo info) {
3357        synchronized (mPackages) {
3358            return addPermissionLocked(info, true);
3359        }
3360    }
3361
3362    @Override
3363    public void removePermission(String name) {
3364        synchronized (mPackages) {
3365            checkPermissionTreeLP(name);
3366            BasePermission bp = mSettings.mPermissions.get(name);
3367            if (bp != null) {
3368                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3369                    throw new SecurityException(
3370                            "Not allowed to modify non-dynamic permission "
3371                            + name);
3372                }
3373                mSettings.mPermissions.remove(name);
3374                mSettings.writeLPr();
3375            }
3376        }
3377    }
3378
3379    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3380            BasePermission bp) {
3381        int index = pkg.requestedPermissions.indexOf(bp.name);
3382        if (index == -1) {
3383            throw new SecurityException("Package " + pkg.packageName
3384                    + " has not requested permission " + bp.name);
3385        }
3386        if (!bp.isRuntime()) {
3387            throw new SecurityException("Permission " + bp.name
3388                    + " is not a changeable permission type");
3389        }
3390    }
3391
3392    @Override
3393    public void grantRuntimePermission(String packageName, String name, final int userId) {
3394        if (!sUserManager.exists(userId)) {
3395            Log.e(TAG, "No such user:" + userId);
3396            return;
3397        }
3398
3399        mContext.enforceCallingOrSelfPermission(
3400                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3401                "grantRuntimePermission");
3402
3403        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3404                "grantRuntimePermission");
3405
3406        final int uid;
3407        final SettingBase sb;
3408
3409        synchronized (mPackages) {
3410            final PackageParser.Package pkg = mPackages.get(packageName);
3411            if (pkg == null) {
3412                throw new IllegalArgumentException("Unknown package: " + packageName);
3413            }
3414
3415            final BasePermission bp = mSettings.mPermissions.get(name);
3416            if (bp == null) {
3417                throw new IllegalArgumentException("Unknown permission: " + name);
3418            }
3419
3420            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3421
3422            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3423            sb = (SettingBase) pkg.mExtras;
3424            if (sb == null) {
3425                throw new IllegalArgumentException("Unknown package: " + packageName);
3426            }
3427
3428            final PermissionsState permissionsState = sb.getPermissionsState();
3429
3430            final int flags = permissionsState.getPermissionFlags(name, userId);
3431            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3432                throw new SecurityException("Cannot grant system fixed permission: "
3433                        + name + " for package: " + packageName);
3434            }
3435
3436            final int result = permissionsState.grantRuntimePermission(bp, userId);
3437            switch (result) {
3438                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3439                    return;
3440                }
3441
3442                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3443                    mHandler.post(new Runnable() {
3444                        @Override
3445                        public void run() {
3446                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3447                        }
3448                    });
3449                } break;
3450            }
3451
3452            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3453
3454            // Not critical if that is lost - app has to request again.
3455            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3456        }
3457
3458        // Only need to do this if user is initialized. Otherwise it's a new user
3459        // and there are no processes running as the user yet and there's no need
3460        // to make an expensive call to remount processes for the changed permissions.
3461        if (READ_EXTERNAL_STORAGE.equals(name)
3462                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3463            final long token = Binder.clearCallingIdentity();
3464            try {
3465                if (sUserManager.isInitialized(userId)) {
3466                    final StorageManager storage = mContext.getSystemService(StorageManager.class);
3467                    storage.remountUid(uid);
3468                }
3469            } finally {
3470                Binder.restoreCallingIdentity(token);
3471            }
3472        }
3473    }
3474
3475    @Override
3476    public void revokeRuntimePermission(String packageName, String name, int userId) {
3477        if (!sUserManager.exists(userId)) {
3478            Log.e(TAG, "No such user:" + userId);
3479            return;
3480        }
3481
3482        mContext.enforceCallingOrSelfPermission(
3483                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3484                "revokeRuntimePermission");
3485
3486        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3487                "revokeRuntimePermission");
3488
3489        final SettingBase sb;
3490
3491        synchronized (mPackages) {
3492            final PackageParser.Package pkg = mPackages.get(packageName);
3493            if (pkg == null) {
3494                throw new IllegalArgumentException("Unknown package: " + packageName);
3495            }
3496
3497            final BasePermission bp = mSettings.mPermissions.get(name);
3498            if (bp == null) {
3499                throw new IllegalArgumentException("Unknown permission: " + name);
3500            }
3501
3502            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3503
3504            sb = (SettingBase) pkg.mExtras;
3505            if (sb == null) {
3506                throw new IllegalArgumentException("Unknown package: " + packageName);
3507            }
3508
3509            final PermissionsState permissionsState = sb.getPermissionsState();
3510
3511            final int flags = permissionsState.getPermissionFlags(name, userId);
3512            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3513                throw new SecurityException("Cannot revoke system fixed permission: "
3514                        + name + " for package: " + packageName);
3515            }
3516
3517            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3518                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3519                return;
3520            }
3521
3522            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3523
3524            // Critical, after this call app should never have the permission.
3525            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3526        }
3527
3528        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3529    }
3530
3531    @Override
3532    public void resetRuntimePermissions() {
3533        mContext.enforceCallingOrSelfPermission(
3534                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3535                "revokeRuntimePermission");
3536
3537        int callingUid = Binder.getCallingUid();
3538        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3539            mContext.enforceCallingOrSelfPermission(
3540                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3541                    "resetRuntimePermissions");
3542        }
3543
3544        final int[] userIds;
3545
3546        synchronized (mPackages) {
3547            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3548            final int userCount = UserManagerService.getInstance().getUserIds().length;
3549            userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount);
3550        }
3551
3552        for (int userId : userIds) {
3553            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
3554        }
3555    }
3556
3557    @Override
3558    public int getPermissionFlags(String name, String packageName, int userId) {
3559        if (!sUserManager.exists(userId)) {
3560            return 0;
3561        }
3562
3563        mContext.enforceCallingOrSelfPermission(
3564                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3565                "getPermissionFlags");
3566
3567        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3568                "getPermissionFlags");
3569
3570        synchronized (mPackages) {
3571            final PackageParser.Package pkg = mPackages.get(packageName);
3572            if (pkg == null) {
3573                throw new IllegalArgumentException("Unknown package: " + packageName);
3574            }
3575
3576            final BasePermission bp = mSettings.mPermissions.get(name);
3577            if (bp == null) {
3578                throw new IllegalArgumentException("Unknown permission: " + name);
3579            }
3580
3581            SettingBase sb = (SettingBase) pkg.mExtras;
3582            if (sb == null) {
3583                throw new IllegalArgumentException("Unknown package: " + packageName);
3584            }
3585
3586            PermissionsState permissionsState = sb.getPermissionsState();
3587            return permissionsState.getPermissionFlags(name, userId);
3588        }
3589    }
3590
3591    @Override
3592    public void updatePermissionFlags(String name, String packageName, int flagMask,
3593            int flagValues, int userId) {
3594        if (!sUserManager.exists(userId)) {
3595            return;
3596        }
3597
3598        mContext.enforceCallingOrSelfPermission(
3599                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3600                "updatePermissionFlags");
3601
3602        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3603                "updatePermissionFlags");
3604
3605        // Only the system can change system fixed flags.
3606        if (getCallingUid() != Process.SYSTEM_UID) {
3607            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3608            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3609        }
3610
3611        synchronized (mPackages) {
3612            final PackageParser.Package pkg = mPackages.get(packageName);
3613            if (pkg == null) {
3614                throw new IllegalArgumentException("Unknown package: " + packageName);
3615            }
3616
3617            final BasePermission bp = mSettings.mPermissions.get(name);
3618            if (bp == null) {
3619                throw new IllegalArgumentException("Unknown permission: " + name);
3620            }
3621
3622            SettingBase sb = (SettingBase) pkg.mExtras;
3623            if (sb == null) {
3624                throw new IllegalArgumentException("Unknown package: " + packageName);
3625            }
3626
3627            PermissionsState permissionsState = sb.getPermissionsState();
3628
3629            // Only the package manager can change flags for system component permissions.
3630            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3631            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3632                return;
3633            }
3634
3635            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3636
3637            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3638                // Install and runtime permissions are stored in different places,
3639                // so figure out what permission changed and persist the change.
3640                if (permissionsState.getInstallPermissionState(name) != null) {
3641                    scheduleWriteSettingsLocked();
3642                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3643                        || hadState) {
3644                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3645                }
3646            }
3647        }
3648    }
3649
3650    /**
3651     * Update the permission flags for all packages and runtime permissions of a user in order
3652     * to allow device or profile owner to remove POLICY_FIXED.
3653     */
3654    @Override
3655    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3656        if (!sUserManager.exists(userId)) {
3657            return;
3658        }
3659
3660        mContext.enforceCallingOrSelfPermission(
3661                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3662                "updatePermissionFlagsForAllApps");
3663
3664        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3665                "updatePermissionFlagsForAllApps");
3666
3667        // Only the system can change system fixed flags.
3668        if (getCallingUid() != Process.SYSTEM_UID) {
3669            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3670            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3671        }
3672
3673        synchronized (mPackages) {
3674            boolean changed = false;
3675            final int packageCount = mPackages.size();
3676            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3677                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3678                SettingBase sb = (SettingBase) pkg.mExtras;
3679                if (sb == null) {
3680                    continue;
3681                }
3682                PermissionsState permissionsState = sb.getPermissionsState();
3683                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3684                        userId, flagMask, flagValues);
3685            }
3686            if (changed) {
3687                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3688            }
3689        }
3690    }
3691
3692    @Override
3693    public boolean shouldShowRequestPermissionRationale(String permissionName,
3694            String packageName, int userId) {
3695        if (UserHandle.getCallingUserId() != userId) {
3696            mContext.enforceCallingPermission(
3697                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3698                    "canShowRequestPermissionRationale for user " + userId);
3699        }
3700
3701        final int uid = getPackageUid(packageName, userId);
3702        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3703            return false;
3704        }
3705
3706        if (checkPermission(permissionName, packageName, userId)
3707                == PackageManager.PERMISSION_GRANTED) {
3708            return false;
3709        }
3710
3711        final int flags;
3712
3713        final long identity = Binder.clearCallingIdentity();
3714        try {
3715            flags = getPermissionFlags(permissionName,
3716                    packageName, userId);
3717        } finally {
3718            Binder.restoreCallingIdentity(identity);
3719        }
3720
3721        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3722                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3723                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3724
3725        if ((flags & fixedFlags) != 0) {
3726            return false;
3727        }
3728
3729        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3730    }
3731
3732    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3733        BasePermission bp = mSettings.mPermissions.get(permission);
3734        if (bp == null) {
3735            throw new SecurityException("Missing " + permission + " permission");
3736        }
3737
3738        SettingBase sb = (SettingBase) pkg.mExtras;
3739        PermissionsState permissionsState = sb.getPermissionsState();
3740
3741        if (permissionsState.grantInstallPermission(bp) !=
3742                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3743            scheduleWriteSettingsLocked();
3744        }
3745    }
3746
3747    @Override
3748    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3749        mContext.enforceCallingOrSelfPermission(
3750                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3751                "addOnPermissionsChangeListener");
3752
3753        synchronized (mPackages) {
3754            mOnPermissionChangeListeners.addListenerLocked(listener);
3755        }
3756    }
3757
3758    @Override
3759    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3760        synchronized (mPackages) {
3761            mOnPermissionChangeListeners.removeListenerLocked(listener);
3762        }
3763    }
3764
3765    @Override
3766    public boolean isProtectedBroadcast(String actionName) {
3767        synchronized (mPackages) {
3768            return mProtectedBroadcasts.contains(actionName);
3769        }
3770    }
3771
3772    @Override
3773    public int checkSignatures(String pkg1, String pkg2) {
3774        synchronized (mPackages) {
3775            final PackageParser.Package p1 = mPackages.get(pkg1);
3776            final PackageParser.Package p2 = mPackages.get(pkg2);
3777            if (p1 == null || p1.mExtras == null
3778                    || p2 == null || p2.mExtras == null) {
3779                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3780            }
3781            return compareSignatures(p1.mSignatures, p2.mSignatures);
3782        }
3783    }
3784
3785    @Override
3786    public int checkUidSignatures(int uid1, int uid2) {
3787        // Map to base uids.
3788        uid1 = UserHandle.getAppId(uid1);
3789        uid2 = UserHandle.getAppId(uid2);
3790        // reader
3791        synchronized (mPackages) {
3792            Signature[] s1;
3793            Signature[] s2;
3794            Object obj = mSettings.getUserIdLPr(uid1);
3795            if (obj != null) {
3796                if (obj instanceof SharedUserSetting) {
3797                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3798                } else if (obj instanceof PackageSetting) {
3799                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3800                } else {
3801                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3802                }
3803            } else {
3804                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3805            }
3806            obj = mSettings.getUserIdLPr(uid2);
3807            if (obj != null) {
3808                if (obj instanceof SharedUserSetting) {
3809                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3810                } else if (obj instanceof PackageSetting) {
3811                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3812                } else {
3813                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3814                }
3815            } else {
3816                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3817            }
3818            return compareSignatures(s1, s2);
3819        }
3820    }
3821
3822    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3823        final long identity = Binder.clearCallingIdentity();
3824        try {
3825            if (sb instanceof SharedUserSetting) {
3826                SharedUserSetting sus = (SharedUserSetting) sb;
3827                final int packageCount = sus.packages.size();
3828                for (int i = 0; i < packageCount; i++) {
3829                    PackageSetting susPs = sus.packages.valueAt(i);
3830                    if (userId == UserHandle.USER_ALL) {
3831                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3832                    } else {
3833                        final int uid = UserHandle.getUid(userId, susPs.appId);
3834                        killUid(uid, reason);
3835                    }
3836                }
3837            } else if (sb instanceof PackageSetting) {
3838                PackageSetting ps = (PackageSetting) sb;
3839                if (userId == UserHandle.USER_ALL) {
3840                    killApplication(ps.pkg.packageName, ps.appId, reason);
3841                } else {
3842                    final int uid = UserHandle.getUid(userId, ps.appId);
3843                    killUid(uid, reason);
3844                }
3845            }
3846        } finally {
3847            Binder.restoreCallingIdentity(identity);
3848        }
3849    }
3850
3851    private static void killUid(int uid, String reason) {
3852        IActivityManager am = ActivityManagerNative.getDefault();
3853        if (am != null) {
3854            try {
3855                am.killUid(uid, reason);
3856            } catch (RemoteException e) {
3857                /* ignore - same process */
3858            }
3859        }
3860    }
3861
3862    /**
3863     * Compares two sets of signatures. Returns:
3864     * <br />
3865     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3866     * <br />
3867     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3868     * <br />
3869     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3870     * <br />
3871     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3872     * <br />
3873     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3874     */
3875    static int compareSignatures(Signature[] s1, Signature[] s2) {
3876        if (s1 == null) {
3877            return s2 == null
3878                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3879                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3880        }
3881
3882        if (s2 == null) {
3883            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3884        }
3885
3886        if (s1.length != s2.length) {
3887            return PackageManager.SIGNATURE_NO_MATCH;
3888        }
3889
3890        // Since both signature sets are of size 1, we can compare without HashSets.
3891        if (s1.length == 1) {
3892            return s1[0].equals(s2[0]) ?
3893                    PackageManager.SIGNATURE_MATCH :
3894                    PackageManager.SIGNATURE_NO_MATCH;
3895        }
3896
3897        ArraySet<Signature> set1 = new ArraySet<Signature>();
3898        for (Signature sig : s1) {
3899            set1.add(sig);
3900        }
3901        ArraySet<Signature> set2 = new ArraySet<Signature>();
3902        for (Signature sig : s2) {
3903            set2.add(sig);
3904        }
3905        // Make sure s2 contains all signatures in s1.
3906        if (set1.equals(set2)) {
3907            return PackageManager.SIGNATURE_MATCH;
3908        }
3909        return PackageManager.SIGNATURE_NO_MATCH;
3910    }
3911
3912    /**
3913     * If the database version for this type of package (internal storage or
3914     * external storage) is less than the version where package signatures
3915     * were updated, return true.
3916     */
3917    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3918        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3919                DatabaseVersion.SIGNATURE_END_ENTITY))
3920                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3921                        DatabaseVersion.SIGNATURE_END_ENTITY));
3922    }
3923
3924    /**
3925     * Used for backward compatibility to make sure any packages with
3926     * certificate chains get upgraded to the new style. {@code existingSigs}
3927     * will be in the old format (since they were stored on disk from before the
3928     * system upgrade) and {@code scannedSigs} will be in the newer format.
3929     */
3930    private int compareSignaturesCompat(PackageSignatures existingSigs,
3931            PackageParser.Package scannedPkg) {
3932        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3933            return PackageManager.SIGNATURE_NO_MATCH;
3934        }
3935
3936        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3937        for (Signature sig : existingSigs.mSignatures) {
3938            existingSet.add(sig);
3939        }
3940        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3941        for (Signature sig : scannedPkg.mSignatures) {
3942            try {
3943                Signature[] chainSignatures = sig.getChainSignatures();
3944                for (Signature chainSig : chainSignatures) {
3945                    scannedCompatSet.add(chainSig);
3946                }
3947            } catch (CertificateEncodingException e) {
3948                scannedCompatSet.add(sig);
3949            }
3950        }
3951        /*
3952         * Make sure the expanded scanned set contains all signatures in the
3953         * existing one.
3954         */
3955        if (scannedCompatSet.equals(existingSet)) {
3956            // Migrate the old signatures to the new scheme.
3957            existingSigs.assignSignatures(scannedPkg.mSignatures);
3958            // The new KeySets will be re-added later in the scanning process.
3959            synchronized (mPackages) {
3960                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3961            }
3962            return PackageManager.SIGNATURE_MATCH;
3963        }
3964        return PackageManager.SIGNATURE_NO_MATCH;
3965    }
3966
3967    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3968        if (isExternal(scannedPkg)) {
3969            return mSettings.isExternalDatabaseVersionOlderThan(
3970                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3971        } else {
3972            return mSettings.isInternalDatabaseVersionOlderThan(
3973                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3974        }
3975    }
3976
3977    private int compareSignaturesRecover(PackageSignatures existingSigs,
3978            PackageParser.Package scannedPkg) {
3979        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3980            return PackageManager.SIGNATURE_NO_MATCH;
3981        }
3982
3983        String msg = null;
3984        try {
3985            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3986                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3987                        + scannedPkg.packageName);
3988                return PackageManager.SIGNATURE_MATCH;
3989            }
3990        } catch (CertificateException e) {
3991            msg = e.getMessage();
3992        }
3993
3994        logCriticalInfo(Log.INFO,
3995                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3996        return PackageManager.SIGNATURE_NO_MATCH;
3997    }
3998
3999    @Override
4000    public String[] getPackagesForUid(int uid) {
4001        uid = UserHandle.getAppId(uid);
4002        // reader
4003        synchronized (mPackages) {
4004            Object obj = mSettings.getUserIdLPr(uid);
4005            if (obj instanceof SharedUserSetting) {
4006                final SharedUserSetting sus = (SharedUserSetting) obj;
4007                final int N = sus.packages.size();
4008                final String[] res = new String[N];
4009                final Iterator<PackageSetting> it = sus.packages.iterator();
4010                int i = 0;
4011                while (it.hasNext()) {
4012                    res[i++] = it.next().name;
4013                }
4014                return res;
4015            } else if (obj instanceof PackageSetting) {
4016                final PackageSetting ps = (PackageSetting) obj;
4017                return new String[] { ps.name };
4018            }
4019        }
4020        return null;
4021    }
4022
4023    @Override
4024    public String getNameForUid(int uid) {
4025        // reader
4026        synchronized (mPackages) {
4027            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4028            if (obj instanceof SharedUserSetting) {
4029                final SharedUserSetting sus = (SharedUserSetting) obj;
4030                return sus.name + ":" + sus.userId;
4031            } else if (obj instanceof PackageSetting) {
4032                final PackageSetting ps = (PackageSetting) obj;
4033                return ps.name;
4034            }
4035        }
4036        return null;
4037    }
4038
4039    @Override
4040    public int getUidForSharedUser(String sharedUserName) {
4041        if(sharedUserName == null) {
4042            return -1;
4043        }
4044        // reader
4045        synchronized (mPackages) {
4046            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4047            if (suid == null) {
4048                return -1;
4049            }
4050            return suid.userId;
4051        }
4052    }
4053
4054    @Override
4055    public int getFlagsForUid(int uid) {
4056        synchronized (mPackages) {
4057            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4058            if (obj instanceof SharedUserSetting) {
4059                final SharedUserSetting sus = (SharedUserSetting) obj;
4060                return sus.pkgFlags;
4061            } else if (obj instanceof PackageSetting) {
4062                final PackageSetting ps = (PackageSetting) obj;
4063                return ps.pkgFlags;
4064            }
4065        }
4066        return 0;
4067    }
4068
4069    @Override
4070    public int getPrivateFlagsForUid(int uid) {
4071        synchronized (mPackages) {
4072            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4073            if (obj instanceof SharedUserSetting) {
4074                final SharedUserSetting sus = (SharedUserSetting) obj;
4075                return sus.pkgPrivateFlags;
4076            } else if (obj instanceof PackageSetting) {
4077                final PackageSetting ps = (PackageSetting) obj;
4078                return ps.pkgPrivateFlags;
4079            }
4080        }
4081        return 0;
4082    }
4083
4084    @Override
4085    public boolean isUidPrivileged(int uid) {
4086        uid = UserHandle.getAppId(uid);
4087        // reader
4088        synchronized (mPackages) {
4089            Object obj = mSettings.getUserIdLPr(uid);
4090            if (obj instanceof SharedUserSetting) {
4091                final SharedUserSetting sus = (SharedUserSetting) obj;
4092                final Iterator<PackageSetting> it = sus.packages.iterator();
4093                while (it.hasNext()) {
4094                    if (it.next().isPrivileged()) {
4095                        return true;
4096                    }
4097                }
4098            } else if (obj instanceof PackageSetting) {
4099                final PackageSetting ps = (PackageSetting) obj;
4100                return ps.isPrivileged();
4101            }
4102        }
4103        return false;
4104    }
4105
4106    @Override
4107    public String[] getAppOpPermissionPackages(String permissionName) {
4108        synchronized (mPackages) {
4109            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4110            if (pkgs == null) {
4111                return null;
4112            }
4113            return pkgs.toArray(new String[pkgs.size()]);
4114        }
4115    }
4116
4117    @Override
4118    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4119            int flags, int userId) {
4120        if (!sUserManager.exists(userId)) return null;
4121        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4122        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4123        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4124    }
4125
4126    @Override
4127    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4128            IntentFilter filter, int match, ComponentName activity) {
4129        final int userId = UserHandle.getCallingUserId();
4130        if (DEBUG_PREFERRED) {
4131            Log.v(TAG, "setLastChosenActivity intent=" + intent
4132                + " resolvedType=" + resolvedType
4133                + " flags=" + flags
4134                + " filter=" + filter
4135                + " match=" + match
4136                + " activity=" + activity);
4137            filter.dump(new PrintStreamPrinter(System.out), "    ");
4138        }
4139        intent.setComponent(null);
4140        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4141        // Find any earlier preferred or last chosen entries and nuke them
4142        findPreferredActivity(intent, resolvedType,
4143                flags, query, 0, false, true, false, userId);
4144        // Add the new activity as the last chosen for this filter
4145        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4146                "Setting last chosen");
4147    }
4148
4149    @Override
4150    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4151        final int userId = UserHandle.getCallingUserId();
4152        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4153        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4154        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4155                false, false, false, userId);
4156    }
4157
4158    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4159            int flags, List<ResolveInfo> query, int userId) {
4160        if (query != null) {
4161            final int N = query.size();
4162            if (N == 1) {
4163                return query.get(0);
4164            } else if (N > 1) {
4165                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4166                // If there is more than one activity with the same priority,
4167                // then let the user decide between them.
4168                ResolveInfo r0 = query.get(0);
4169                ResolveInfo r1 = query.get(1);
4170                if (DEBUG_INTENT_MATCHING || debug) {
4171                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4172                            + r1.activityInfo.name + "=" + r1.priority);
4173                }
4174                // If the first activity has a higher priority, or a different
4175                // default, then it is always desireable to pick it.
4176                if (r0.priority != r1.priority
4177                        || r0.preferredOrder != r1.preferredOrder
4178                        || r0.isDefault != r1.isDefault) {
4179                    return query.get(0);
4180                }
4181                // If we have saved a preference for a preferred activity for
4182                // this Intent, use that.
4183                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4184                        flags, query, r0.priority, true, false, debug, userId);
4185                if (ri != null) {
4186                    return ri;
4187                }
4188                if (userId != 0) {
4189                    ri = new ResolveInfo(mResolveInfo);
4190                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4191                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4192                            ri.activityInfo.applicationInfo);
4193                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4194                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4195                    return ri;
4196                }
4197                return mResolveInfo;
4198            }
4199        }
4200        return null;
4201    }
4202
4203    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4204            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4205        final int N = query.size();
4206        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4207                .get(userId);
4208        // Get the list of persistent preferred activities that handle the intent
4209        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4210        List<PersistentPreferredActivity> pprefs = ppir != null
4211                ? ppir.queryIntent(intent, resolvedType,
4212                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4213                : null;
4214        if (pprefs != null && pprefs.size() > 0) {
4215            final int M = pprefs.size();
4216            for (int i=0; i<M; i++) {
4217                final PersistentPreferredActivity ppa = pprefs.get(i);
4218                if (DEBUG_PREFERRED || debug) {
4219                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4220                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4221                            + "\n  component=" + ppa.mComponent);
4222                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4223                }
4224                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4225                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4226                if (DEBUG_PREFERRED || debug) {
4227                    Slog.v(TAG, "Found persistent preferred activity:");
4228                    if (ai != null) {
4229                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4230                    } else {
4231                        Slog.v(TAG, "  null");
4232                    }
4233                }
4234                if (ai == null) {
4235                    // This previously registered persistent preferred activity
4236                    // component is no longer known. Ignore it and do NOT remove it.
4237                    continue;
4238                }
4239                for (int j=0; j<N; j++) {
4240                    final ResolveInfo ri = query.get(j);
4241                    if (!ri.activityInfo.applicationInfo.packageName
4242                            .equals(ai.applicationInfo.packageName)) {
4243                        continue;
4244                    }
4245                    if (!ri.activityInfo.name.equals(ai.name)) {
4246                        continue;
4247                    }
4248                    //  Found a persistent preference that can handle the intent.
4249                    if (DEBUG_PREFERRED || debug) {
4250                        Slog.v(TAG, "Returning persistent preferred activity: " +
4251                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4252                    }
4253                    return ri;
4254                }
4255            }
4256        }
4257        return null;
4258    }
4259
4260    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4261            List<ResolveInfo> query, int priority, boolean always,
4262            boolean removeMatches, boolean debug, int userId) {
4263        if (!sUserManager.exists(userId)) return null;
4264        // writer
4265        synchronized (mPackages) {
4266            if (intent.getSelector() != null) {
4267                intent = intent.getSelector();
4268            }
4269            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4270
4271            // Try to find a matching persistent preferred activity.
4272            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4273                    debug, userId);
4274
4275            // If a persistent preferred activity matched, use it.
4276            if (pri != null) {
4277                return pri;
4278            }
4279
4280            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4281            // Get the list of preferred activities that handle the intent
4282            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4283            List<PreferredActivity> prefs = pir != null
4284                    ? pir.queryIntent(intent, resolvedType,
4285                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4286                    : null;
4287            if (prefs != null && prefs.size() > 0) {
4288                boolean changed = false;
4289                try {
4290                    // First figure out how good the original match set is.
4291                    // We will only allow preferred activities that came
4292                    // from the same match quality.
4293                    int match = 0;
4294
4295                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4296
4297                    final int N = query.size();
4298                    for (int j=0; j<N; j++) {
4299                        final ResolveInfo ri = query.get(j);
4300                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4301                                + ": 0x" + Integer.toHexString(match));
4302                        if (ri.match > match) {
4303                            match = ri.match;
4304                        }
4305                    }
4306
4307                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4308                            + Integer.toHexString(match));
4309
4310                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4311                    final int M = prefs.size();
4312                    for (int i=0; i<M; i++) {
4313                        final PreferredActivity pa = prefs.get(i);
4314                        if (DEBUG_PREFERRED || debug) {
4315                            Slog.v(TAG, "Checking PreferredActivity ds="
4316                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4317                                    + "\n  component=" + pa.mPref.mComponent);
4318                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4319                        }
4320                        if (pa.mPref.mMatch != match) {
4321                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4322                                    + Integer.toHexString(pa.mPref.mMatch));
4323                            continue;
4324                        }
4325                        // If it's not an "always" type preferred activity and that's what we're
4326                        // looking for, skip it.
4327                        if (always && !pa.mPref.mAlways) {
4328                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4329                            continue;
4330                        }
4331                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4332                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4333                        if (DEBUG_PREFERRED || debug) {
4334                            Slog.v(TAG, "Found preferred activity:");
4335                            if (ai != null) {
4336                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4337                            } else {
4338                                Slog.v(TAG, "  null");
4339                            }
4340                        }
4341                        if (ai == null) {
4342                            // This previously registered preferred activity
4343                            // component is no longer known.  Most likely an update
4344                            // to the app was installed and in the new version this
4345                            // component no longer exists.  Clean it up by removing
4346                            // it from the preferred activities list, and skip it.
4347                            Slog.w(TAG, "Removing dangling preferred activity: "
4348                                    + pa.mPref.mComponent);
4349                            pir.removeFilter(pa);
4350                            changed = true;
4351                            continue;
4352                        }
4353                        for (int j=0; j<N; j++) {
4354                            final ResolveInfo ri = query.get(j);
4355                            if (!ri.activityInfo.applicationInfo.packageName
4356                                    .equals(ai.applicationInfo.packageName)) {
4357                                continue;
4358                            }
4359                            if (!ri.activityInfo.name.equals(ai.name)) {
4360                                continue;
4361                            }
4362
4363                            if (removeMatches) {
4364                                pir.removeFilter(pa);
4365                                changed = true;
4366                                if (DEBUG_PREFERRED) {
4367                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4368                                }
4369                                break;
4370                            }
4371
4372                            // Okay we found a previously set preferred or last chosen app.
4373                            // If the result set is different from when this
4374                            // was created, we need to clear it and re-ask the
4375                            // user their preference, if we're looking for an "always" type entry.
4376                            if (always && !pa.mPref.sameSet(query)) {
4377                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4378                                        + intent + " type " + resolvedType);
4379                                if (DEBUG_PREFERRED) {
4380                                    Slog.v(TAG, "Removing preferred activity since set changed "
4381                                            + pa.mPref.mComponent);
4382                                }
4383                                pir.removeFilter(pa);
4384                                // Re-add the filter as a "last chosen" entry (!always)
4385                                PreferredActivity lastChosen = new PreferredActivity(
4386                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4387                                pir.addFilter(lastChosen);
4388                                changed = true;
4389                                return null;
4390                            }
4391
4392                            // Yay! Either the set matched or we're looking for the last chosen
4393                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4394                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4395                            return ri;
4396                        }
4397                    }
4398                } finally {
4399                    if (changed) {
4400                        if (DEBUG_PREFERRED) {
4401                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4402                        }
4403                        scheduleWritePackageRestrictionsLocked(userId);
4404                    }
4405                }
4406            }
4407        }
4408        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4409        return null;
4410    }
4411
4412    /*
4413     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4414     */
4415    @Override
4416    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4417            int targetUserId) {
4418        mContext.enforceCallingOrSelfPermission(
4419                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4420        List<CrossProfileIntentFilter> matches =
4421                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4422        if (matches != null) {
4423            int size = matches.size();
4424            for (int i = 0; i < size; i++) {
4425                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4426            }
4427        }
4428        if (hasWebURI(intent)) {
4429            // cross-profile app linking works only towards the parent.
4430            final UserInfo parent = getProfileParent(sourceUserId);
4431            synchronized(mPackages) {
4432                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4433                        intent, resolvedType, 0, sourceUserId, parent.id);
4434                return xpDomainInfo != null
4435                        && xpDomainInfo.bestDomainVerificationStatus !=
4436                                INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
4437            }
4438        }
4439        return false;
4440    }
4441
4442    private UserInfo getProfileParent(int userId) {
4443        final long identity = Binder.clearCallingIdentity();
4444        try {
4445            return sUserManager.getProfileParent(userId);
4446        } finally {
4447            Binder.restoreCallingIdentity(identity);
4448        }
4449    }
4450
4451    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4452            String resolvedType, int userId) {
4453        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4454        if (resolver != null) {
4455            return resolver.queryIntent(intent, resolvedType, false, userId);
4456        }
4457        return null;
4458    }
4459
4460    @Override
4461    public List<ResolveInfo> queryIntentActivities(Intent intent,
4462            String resolvedType, int flags, int userId) {
4463        if (!sUserManager.exists(userId)) return Collections.emptyList();
4464        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4465        ComponentName comp = intent.getComponent();
4466        if (comp == null) {
4467            if (intent.getSelector() != null) {
4468                intent = intent.getSelector();
4469                comp = intent.getComponent();
4470            }
4471        }
4472
4473        if (comp != null) {
4474            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4475            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4476            if (ai != null) {
4477                final ResolveInfo ri = new ResolveInfo();
4478                ri.activityInfo = ai;
4479                list.add(ri);
4480            }
4481            return list;
4482        }
4483
4484        // reader
4485        synchronized (mPackages) {
4486            final String pkgName = intent.getPackage();
4487            if (pkgName == null) {
4488                List<CrossProfileIntentFilter> matchingFilters =
4489                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4490                // Check for results that need to skip the current profile.
4491                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4492                        resolvedType, flags, userId);
4493                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4494                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4495                    result.add(xpResolveInfo);
4496                    return filterIfNotPrimaryUser(result, userId);
4497                }
4498
4499                // Check for results in the current profile.
4500                List<ResolveInfo> result = mActivities.queryIntent(
4501                        intent, resolvedType, flags, userId);
4502
4503                // Check for cross profile results.
4504                xpResolveInfo = queryCrossProfileIntents(
4505                        matchingFilters, intent, resolvedType, flags, userId);
4506                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4507                    result.add(xpResolveInfo);
4508                    Collections.sort(result, mResolvePrioritySorter);
4509                }
4510                result = filterIfNotPrimaryUser(result, userId);
4511                if (hasWebURI(intent)) {
4512                    CrossProfileDomainInfo xpDomainInfo = null;
4513                    final UserInfo parent = getProfileParent(userId);
4514                    if (parent != null) {
4515                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4516                                flags, userId, parent.id);
4517                    }
4518                    if (xpDomainInfo != null) {
4519                        if (xpResolveInfo != null) {
4520                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4521                            // in the result.
4522                            result.remove(xpResolveInfo);
4523                        }
4524                        if (result.size() == 0) {
4525                            result.add(xpDomainInfo.resolveInfo);
4526                            return result;
4527                        }
4528                    } else if (result.size() <= 1) {
4529                        return result;
4530                    }
4531                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4532                            xpDomainInfo, userId);
4533                    Collections.sort(result, mResolvePrioritySorter);
4534                }
4535                return result;
4536            }
4537            final PackageParser.Package pkg = mPackages.get(pkgName);
4538            if (pkg != null) {
4539                return filterIfNotPrimaryUser(
4540                        mActivities.queryIntentForPackage(
4541                                intent, resolvedType, flags, pkg.activities, userId),
4542                        userId);
4543            }
4544            return new ArrayList<ResolveInfo>();
4545        }
4546    }
4547
4548    private static class CrossProfileDomainInfo {
4549        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4550        ResolveInfo resolveInfo;
4551        /* Best domain verification status of the activities found in the other profile */
4552        int bestDomainVerificationStatus;
4553    }
4554
4555    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4556            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4557        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4558                sourceUserId)) {
4559            return null;
4560        }
4561        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4562                resolvedType, flags, parentUserId);
4563
4564        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4565            return null;
4566        }
4567        CrossProfileDomainInfo result = null;
4568        int size = resultTargetUser.size();
4569        for (int i = 0; i < size; i++) {
4570            ResolveInfo riTargetUser = resultTargetUser.get(i);
4571            // Intent filter verification is only for filters that specify a host. So don't return
4572            // those that handle all web uris.
4573            if (riTargetUser.handleAllWebDataURI) {
4574                continue;
4575            }
4576            String packageName = riTargetUser.activityInfo.packageName;
4577            PackageSetting ps = mSettings.mPackages.get(packageName);
4578            if (ps == null) {
4579                continue;
4580            }
4581            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4582            int status = (int)(verificationState >> 32);
4583            if (result == null) {
4584                result = new CrossProfileDomainInfo();
4585                result.resolveInfo =
4586                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4587                result.bestDomainVerificationStatus = status;
4588            } else {
4589                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4590                        result.bestDomainVerificationStatus);
4591            }
4592        }
4593        return result;
4594    }
4595
4596    /**
4597     * Verification statuses are ordered from the worse to the best, except for
4598     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4599     */
4600    private int bestDomainVerificationStatus(int status1, int status2) {
4601        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4602            return status2;
4603        }
4604        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4605            return status1;
4606        }
4607        return (int) MathUtils.max(status1, status2);
4608    }
4609
4610    private boolean isUserEnabled(int userId) {
4611        long callingId = Binder.clearCallingIdentity();
4612        try {
4613            UserInfo userInfo = sUserManager.getUserInfo(userId);
4614            return userInfo != null && userInfo.isEnabled();
4615        } finally {
4616            Binder.restoreCallingIdentity(callingId);
4617        }
4618    }
4619
4620    /**
4621     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4622     *
4623     * @return filtered list
4624     */
4625    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4626        if (userId == UserHandle.USER_OWNER) {
4627            return resolveInfos;
4628        }
4629        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4630            ResolveInfo info = resolveInfos.get(i);
4631            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4632                resolveInfos.remove(i);
4633            }
4634        }
4635        return resolveInfos;
4636    }
4637
4638    private static boolean hasWebURI(Intent intent) {
4639        if (intent.getData() == null) {
4640            return false;
4641        }
4642        final String scheme = intent.getScheme();
4643        if (TextUtils.isEmpty(scheme)) {
4644            return false;
4645        }
4646        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4647    }
4648
4649    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4650            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4651            int userId) {
4652        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4653
4654        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4655            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4656                    candidates.size());
4657        }
4658
4659        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4660        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4661        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4662        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4663        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4664
4665        synchronized (mPackages) {
4666            final int count = candidates.size();
4667            // First, try to use linked apps. Partition the candidates into four lists:
4668            // one for the final results, one for the "do not use ever", one for "undefined status"
4669            // and finally one for "browser app type".
4670            for (int n=0; n<count; n++) {
4671                ResolveInfo info = candidates.get(n);
4672                String packageName = info.activityInfo.packageName;
4673                PackageSetting ps = mSettings.mPackages.get(packageName);
4674                if (ps != null) {
4675                    // Add to the special match all list (Browser use case)
4676                    if (info.handleAllWebDataURI) {
4677                        matchAllList.add(info);
4678                        continue;
4679                    }
4680                    // Try to get the status from User settings first
4681                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4682                    int status = (int)(packedStatus >> 32);
4683                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4684                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4685                        if (DEBUG_DOMAIN_VERIFICATION) {
4686                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4687                                    + " : linkgen=" + linkGeneration);
4688                        }
4689                        // Use link-enabled generation as preferredOrder, i.e.
4690                        // prefer newly-enabled over earlier-enabled.
4691                        info.preferredOrder = linkGeneration;
4692                        alwaysList.add(info);
4693                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4694                        if (DEBUG_DOMAIN_VERIFICATION) {
4695                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4696                        }
4697                        neverList.add(info);
4698                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4699                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4700                        if (DEBUG_DOMAIN_VERIFICATION) {
4701                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4702                        }
4703                        undefinedList.add(info);
4704                    }
4705                }
4706            }
4707            // First try to add the "always" resolution(s) for the current user, if any
4708            if (alwaysList.size() > 0) {
4709                result.addAll(alwaysList);
4710            // if there is an "always" for the parent user, add it.
4711            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4712                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4713                result.add(xpDomainInfo.resolveInfo);
4714            } else {
4715                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4716                result.addAll(undefinedList);
4717                if (xpDomainInfo != null && (
4718                        xpDomainInfo.bestDomainVerificationStatus
4719                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4720                        || xpDomainInfo.bestDomainVerificationStatus
4721                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4722                    result.add(xpDomainInfo.resolveInfo);
4723                }
4724                // Also add Browsers (all of them or only the default one)
4725                if ((matchFlags & MATCH_ALL) != 0) {
4726                    result.addAll(matchAllList);
4727                } else {
4728                    // Browser/generic handling case.  If there's a default browser, go straight
4729                    // to that (but only if there is no other higher-priority match).
4730                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4731                            UserHandle.myUserId());
4732                    int maxMatchPrio = 0;
4733                    ResolveInfo defaultBrowserMatch = null;
4734                    final int numCandidates = matchAllList.size();
4735                    for (int n = 0; n < numCandidates; n++) {
4736                        ResolveInfo info = matchAllList.get(n);
4737                        // track the highest overall match priority...
4738                        if (info.priority > maxMatchPrio) {
4739                            maxMatchPrio = info.priority;
4740                        }
4741                        // ...and the highest-priority default browser match
4742                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4743                            if (defaultBrowserMatch == null
4744                                    || (defaultBrowserMatch.priority < info.priority)) {
4745                                if (debug) {
4746                                    Slog.v(TAG, "Considering default browser match " + info);
4747                                }
4748                                defaultBrowserMatch = info;
4749                            }
4750                        }
4751                    }
4752                    if (defaultBrowserMatch != null
4753                            && defaultBrowserMatch.priority >= maxMatchPrio
4754                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4755                    {
4756                        if (debug) {
4757                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4758                        }
4759                        result.add(defaultBrowserMatch);
4760                    } else {
4761                        result.addAll(matchAllList);
4762                    }
4763                }
4764
4765                // If there is nothing selected, add all candidates and remove the ones that the user
4766                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4767                if (result.size() == 0) {
4768                    result.addAll(candidates);
4769                    result.removeAll(neverList);
4770                }
4771            }
4772        }
4773        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4774            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4775                    result.size());
4776            for (ResolveInfo info : result) {
4777                Slog.v(TAG, "  + " + info.activityInfo);
4778            }
4779        }
4780        return result;
4781    }
4782
4783    // Returns a packed value as a long:
4784    //
4785    // high 'int'-sized word: link status: undefined/ask/never/always.
4786    // low 'int'-sized word: relative priority among 'always' results.
4787    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4788        long result = ps.getDomainVerificationStatusForUser(userId);
4789        // if none available, get the master status
4790        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4791            if (ps.getIntentFilterVerificationInfo() != null) {
4792                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4793            }
4794        }
4795        return result;
4796    }
4797
4798    private ResolveInfo querySkipCurrentProfileIntents(
4799            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4800            int flags, int sourceUserId) {
4801        if (matchingFilters != null) {
4802            int size = matchingFilters.size();
4803            for (int i = 0; i < size; i ++) {
4804                CrossProfileIntentFilter filter = matchingFilters.get(i);
4805                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4806                    // Checking if there are activities in the target user that can handle the
4807                    // intent.
4808                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4809                            flags, sourceUserId);
4810                    if (resolveInfo != null) {
4811                        return resolveInfo;
4812                    }
4813                }
4814            }
4815        }
4816        return null;
4817    }
4818
4819    // Return matching ResolveInfo if any for skip current profile intent filters.
4820    private ResolveInfo queryCrossProfileIntents(
4821            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4822            int flags, int sourceUserId) {
4823        if (matchingFilters != null) {
4824            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4825            // match the same intent. For performance reasons, it is better not to
4826            // run queryIntent twice for the same userId
4827            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4828            int size = matchingFilters.size();
4829            for (int i = 0; i < size; i++) {
4830                CrossProfileIntentFilter filter = matchingFilters.get(i);
4831                int targetUserId = filter.getTargetUserId();
4832                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4833                        && !alreadyTriedUserIds.get(targetUserId)) {
4834                    // Checking if there are activities in the target user that can handle the
4835                    // intent.
4836                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4837                            flags, sourceUserId);
4838                    if (resolveInfo != null) return resolveInfo;
4839                    alreadyTriedUserIds.put(targetUserId, true);
4840                }
4841            }
4842        }
4843        return null;
4844    }
4845
4846    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4847            String resolvedType, int flags, int sourceUserId) {
4848        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4849                resolvedType, flags, filter.getTargetUserId());
4850        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4851            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4852        }
4853        return null;
4854    }
4855
4856    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4857            int sourceUserId, int targetUserId) {
4858        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4859        String className;
4860        if (targetUserId == UserHandle.USER_OWNER) {
4861            className = FORWARD_INTENT_TO_USER_OWNER;
4862        } else {
4863            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4864        }
4865        ComponentName forwardingActivityComponentName = new ComponentName(
4866                mAndroidApplication.packageName, className);
4867        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4868                sourceUserId);
4869        if (targetUserId == UserHandle.USER_OWNER) {
4870            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4871            forwardingResolveInfo.noResourceId = true;
4872        }
4873        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4874        forwardingResolveInfo.priority = 0;
4875        forwardingResolveInfo.preferredOrder = 0;
4876        forwardingResolveInfo.match = 0;
4877        forwardingResolveInfo.isDefault = true;
4878        forwardingResolveInfo.filter = filter;
4879        forwardingResolveInfo.targetUserId = targetUserId;
4880        return forwardingResolveInfo;
4881    }
4882
4883    @Override
4884    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4885            Intent[] specifics, String[] specificTypes, Intent intent,
4886            String resolvedType, int flags, int userId) {
4887        if (!sUserManager.exists(userId)) return Collections.emptyList();
4888        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4889                false, "query intent activity options");
4890        final String resultsAction = intent.getAction();
4891
4892        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4893                | PackageManager.GET_RESOLVED_FILTER, userId);
4894
4895        if (DEBUG_INTENT_MATCHING) {
4896            Log.v(TAG, "Query " + intent + ": " + results);
4897        }
4898
4899        int specificsPos = 0;
4900        int N;
4901
4902        // todo: note that the algorithm used here is O(N^2).  This
4903        // isn't a problem in our current environment, but if we start running
4904        // into situations where we have more than 5 or 10 matches then this
4905        // should probably be changed to something smarter...
4906
4907        // First we go through and resolve each of the specific items
4908        // that were supplied, taking care of removing any corresponding
4909        // duplicate items in the generic resolve list.
4910        if (specifics != null) {
4911            for (int i=0; i<specifics.length; i++) {
4912                final Intent sintent = specifics[i];
4913                if (sintent == null) {
4914                    continue;
4915                }
4916
4917                if (DEBUG_INTENT_MATCHING) {
4918                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4919                }
4920
4921                String action = sintent.getAction();
4922                if (resultsAction != null && resultsAction.equals(action)) {
4923                    // If this action was explicitly requested, then don't
4924                    // remove things that have it.
4925                    action = null;
4926                }
4927
4928                ResolveInfo ri = null;
4929                ActivityInfo ai = null;
4930
4931                ComponentName comp = sintent.getComponent();
4932                if (comp == null) {
4933                    ri = resolveIntent(
4934                        sintent,
4935                        specificTypes != null ? specificTypes[i] : null,
4936                            flags, userId);
4937                    if (ri == null) {
4938                        continue;
4939                    }
4940                    if (ri == mResolveInfo) {
4941                        // ACK!  Must do something better with this.
4942                    }
4943                    ai = ri.activityInfo;
4944                    comp = new ComponentName(ai.applicationInfo.packageName,
4945                            ai.name);
4946                } else {
4947                    ai = getActivityInfo(comp, flags, userId);
4948                    if (ai == null) {
4949                        continue;
4950                    }
4951                }
4952
4953                // Look for any generic query activities that are duplicates
4954                // of this specific one, and remove them from the results.
4955                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4956                N = results.size();
4957                int j;
4958                for (j=specificsPos; j<N; j++) {
4959                    ResolveInfo sri = results.get(j);
4960                    if ((sri.activityInfo.name.equals(comp.getClassName())
4961                            && sri.activityInfo.applicationInfo.packageName.equals(
4962                                    comp.getPackageName()))
4963                        || (action != null && sri.filter.matchAction(action))) {
4964                        results.remove(j);
4965                        if (DEBUG_INTENT_MATCHING) Log.v(
4966                            TAG, "Removing duplicate item from " + j
4967                            + " due to specific " + specificsPos);
4968                        if (ri == null) {
4969                            ri = sri;
4970                        }
4971                        j--;
4972                        N--;
4973                    }
4974                }
4975
4976                // Add this specific item to its proper place.
4977                if (ri == null) {
4978                    ri = new ResolveInfo();
4979                    ri.activityInfo = ai;
4980                }
4981                results.add(specificsPos, ri);
4982                ri.specificIndex = i;
4983                specificsPos++;
4984            }
4985        }
4986
4987        // Now we go through the remaining generic results and remove any
4988        // duplicate actions that are found here.
4989        N = results.size();
4990        for (int i=specificsPos; i<N-1; i++) {
4991            final ResolveInfo rii = results.get(i);
4992            if (rii.filter == null) {
4993                continue;
4994            }
4995
4996            // Iterate over all of the actions of this result's intent
4997            // filter...  typically this should be just one.
4998            final Iterator<String> it = rii.filter.actionsIterator();
4999            if (it == null) {
5000                continue;
5001            }
5002            while (it.hasNext()) {
5003                final String action = it.next();
5004                if (resultsAction != null && resultsAction.equals(action)) {
5005                    // If this action was explicitly requested, then don't
5006                    // remove things that have it.
5007                    continue;
5008                }
5009                for (int j=i+1; j<N; j++) {
5010                    final ResolveInfo rij = results.get(j);
5011                    if (rij.filter != null && rij.filter.hasAction(action)) {
5012                        results.remove(j);
5013                        if (DEBUG_INTENT_MATCHING) Log.v(
5014                            TAG, "Removing duplicate item from " + j
5015                            + " due to action " + action + " at " + i);
5016                        j--;
5017                        N--;
5018                    }
5019                }
5020            }
5021
5022            // If the caller didn't request filter information, drop it now
5023            // so we don't have to marshall/unmarshall it.
5024            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5025                rii.filter = null;
5026            }
5027        }
5028
5029        // Filter out the caller activity if so requested.
5030        if (caller != null) {
5031            N = results.size();
5032            for (int i=0; i<N; i++) {
5033                ActivityInfo ainfo = results.get(i).activityInfo;
5034                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5035                        && caller.getClassName().equals(ainfo.name)) {
5036                    results.remove(i);
5037                    break;
5038                }
5039            }
5040        }
5041
5042        // If the caller didn't request filter information,
5043        // drop them now so we don't have to
5044        // marshall/unmarshall it.
5045        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5046            N = results.size();
5047            for (int i=0; i<N; i++) {
5048                results.get(i).filter = null;
5049            }
5050        }
5051
5052        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5053        return results;
5054    }
5055
5056    @Override
5057    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5058            int userId) {
5059        if (!sUserManager.exists(userId)) return Collections.emptyList();
5060        ComponentName comp = intent.getComponent();
5061        if (comp == null) {
5062            if (intent.getSelector() != null) {
5063                intent = intent.getSelector();
5064                comp = intent.getComponent();
5065            }
5066        }
5067        if (comp != null) {
5068            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5069            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5070            if (ai != null) {
5071                ResolveInfo ri = new ResolveInfo();
5072                ri.activityInfo = ai;
5073                list.add(ri);
5074            }
5075            return list;
5076        }
5077
5078        // reader
5079        synchronized (mPackages) {
5080            String pkgName = intent.getPackage();
5081            if (pkgName == null) {
5082                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5083            }
5084            final PackageParser.Package pkg = mPackages.get(pkgName);
5085            if (pkg != null) {
5086                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5087                        userId);
5088            }
5089            return null;
5090        }
5091    }
5092
5093    @Override
5094    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5095        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5096        if (!sUserManager.exists(userId)) return null;
5097        if (query != null) {
5098            if (query.size() >= 1) {
5099                // If there is more than one service with the same priority,
5100                // just arbitrarily pick the first one.
5101                return query.get(0);
5102            }
5103        }
5104        return null;
5105    }
5106
5107    @Override
5108    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5109            int userId) {
5110        if (!sUserManager.exists(userId)) return Collections.emptyList();
5111        ComponentName comp = intent.getComponent();
5112        if (comp == null) {
5113            if (intent.getSelector() != null) {
5114                intent = intent.getSelector();
5115                comp = intent.getComponent();
5116            }
5117        }
5118        if (comp != null) {
5119            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5120            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5121            if (si != null) {
5122                final ResolveInfo ri = new ResolveInfo();
5123                ri.serviceInfo = si;
5124                list.add(ri);
5125            }
5126            return list;
5127        }
5128
5129        // reader
5130        synchronized (mPackages) {
5131            String pkgName = intent.getPackage();
5132            if (pkgName == null) {
5133                return mServices.queryIntent(intent, resolvedType, flags, userId);
5134            }
5135            final PackageParser.Package pkg = mPackages.get(pkgName);
5136            if (pkg != null) {
5137                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5138                        userId);
5139            }
5140            return null;
5141        }
5142    }
5143
5144    @Override
5145    public List<ResolveInfo> queryIntentContentProviders(
5146            Intent intent, String resolvedType, int flags, int userId) {
5147        if (!sUserManager.exists(userId)) return Collections.emptyList();
5148        ComponentName comp = intent.getComponent();
5149        if (comp == null) {
5150            if (intent.getSelector() != null) {
5151                intent = intent.getSelector();
5152                comp = intent.getComponent();
5153            }
5154        }
5155        if (comp != null) {
5156            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5157            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5158            if (pi != null) {
5159                final ResolveInfo ri = new ResolveInfo();
5160                ri.providerInfo = pi;
5161                list.add(ri);
5162            }
5163            return list;
5164        }
5165
5166        // reader
5167        synchronized (mPackages) {
5168            String pkgName = intent.getPackage();
5169            if (pkgName == null) {
5170                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5171            }
5172            final PackageParser.Package pkg = mPackages.get(pkgName);
5173            if (pkg != null) {
5174                return mProviders.queryIntentForPackage(
5175                        intent, resolvedType, flags, pkg.providers, userId);
5176            }
5177            return null;
5178        }
5179    }
5180
5181    @Override
5182    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5183        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5184
5185        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5186
5187        // writer
5188        synchronized (mPackages) {
5189            ArrayList<PackageInfo> list;
5190            if (listUninstalled) {
5191                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5192                for (PackageSetting ps : mSettings.mPackages.values()) {
5193                    PackageInfo pi;
5194                    if (ps.pkg != null) {
5195                        pi = generatePackageInfo(ps.pkg, flags, userId);
5196                    } else {
5197                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5198                    }
5199                    if (pi != null) {
5200                        list.add(pi);
5201                    }
5202                }
5203            } else {
5204                list = new ArrayList<PackageInfo>(mPackages.size());
5205                for (PackageParser.Package p : mPackages.values()) {
5206                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5207                    if (pi != null) {
5208                        list.add(pi);
5209                    }
5210                }
5211            }
5212
5213            return new ParceledListSlice<PackageInfo>(list);
5214        }
5215    }
5216
5217    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5218            String[] permissions, boolean[] tmp, int flags, int userId) {
5219        int numMatch = 0;
5220        final PermissionsState permissionsState = ps.getPermissionsState();
5221        for (int i=0; i<permissions.length; i++) {
5222            final String permission = permissions[i];
5223            if (permissionsState.hasPermission(permission, userId)) {
5224                tmp[i] = true;
5225                numMatch++;
5226            } else {
5227                tmp[i] = false;
5228            }
5229        }
5230        if (numMatch == 0) {
5231            return;
5232        }
5233        PackageInfo pi;
5234        if (ps.pkg != null) {
5235            pi = generatePackageInfo(ps.pkg, flags, userId);
5236        } else {
5237            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5238        }
5239        // The above might return null in cases of uninstalled apps or install-state
5240        // skew across users/profiles.
5241        if (pi != null) {
5242            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5243                if (numMatch == permissions.length) {
5244                    pi.requestedPermissions = permissions;
5245                } else {
5246                    pi.requestedPermissions = new String[numMatch];
5247                    numMatch = 0;
5248                    for (int i=0; i<permissions.length; i++) {
5249                        if (tmp[i]) {
5250                            pi.requestedPermissions[numMatch] = permissions[i];
5251                            numMatch++;
5252                        }
5253                    }
5254                }
5255            }
5256            list.add(pi);
5257        }
5258    }
5259
5260    @Override
5261    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5262            String[] permissions, int flags, int userId) {
5263        if (!sUserManager.exists(userId)) return null;
5264        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5265
5266        // writer
5267        synchronized (mPackages) {
5268            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5269            boolean[] tmpBools = new boolean[permissions.length];
5270            if (listUninstalled) {
5271                for (PackageSetting ps : mSettings.mPackages.values()) {
5272                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5273                }
5274            } else {
5275                for (PackageParser.Package pkg : mPackages.values()) {
5276                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5277                    if (ps != null) {
5278                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5279                                userId);
5280                    }
5281                }
5282            }
5283
5284            return new ParceledListSlice<PackageInfo>(list);
5285        }
5286    }
5287
5288    @Override
5289    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5290        if (!sUserManager.exists(userId)) return null;
5291        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5292
5293        // writer
5294        synchronized (mPackages) {
5295            ArrayList<ApplicationInfo> list;
5296            if (listUninstalled) {
5297                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5298                for (PackageSetting ps : mSettings.mPackages.values()) {
5299                    ApplicationInfo ai;
5300                    if (ps.pkg != null) {
5301                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5302                                ps.readUserState(userId), userId);
5303                    } else {
5304                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5305                    }
5306                    if (ai != null) {
5307                        list.add(ai);
5308                    }
5309                }
5310            } else {
5311                list = new ArrayList<ApplicationInfo>(mPackages.size());
5312                for (PackageParser.Package p : mPackages.values()) {
5313                    if (p.mExtras != null) {
5314                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5315                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5316                        if (ai != null) {
5317                            list.add(ai);
5318                        }
5319                    }
5320                }
5321            }
5322
5323            return new ParceledListSlice<ApplicationInfo>(list);
5324        }
5325    }
5326
5327    public List<ApplicationInfo> getPersistentApplications(int flags) {
5328        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5329
5330        // reader
5331        synchronized (mPackages) {
5332            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5333            final int userId = UserHandle.getCallingUserId();
5334            while (i.hasNext()) {
5335                final PackageParser.Package p = i.next();
5336                if (p.applicationInfo != null
5337                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5338                        && (!mSafeMode || isSystemApp(p))) {
5339                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5340                    if (ps != null) {
5341                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5342                                ps.readUserState(userId), userId);
5343                        if (ai != null) {
5344                            finalList.add(ai);
5345                        }
5346                    }
5347                }
5348            }
5349        }
5350
5351        return finalList;
5352    }
5353
5354    @Override
5355    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5356        if (!sUserManager.exists(userId)) return null;
5357        // reader
5358        synchronized (mPackages) {
5359            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5360            PackageSetting ps = provider != null
5361                    ? mSettings.mPackages.get(provider.owner.packageName)
5362                    : null;
5363            return ps != null
5364                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5365                    && (!mSafeMode || (provider.info.applicationInfo.flags
5366                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5367                    ? PackageParser.generateProviderInfo(provider, flags,
5368                            ps.readUserState(userId), userId)
5369                    : null;
5370        }
5371    }
5372
5373    /**
5374     * @deprecated
5375     */
5376    @Deprecated
5377    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5378        // reader
5379        synchronized (mPackages) {
5380            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5381                    .entrySet().iterator();
5382            final int userId = UserHandle.getCallingUserId();
5383            while (i.hasNext()) {
5384                Map.Entry<String, PackageParser.Provider> entry = i.next();
5385                PackageParser.Provider p = entry.getValue();
5386                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5387
5388                if (ps != null && p.syncable
5389                        && (!mSafeMode || (p.info.applicationInfo.flags
5390                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5391                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5392                            ps.readUserState(userId), userId);
5393                    if (info != null) {
5394                        outNames.add(entry.getKey());
5395                        outInfo.add(info);
5396                    }
5397                }
5398            }
5399        }
5400    }
5401
5402    @Override
5403    public List<ProviderInfo> queryContentProviders(String processName,
5404            int uid, int flags) {
5405        ArrayList<ProviderInfo> finalList = null;
5406        // reader
5407        synchronized (mPackages) {
5408            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5409            final int userId = processName != null ?
5410                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5411            while (i.hasNext()) {
5412                final PackageParser.Provider p = i.next();
5413                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5414                if (ps != null && p.info.authority != null
5415                        && (processName == null
5416                                || (p.info.processName.equals(processName)
5417                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5418                        && mSettings.isEnabledLPr(p.info, flags, userId)
5419                        && (!mSafeMode
5420                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5421                    if (finalList == null) {
5422                        finalList = new ArrayList<ProviderInfo>(3);
5423                    }
5424                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5425                            ps.readUserState(userId), userId);
5426                    if (info != null) {
5427                        finalList.add(info);
5428                    }
5429                }
5430            }
5431        }
5432
5433        if (finalList != null) {
5434            Collections.sort(finalList, mProviderInitOrderSorter);
5435        }
5436
5437        return finalList;
5438    }
5439
5440    @Override
5441    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5442            int flags) {
5443        // reader
5444        synchronized (mPackages) {
5445            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5446            return PackageParser.generateInstrumentationInfo(i, flags);
5447        }
5448    }
5449
5450    @Override
5451    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5452            int flags) {
5453        ArrayList<InstrumentationInfo> finalList =
5454            new ArrayList<InstrumentationInfo>();
5455
5456        // reader
5457        synchronized (mPackages) {
5458            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5459            while (i.hasNext()) {
5460                final PackageParser.Instrumentation p = i.next();
5461                if (targetPackage == null
5462                        || targetPackage.equals(p.info.targetPackage)) {
5463                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5464                            flags);
5465                    if (ii != null) {
5466                        finalList.add(ii);
5467                    }
5468                }
5469            }
5470        }
5471
5472        return finalList;
5473    }
5474
5475    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5476        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5477        if (overlays == null) {
5478            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5479            return;
5480        }
5481        for (PackageParser.Package opkg : overlays.values()) {
5482            // Not much to do if idmap fails: we already logged the error
5483            // and we certainly don't want to abort installation of pkg simply
5484            // because an overlay didn't fit properly. For these reasons,
5485            // ignore the return value of createIdmapForPackagePairLI.
5486            createIdmapForPackagePairLI(pkg, opkg);
5487        }
5488    }
5489
5490    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5491            PackageParser.Package opkg) {
5492        if (!opkg.mTrustedOverlay) {
5493            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5494                    opkg.baseCodePath + ": overlay not trusted");
5495            return false;
5496        }
5497        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5498        if (overlaySet == null) {
5499            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5500                    opkg.baseCodePath + " but target package has no known overlays");
5501            return false;
5502        }
5503        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5504        // TODO: generate idmap for split APKs
5505        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5506            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5507                    + opkg.baseCodePath);
5508            return false;
5509        }
5510        PackageParser.Package[] overlayArray =
5511            overlaySet.values().toArray(new PackageParser.Package[0]);
5512        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5513            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5514                return p1.mOverlayPriority - p2.mOverlayPriority;
5515            }
5516        };
5517        Arrays.sort(overlayArray, cmp);
5518
5519        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5520        int i = 0;
5521        for (PackageParser.Package p : overlayArray) {
5522            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5523        }
5524        return true;
5525    }
5526
5527    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5528        final File[] files = dir.listFiles();
5529        if (ArrayUtils.isEmpty(files)) {
5530            Log.d(TAG, "No files in app dir " + dir);
5531            return;
5532        }
5533
5534        if (DEBUG_PACKAGE_SCANNING) {
5535            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5536                    + " flags=0x" + Integer.toHexString(parseFlags));
5537        }
5538
5539        for (File file : files) {
5540            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5541                    && !PackageInstallerService.isStageName(file.getName());
5542            if (!isPackage) {
5543                // Ignore entries which are not packages
5544                continue;
5545            }
5546            try {
5547                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5548                        scanFlags, currentTime, null);
5549            } catch (PackageManagerException e) {
5550                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5551
5552                // Delete invalid userdata apps
5553                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5554                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5555                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5556                    if (file.isDirectory()) {
5557                        mInstaller.rmPackageDir(file.getAbsolutePath());
5558                    } else {
5559                        file.delete();
5560                    }
5561                }
5562            }
5563        }
5564    }
5565
5566    private static File getSettingsProblemFile() {
5567        File dataDir = Environment.getDataDirectory();
5568        File systemDir = new File(dataDir, "system");
5569        File fname = new File(systemDir, "uiderrors.txt");
5570        return fname;
5571    }
5572
5573    static void reportSettingsProblem(int priority, String msg) {
5574        logCriticalInfo(priority, msg);
5575    }
5576
5577    static void logCriticalInfo(int priority, String msg) {
5578        Slog.println(priority, TAG, msg);
5579        EventLogTags.writePmCriticalInfo(msg);
5580        try {
5581            File fname = getSettingsProblemFile();
5582            FileOutputStream out = new FileOutputStream(fname, true);
5583            PrintWriter pw = new FastPrintWriter(out);
5584            SimpleDateFormat formatter = new SimpleDateFormat();
5585            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5586            pw.println(dateString + ": " + msg);
5587            pw.close();
5588            FileUtils.setPermissions(
5589                    fname.toString(),
5590                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5591                    -1, -1);
5592        } catch (java.io.IOException e) {
5593        }
5594    }
5595
5596    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5597            PackageParser.Package pkg, File srcFile, int parseFlags)
5598            throws PackageManagerException {
5599        if (ps != null
5600                && ps.codePath.equals(srcFile)
5601                && ps.timeStamp == srcFile.lastModified()
5602                && !isCompatSignatureUpdateNeeded(pkg)
5603                && !isRecoverSignatureUpdateNeeded(pkg)) {
5604            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5605            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5606            ArraySet<PublicKey> signingKs;
5607            synchronized (mPackages) {
5608                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5609            }
5610            if (ps.signatures.mSignatures != null
5611                    && ps.signatures.mSignatures.length != 0
5612                    && signingKs != null) {
5613                // Optimization: reuse the existing cached certificates
5614                // if the package appears to be unchanged.
5615                pkg.mSignatures = ps.signatures.mSignatures;
5616                pkg.mSigningKeys = signingKs;
5617                return;
5618            }
5619
5620            Slog.w(TAG, "PackageSetting for " + ps.name
5621                    + " is missing signatures.  Collecting certs again to recover them.");
5622        } else {
5623            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5624        }
5625
5626        try {
5627            pp.collectCertificates(pkg, parseFlags);
5628            pp.collectManifestDigest(pkg);
5629        } catch (PackageParserException e) {
5630            throw PackageManagerException.from(e);
5631        }
5632    }
5633
5634    /*
5635     *  Scan a package and return the newly parsed package.
5636     *  Returns null in case of errors and the error code is stored in mLastScanError
5637     */
5638    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5639            long currentTime, UserHandle user) throws PackageManagerException {
5640        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5641        parseFlags |= mDefParseFlags;
5642        PackageParser pp = new PackageParser();
5643        pp.setSeparateProcesses(mSeparateProcesses);
5644        pp.setOnlyCoreApps(mOnlyCore);
5645        pp.setDisplayMetrics(mMetrics);
5646
5647        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5648            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5649        }
5650
5651        final PackageParser.Package pkg;
5652        try {
5653            pkg = pp.parsePackage(scanFile, parseFlags);
5654        } catch (PackageParserException e) {
5655            throw PackageManagerException.from(e);
5656        }
5657
5658        PackageSetting ps = null;
5659        PackageSetting updatedPkg;
5660        // reader
5661        synchronized (mPackages) {
5662            // Look to see if we already know about this package.
5663            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5664            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5665                // This package has been renamed to its original name.  Let's
5666                // use that.
5667                ps = mSettings.peekPackageLPr(oldName);
5668            }
5669            // If there was no original package, see one for the real package name.
5670            if (ps == null) {
5671                ps = mSettings.peekPackageLPr(pkg.packageName);
5672            }
5673            // Check to see if this package could be hiding/updating a system
5674            // package.  Must look for it either under the original or real
5675            // package name depending on our state.
5676            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5677            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5678        }
5679        boolean updatedPkgBetter = false;
5680        // First check if this is a system package that may involve an update
5681        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5682            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5683            // it needs to drop FLAG_PRIVILEGED.
5684            if (locationIsPrivileged(scanFile)) {
5685                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5686            } else {
5687                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5688            }
5689
5690            if (ps != null && !ps.codePath.equals(scanFile)) {
5691                // The path has changed from what was last scanned...  check the
5692                // version of the new path against what we have stored to determine
5693                // what to do.
5694                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5695                if (pkg.mVersionCode <= ps.versionCode) {
5696                    // The system package has been updated and the code path does not match
5697                    // Ignore entry. Skip it.
5698                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5699                            + " ignored: updated version " + ps.versionCode
5700                            + " better than this " + pkg.mVersionCode);
5701                    if (!updatedPkg.codePath.equals(scanFile)) {
5702                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5703                                + ps.name + " changing from " + updatedPkg.codePathString
5704                                + " to " + scanFile);
5705                        updatedPkg.codePath = scanFile;
5706                        updatedPkg.codePathString = scanFile.toString();
5707                        updatedPkg.resourcePath = scanFile;
5708                        updatedPkg.resourcePathString = scanFile.toString();
5709                    }
5710                    updatedPkg.pkg = pkg;
5711                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5712                            "Package " + ps.name + " at " + scanFile
5713                                    + " ignored: updated version " + ps.versionCode
5714                                    + " better than this " + pkg.mVersionCode);
5715                } else {
5716                    // The current app on the system partition is better than
5717                    // what we have updated to on the data partition; switch
5718                    // back to the system partition version.
5719                    // At this point, its safely assumed that package installation for
5720                    // apps in system partition will go through. If not there won't be a working
5721                    // version of the app
5722                    // writer
5723                    synchronized (mPackages) {
5724                        // Just remove the loaded entries from package lists.
5725                        mPackages.remove(ps.name);
5726                    }
5727
5728                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5729                            + " reverting from " + ps.codePathString
5730                            + ": new version " + pkg.mVersionCode
5731                            + " better than installed " + ps.versionCode);
5732
5733                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5734                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5735                    synchronized (mInstallLock) {
5736                        args.cleanUpResourcesLI();
5737                    }
5738                    synchronized (mPackages) {
5739                        mSettings.enableSystemPackageLPw(ps.name);
5740                    }
5741                    updatedPkgBetter = true;
5742                }
5743            }
5744        }
5745
5746        if (updatedPkg != null) {
5747            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5748            // initially
5749            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5750
5751            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5752            // flag set initially
5753            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5754                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5755            }
5756        }
5757
5758        // Verify certificates against what was last scanned
5759        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5760
5761        /*
5762         * A new system app appeared, but we already had a non-system one of the
5763         * same name installed earlier.
5764         */
5765        boolean shouldHideSystemApp = false;
5766        if (updatedPkg == null && ps != null
5767                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5768            /*
5769             * Check to make sure the signatures match first. If they don't,
5770             * wipe the installed application and its data.
5771             */
5772            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5773                    != PackageManager.SIGNATURE_MATCH) {
5774                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5775                        + " signatures don't match existing userdata copy; removing");
5776                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5777                ps = null;
5778            } else {
5779                /*
5780                 * If the newly-added system app is an older version than the
5781                 * already installed version, hide it. It will be scanned later
5782                 * and re-added like an update.
5783                 */
5784                if (pkg.mVersionCode <= ps.versionCode) {
5785                    shouldHideSystemApp = true;
5786                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5787                            + " but new version " + pkg.mVersionCode + " better than installed "
5788                            + ps.versionCode + "; hiding system");
5789                } else {
5790                    /*
5791                     * The newly found system app is a newer version that the
5792                     * one previously installed. Simply remove the
5793                     * already-installed application and replace it with our own
5794                     * while keeping the application data.
5795                     */
5796                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5797                            + " reverting from " + ps.codePathString + ": new version "
5798                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5799                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5800                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5801                    synchronized (mInstallLock) {
5802                        args.cleanUpResourcesLI();
5803                    }
5804                }
5805            }
5806        }
5807
5808        // The apk is forward locked (not public) if its code and resources
5809        // are kept in different files. (except for app in either system or
5810        // vendor path).
5811        // TODO grab this value from PackageSettings
5812        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5813            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5814                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5815            }
5816        }
5817
5818        // TODO: extend to support forward-locked splits
5819        String resourcePath = null;
5820        String baseResourcePath = null;
5821        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5822            if (ps != null && ps.resourcePathString != null) {
5823                resourcePath = ps.resourcePathString;
5824                baseResourcePath = ps.resourcePathString;
5825            } else {
5826                // Should not happen at all. Just log an error.
5827                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5828            }
5829        } else {
5830            resourcePath = pkg.codePath;
5831            baseResourcePath = pkg.baseCodePath;
5832        }
5833
5834        // Set application objects path explicitly.
5835        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5836        pkg.applicationInfo.setCodePath(pkg.codePath);
5837        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5838        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5839        pkg.applicationInfo.setResourcePath(resourcePath);
5840        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5841        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5842
5843        // Note that we invoke the following method only if we are about to unpack an application
5844        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5845                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5846
5847        /*
5848         * If the system app should be overridden by a previously installed
5849         * data, hide the system app now and let the /data/app scan pick it up
5850         * again.
5851         */
5852        if (shouldHideSystemApp) {
5853            synchronized (mPackages) {
5854                /*
5855                 * We have to grant systems permissions before we hide, because
5856                 * grantPermissions will assume the package update is trying to
5857                 * expand its permissions.
5858                 */
5859                grantPermissionsLPw(pkg, true, pkg.packageName);
5860                mSettings.disableSystemPackageLPw(pkg.packageName);
5861            }
5862        }
5863
5864        return scannedPkg;
5865    }
5866
5867    private static String fixProcessName(String defProcessName,
5868            String processName, int uid) {
5869        if (processName == null) {
5870            return defProcessName;
5871        }
5872        return processName;
5873    }
5874
5875    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5876            throws PackageManagerException {
5877        if (pkgSetting.signatures.mSignatures != null) {
5878            // Already existing package. Make sure signatures match
5879            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5880                    == PackageManager.SIGNATURE_MATCH;
5881            if (!match) {
5882                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5883                        == PackageManager.SIGNATURE_MATCH;
5884            }
5885            if (!match) {
5886                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5887                        == PackageManager.SIGNATURE_MATCH;
5888            }
5889            if (!match) {
5890                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5891                        + pkg.packageName + " signatures do not match the "
5892                        + "previously installed version; ignoring!");
5893            }
5894        }
5895
5896        // Check for shared user signatures
5897        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5898            // Already existing package. Make sure signatures match
5899            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5900                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5901            if (!match) {
5902                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5903                        == PackageManager.SIGNATURE_MATCH;
5904            }
5905            if (!match) {
5906                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5907                        == PackageManager.SIGNATURE_MATCH;
5908            }
5909            if (!match) {
5910                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5911                        "Package " + pkg.packageName
5912                        + " has no signatures that match those in shared user "
5913                        + pkgSetting.sharedUser.name + "; ignoring!");
5914            }
5915        }
5916    }
5917
5918    /**
5919     * Enforces that only the system UID or root's UID can call a method exposed
5920     * via Binder.
5921     *
5922     * @param message used as message if SecurityException is thrown
5923     * @throws SecurityException if the caller is not system or root
5924     */
5925    private static final void enforceSystemOrRoot(String message) {
5926        final int uid = Binder.getCallingUid();
5927        if (uid != Process.SYSTEM_UID && uid != 0) {
5928            throw new SecurityException(message);
5929        }
5930    }
5931
5932    @Override
5933    public void performBootDexOpt() {
5934        enforceSystemOrRoot("Only the system can request dexopt be performed");
5935
5936        // Before everything else, see whether we need to fstrim.
5937        try {
5938            IMountService ms = PackageHelper.getMountService();
5939            if (ms != null) {
5940                final boolean isUpgrade = isUpgrade();
5941                boolean doTrim = isUpgrade;
5942                if (doTrim) {
5943                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5944                } else {
5945                    final long interval = android.provider.Settings.Global.getLong(
5946                            mContext.getContentResolver(),
5947                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5948                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5949                    if (interval > 0) {
5950                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5951                        if (timeSinceLast > interval) {
5952                            doTrim = true;
5953                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5954                                    + "; running immediately");
5955                        }
5956                    }
5957                }
5958                if (doTrim) {
5959                    if (!isFirstBoot()) {
5960                        try {
5961                            ActivityManagerNative.getDefault().showBootMessage(
5962                                    mContext.getResources().getString(
5963                                            R.string.android_upgrading_fstrim), true);
5964                        } catch (RemoteException e) {
5965                        }
5966                    }
5967                    ms.runMaintenance();
5968                }
5969            } else {
5970                Slog.e(TAG, "Mount service unavailable!");
5971            }
5972        } catch (RemoteException e) {
5973            // Can't happen; MountService is local
5974        }
5975
5976        final ArraySet<PackageParser.Package> pkgs;
5977        synchronized (mPackages) {
5978            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5979        }
5980
5981        if (pkgs != null) {
5982            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5983            // in case the device runs out of space.
5984            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5985            // Give priority to core apps.
5986            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5987                PackageParser.Package pkg = it.next();
5988                if (pkg.coreApp) {
5989                    if (DEBUG_DEXOPT) {
5990                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5991                    }
5992                    sortedPkgs.add(pkg);
5993                    it.remove();
5994                }
5995            }
5996            // Give priority to system apps that listen for pre boot complete.
5997            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5998            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5999            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6000                PackageParser.Package pkg = it.next();
6001                if (pkgNames.contains(pkg.packageName)) {
6002                    if (DEBUG_DEXOPT) {
6003                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6004                    }
6005                    sortedPkgs.add(pkg);
6006                    it.remove();
6007                }
6008            }
6009            // Give priority to system apps.
6010            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6011                PackageParser.Package pkg = it.next();
6012                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6013                    if (DEBUG_DEXOPT) {
6014                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6015                    }
6016                    sortedPkgs.add(pkg);
6017                    it.remove();
6018                }
6019            }
6020            // Give priority to updated system apps.
6021            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6022                PackageParser.Package pkg = it.next();
6023                if (pkg.isUpdatedSystemApp()) {
6024                    if (DEBUG_DEXOPT) {
6025                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6026                    }
6027                    sortedPkgs.add(pkg);
6028                    it.remove();
6029                }
6030            }
6031            // Give priority to apps that listen for boot complete.
6032            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6033            pkgNames = getPackageNamesForIntent(intent);
6034            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6035                PackageParser.Package pkg = it.next();
6036                if (pkgNames.contains(pkg.packageName)) {
6037                    if (DEBUG_DEXOPT) {
6038                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6039                    }
6040                    sortedPkgs.add(pkg);
6041                    it.remove();
6042                }
6043            }
6044            // Filter out packages that aren't recently used.
6045            filterRecentlyUsedApps(pkgs);
6046            // Add all remaining apps.
6047            for (PackageParser.Package pkg : pkgs) {
6048                if (DEBUG_DEXOPT) {
6049                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6050                }
6051                sortedPkgs.add(pkg);
6052            }
6053
6054            // If we want to be lazy, filter everything that wasn't recently used.
6055            if (mLazyDexOpt) {
6056                filterRecentlyUsedApps(sortedPkgs);
6057            }
6058
6059            int i = 0;
6060            int total = sortedPkgs.size();
6061            File dataDir = Environment.getDataDirectory();
6062            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6063            if (lowThreshold == 0) {
6064                throw new IllegalStateException("Invalid low memory threshold");
6065            }
6066            for (PackageParser.Package pkg : sortedPkgs) {
6067                long usableSpace = dataDir.getUsableSpace();
6068                if (usableSpace < lowThreshold) {
6069                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6070                    break;
6071                }
6072                performBootDexOpt(pkg, ++i, total);
6073            }
6074        }
6075    }
6076
6077    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6078        // Filter out packages that aren't recently used.
6079        //
6080        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6081        // should do a full dexopt.
6082        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6083            int total = pkgs.size();
6084            int skipped = 0;
6085            long now = System.currentTimeMillis();
6086            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6087                PackageParser.Package pkg = i.next();
6088                long then = pkg.mLastPackageUsageTimeInMills;
6089                if (then + mDexOptLRUThresholdInMills < now) {
6090                    if (DEBUG_DEXOPT) {
6091                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6092                              ((then == 0) ? "never" : new Date(then)));
6093                    }
6094                    i.remove();
6095                    skipped++;
6096                }
6097            }
6098            if (DEBUG_DEXOPT) {
6099                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6100            }
6101        }
6102    }
6103
6104    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6105        List<ResolveInfo> ris = null;
6106        try {
6107            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6108                    intent, null, 0, UserHandle.USER_OWNER);
6109        } catch (RemoteException e) {
6110        }
6111        ArraySet<String> pkgNames = new ArraySet<String>();
6112        if (ris != null) {
6113            for (ResolveInfo ri : ris) {
6114                pkgNames.add(ri.activityInfo.packageName);
6115            }
6116        }
6117        return pkgNames;
6118    }
6119
6120    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6121        if (DEBUG_DEXOPT) {
6122            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6123        }
6124        if (!isFirstBoot()) {
6125            try {
6126                ActivityManagerNative.getDefault().showBootMessage(
6127                        mContext.getResources().getString(R.string.android_upgrading_apk,
6128                                curr, total), true);
6129            } catch (RemoteException e) {
6130            }
6131        }
6132        PackageParser.Package p = pkg;
6133        synchronized (mInstallLock) {
6134            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6135                    false /* force dex */, false /* defer */, true /* include dependencies */);
6136        }
6137    }
6138
6139    @Override
6140    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6141        return performDexOpt(packageName, instructionSet, false);
6142    }
6143
6144    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6145        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6146        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6147        if (!dexopt && !updateUsage) {
6148            // We aren't going to dexopt or update usage, so bail early.
6149            return false;
6150        }
6151        PackageParser.Package p;
6152        final String targetInstructionSet;
6153        synchronized (mPackages) {
6154            p = mPackages.get(packageName);
6155            if (p == null) {
6156                return false;
6157            }
6158            if (updateUsage) {
6159                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6160            }
6161            mPackageUsage.write(false);
6162            if (!dexopt) {
6163                // We aren't going to dexopt, so bail early.
6164                return false;
6165            }
6166
6167            targetInstructionSet = instructionSet != null ? instructionSet :
6168                    getPrimaryInstructionSet(p.applicationInfo);
6169            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6170                return false;
6171            }
6172        }
6173
6174        synchronized (mInstallLock) {
6175            final String[] instructionSets = new String[] { targetInstructionSet };
6176            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6177                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
6178            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6179        }
6180    }
6181
6182    public ArraySet<String> getPackagesThatNeedDexOpt() {
6183        ArraySet<String> pkgs = null;
6184        synchronized (mPackages) {
6185            for (PackageParser.Package p : mPackages.values()) {
6186                if (DEBUG_DEXOPT) {
6187                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6188                }
6189                if (!p.mDexOptPerformed.isEmpty()) {
6190                    continue;
6191                }
6192                if (pkgs == null) {
6193                    pkgs = new ArraySet<String>();
6194                }
6195                pkgs.add(p.packageName);
6196            }
6197        }
6198        return pkgs;
6199    }
6200
6201    public void shutdown() {
6202        mPackageUsage.write(true);
6203    }
6204
6205    @Override
6206    public void forceDexOpt(String packageName) {
6207        enforceSystemOrRoot("forceDexOpt");
6208
6209        PackageParser.Package pkg;
6210        synchronized (mPackages) {
6211            pkg = mPackages.get(packageName);
6212            if (pkg == null) {
6213                throw new IllegalArgumentException("Missing package: " + packageName);
6214            }
6215        }
6216
6217        synchronized (mInstallLock) {
6218            final String[] instructionSets = new String[] {
6219                    getPrimaryInstructionSet(pkg.applicationInfo) };
6220            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6221                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6222            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6223                throw new IllegalStateException("Failed to dexopt: " + res);
6224            }
6225        }
6226    }
6227
6228    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6229        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6230            Slog.w(TAG, "Unable to update from " + oldPkg.name
6231                    + " to " + newPkg.packageName
6232                    + ": old package not in system partition");
6233            return false;
6234        } else if (mPackages.get(oldPkg.name) != null) {
6235            Slog.w(TAG, "Unable to update from " + oldPkg.name
6236                    + " to " + newPkg.packageName
6237                    + ": old package still exists");
6238            return false;
6239        }
6240        return true;
6241    }
6242
6243    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6244        int[] users = sUserManager.getUserIds();
6245        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6246        if (res < 0) {
6247            return res;
6248        }
6249        for (int user : users) {
6250            if (user != 0) {
6251                res = mInstaller.createUserData(volumeUuid, packageName,
6252                        UserHandle.getUid(user, uid), user, seinfo);
6253                if (res < 0) {
6254                    return res;
6255                }
6256            }
6257        }
6258        return res;
6259    }
6260
6261    private int removeDataDirsLI(String volumeUuid, String packageName) {
6262        int[] users = sUserManager.getUserIds();
6263        int res = 0;
6264        for (int user : users) {
6265            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6266            if (resInner < 0) {
6267                res = resInner;
6268            }
6269        }
6270
6271        return res;
6272    }
6273
6274    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6275        int[] users = sUserManager.getUserIds();
6276        int res = 0;
6277        for (int user : users) {
6278            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6279            if (resInner < 0) {
6280                res = resInner;
6281            }
6282        }
6283        return res;
6284    }
6285
6286    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6287            PackageParser.Package changingLib) {
6288        if (file.path != null) {
6289            usesLibraryFiles.add(file.path);
6290            return;
6291        }
6292        PackageParser.Package p = mPackages.get(file.apk);
6293        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6294            // If we are doing this while in the middle of updating a library apk,
6295            // then we need to make sure to use that new apk for determining the
6296            // dependencies here.  (We haven't yet finished committing the new apk
6297            // to the package manager state.)
6298            if (p == null || p.packageName.equals(changingLib.packageName)) {
6299                p = changingLib;
6300            }
6301        }
6302        if (p != null) {
6303            usesLibraryFiles.addAll(p.getAllCodePaths());
6304        }
6305    }
6306
6307    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6308            PackageParser.Package changingLib) throws PackageManagerException {
6309        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6310            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6311            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6312            for (int i=0; i<N; i++) {
6313                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6314                if (file == null) {
6315                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6316                            "Package " + pkg.packageName + " requires unavailable shared library "
6317                            + pkg.usesLibraries.get(i) + "; failing!");
6318                }
6319                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6320            }
6321            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6322            for (int i=0; i<N; i++) {
6323                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6324                if (file == null) {
6325                    Slog.w(TAG, "Package " + pkg.packageName
6326                            + " desires unavailable shared library "
6327                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6328                } else {
6329                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6330                }
6331            }
6332            N = usesLibraryFiles.size();
6333            if (N > 0) {
6334                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6335            } else {
6336                pkg.usesLibraryFiles = null;
6337            }
6338        }
6339    }
6340
6341    private static boolean hasString(List<String> list, List<String> which) {
6342        if (list == null) {
6343            return false;
6344        }
6345        for (int i=list.size()-1; i>=0; i--) {
6346            for (int j=which.size()-1; j>=0; j--) {
6347                if (which.get(j).equals(list.get(i))) {
6348                    return true;
6349                }
6350            }
6351        }
6352        return false;
6353    }
6354
6355    private void updateAllSharedLibrariesLPw() {
6356        for (PackageParser.Package pkg : mPackages.values()) {
6357            try {
6358                updateSharedLibrariesLPw(pkg, null);
6359            } catch (PackageManagerException e) {
6360                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6361            }
6362        }
6363    }
6364
6365    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6366            PackageParser.Package changingPkg) {
6367        ArrayList<PackageParser.Package> res = null;
6368        for (PackageParser.Package pkg : mPackages.values()) {
6369            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6370                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6371                if (res == null) {
6372                    res = new ArrayList<PackageParser.Package>();
6373                }
6374                res.add(pkg);
6375                try {
6376                    updateSharedLibrariesLPw(pkg, changingPkg);
6377                } catch (PackageManagerException e) {
6378                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6379                }
6380            }
6381        }
6382        return res;
6383    }
6384
6385    /**
6386     * Derive the value of the {@code cpuAbiOverride} based on the provided
6387     * value and an optional stored value from the package settings.
6388     */
6389    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6390        String cpuAbiOverride = null;
6391
6392        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6393            cpuAbiOverride = null;
6394        } else if (abiOverride != null) {
6395            cpuAbiOverride = abiOverride;
6396        } else if (settings != null) {
6397            cpuAbiOverride = settings.cpuAbiOverrideString;
6398        }
6399
6400        return cpuAbiOverride;
6401    }
6402
6403    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6404            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6405        boolean success = false;
6406        try {
6407            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6408                    currentTime, user);
6409            success = true;
6410            return res;
6411        } finally {
6412            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6413                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6414            }
6415        }
6416    }
6417
6418    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6419            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6420        final File scanFile = new File(pkg.codePath);
6421        if (pkg.applicationInfo.getCodePath() == null ||
6422                pkg.applicationInfo.getResourcePath() == null) {
6423            // Bail out. The resource and code paths haven't been set.
6424            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6425                    "Code and resource paths haven't been set correctly");
6426        }
6427
6428        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6429            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6430        } else {
6431            // Only allow system apps to be flagged as core apps.
6432            pkg.coreApp = false;
6433        }
6434
6435        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6436            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6437        }
6438
6439        if (mCustomResolverComponentName != null &&
6440                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6441            setUpCustomResolverActivity(pkg);
6442        }
6443
6444        if (pkg.packageName.equals("android")) {
6445            synchronized (mPackages) {
6446                if (mAndroidApplication != null) {
6447                    Slog.w(TAG, "*************************************************");
6448                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6449                    Slog.w(TAG, " file=" + scanFile);
6450                    Slog.w(TAG, "*************************************************");
6451                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6452                            "Core android package being redefined.  Skipping.");
6453                }
6454
6455                // Set up information for our fall-back user intent resolution activity.
6456                mPlatformPackage = pkg;
6457                pkg.mVersionCode = mSdkVersion;
6458                mAndroidApplication = pkg.applicationInfo;
6459
6460                if (!mResolverReplaced) {
6461                    mResolveActivity.applicationInfo = mAndroidApplication;
6462                    mResolveActivity.name = ResolverActivity.class.getName();
6463                    mResolveActivity.packageName = mAndroidApplication.packageName;
6464                    mResolveActivity.processName = "system:ui";
6465                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6466                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6467                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6468                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6469                    mResolveActivity.exported = true;
6470                    mResolveActivity.enabled = true;
6471                    mResolveInfo.activityInfo = mResolveActivity;
6472                    mResolveInfo.priority = 0;
6473                    mResolveInfo.preferredOrder = 0;
6474                    mResolveInfo.match = 0;
6475                    mResolveComponentName = new ComponentName(
6476                            mAndroidApplication.packageName, mResolveActivity.name);
6477                }
6478            }
6479        }
6480
6481        if (DEBUG_PACKAGE_SCANNING) {
6482            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6483                Log.d(TAG, "Scanning package " + pkg.packageName);
6484        }
6485
6486        if (mPackages.containsKey(pkg.packageName)
6487                || mSharedLibraries.containsKey(pkg.packageName)) {
6488            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6489                    "Application package " + pkg.packageName
6490                    + " already installed.  Skipping duplicate.");
6491        }
6492
6493        // If we're only installing presumed-existing packages, require that the
6494        // scanned APK is both already known and at the path previously established
6495        // for it.  Previously unknown packages we pick up normally, but if we have an
6496        // a priori expectation about this package's install presence, enforce it.
6497        // With a singular exception for new system packages. When an OTA contains
6498        // a new system package, we allow the codepath to change from a system location
6499        // to the user-installed location. If we don't allow this change, any newer,
6500        // user-installed version of the application will be ignored.
6501        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6502            if (mExpectingBetter.containsKey(pkg.packageName)) {
6503                logCriticalInfo(Log.WARN,
6504                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6505            } else {
6506                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6507                if (known != null) {
6508                    if (DEBUG_PACKAGE_SCANNING) {
6509                        Log.d(TAG, "Examining " + pkg.codePath
6510                                + " and requiring known paths " + known.codePathString
6511                                + " & " + known.resourcePathString);
6512                    }
6513                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6514                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6515                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6516                                "Application package " + pkg.packageName
6517                                + " found at " + pkg.applicationInfo.getCodePath()
6518                                + " but expected at " + known.codePathString + "; ignoring.");
6519                    }
6520                }
6521            }
6522        }
6523
6524        // Initialize package source and resource directories
6525        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6526        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6527
6528        SharedUserSetting suid = null;
6529        PackageSetting pkgSetting = null;
6530
6531        if (!isSystemApp(pkg)) {
6532            // Only system apps can use these features.
6533            pkg.mOriginalPackages = null;
6534            pkg.mRealPackage = null;
6535            pkg.mAdoptPermissions = null;
6536        }
6537
6538        // writer
6539        synchronized (mPackages) {
6540            if (pkg.mSharedUserId != null) {
6541                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6542                if (suid == null) {
6543                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6544                            "Creating application package " + pkg.packageName
6545                            + " for shared user failed");
6546                }
6547                if (DEBUG_PACKAGE_SCANNING) {
6548                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6549                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6550                                + "): packages=" + suid.packages);
6551                }
6552            }
6553
6554            // Check if we are renaming from an original package name.
6555            PackageSetting origPackage = null;
6556            String realName = null;
6557            if (pkg.mOriginalPackages != null) {
6558                // This package may need to be renamed to a previously
6559                // installed name.  Let's check on that...
6560                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6561                if (pkg.mOriginalPackages.contains(renamed)) {
6562                    // This package had originally been installed as the
6563                    // original name, and we have already taken care of
6564                    // transitioning to the new one.  Just update the new
6565                    // one to continue using the old name.
6566                    realName = pkg.mRealPackage;
6567                    if (!pkg.packageName.equals(renamed)) {
6568                        // Callers into this function may have already taken
6569                        // care of renaming the package; only do it here if
6570                        // it is not already done.
6571                        pkg.setPackageName(renamed);
6572                    }
6573
6574                } else {
6575                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6576                        if ((origPackage = mSettings.peekPackageLPr(
6577                                pkg.mOriginalPackages.get(i))) != null) {
6578                            // We do have the package already installed under its
6579                            // original name...  should we use it?
6580                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6581                                // New package is not compatible with original.
6582                                origPackage = null;
6583                                continue;
6584                            } else if (origPackage.sharedUser != null) {
6585                                // Make sure uid is compatible between packages.
6586                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6587                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6588                                            + " to " + pkg.packageName + ": old uid "
6589                                            + origPackage.sharedUser.name
6590                                            + " differs from " + pkg.mSharedUserId);
6591                                    origPackage = null;
6592                                    continue;
6593                                }
6594                            } else {
6595                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6596                                        + pkg.packageName + " to old name " + origPackage.name);
6597                            }
6598                            break;
6599                        }
6600                    }
6601                }
6602            }
6603
6604            if (mTransferedPackages.contains(pkg.packageName)) {
6605                Slog.w(TAG, "Package " + pkg.packageName
6606                        + " was transferred to another, but its .apk remains");
6607            }
6608
6609            // Just create the setting, don't add it yet. For already existing packages
6610            // the PkgSetting exists already and doesn't have to be created.
6611            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6612                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6613                    pkg.applicationInfo.primaryCpuAbi,
6614                    pkg.applicationInfo.secondaryCpuAbi,
6615                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6616                    user, false);
6617            if (pkgSetting == null) {
6618                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6619                        "Creating application package " + pkg.packageName + " failed");
6620            }
6621
6622            if (pkgSetting.origPackage != null) {
6623                // If we are first transitioning from an original package,
6624                // fix up the new package's name now.  We need to do this after
6625                // looking up the package under its new name, so getPackageLP
6626                // can take care of fiddling things correctly.
6627                pkg.setPackageName(origPackage.name);
6628
6629                // File a report about this.
6630                String msg = "New package " + pkgSetting.realName
6631                        + " renamed to replace old package " + pkgSetting.name;
6632                reportSettingsProblem(Log.WARN, msg);
6633
6634                // Make a note of it.
6635                mTransferedPackages.add(origPackage.name);
6636
6637                // No longer need to retain this.
6638                pkgSetting.origPackage = null;
6639            }
6640
6641            if (realName != null) {
6642                // Make a note of it.
6643                mTransferedPackages.add(pkg.packageName);
6644            }
6645
6646            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6647                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6648            }
6649
6650            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6651                // Check all shared libraries and map to their actual file path.
6652                // We only do this here for apps not on a system dir, because those
6653                // are the only ones that can fail an install due to this.  We
6654                // will take care of the system apps by updating all of their
6655                // library paths after the scan is done.
6656                updateSharedLibrariesLPw(pkg, null);
6657            }
6658
6659            if (mFoundPolicyFile) {
6660                SELinuxMMAC.assignSeinfoValue(pkg);
6661            }
6662
6663            pkg.applicationInfo.uid = pkgSetting.appId;
6664            pkg.mExtras = pkgSetting;
6665            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6666                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6667                    // We just determined the app is signed correctly, so bring
6668                    // over the latest parsed certs.
6669                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6670                } else {
6671                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6672                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6673                                "Package " + pkg.packageName + " upgrade keys do not match the "
6674                                + "previously installed version");
6675                    } else {
6676                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6677                        String msg = "System package " + pkg.packageName
6678                            + " signature changed; retaining data.";
6679                        reportSettingsProblem(Log.WARN, msg);
6680                    }
6681                }
6682            } else {
6683                try {
6684                    verifySignaturesLP(pkgSetting, pkg);
6685                    // We just determined the app is signed correctly, so bring
6686                    // over the latest parsed certs.
6687                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6688                } catch (PackageManagerException e) {
6689                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6690                        throw e;
6691                    }
6692                    // The signature has changed, but this package is in the system
6693                    // image...  let's recover!
6694                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6695                    // However...  if this package is part of a shared user, but it
6696                    // doesn't match the signature of the shared user, let's fail.
6697                    // What this means is that you can't change the signatures
6698                    // associated with an overall shared user, which doesn't seem all
6699                    // that unreasonable.
6700                    if (pkgSetting.sharedUser != null) {
6701                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6702                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6703                            throw new PackageManagerException(
6704                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6705                                            "Signature mismatch for shared user : "
6706                                            + pkgSetting.sharedUser);
6707                        }
6708                    }
6709                    // File a report about this.
6710                    String msg = "System package " + pkg.packageName
6711                        + " signature changed; retaining data.";
6712                    reportSettingsProblem(Log.WARN, msg);
6713                }
6714            }
6715            // Verify that this new package doesn't have any content providers
6716            // that conflict with existing packages.  Only do this if the
6717            // package isn't already installed, since we don't want to break
6718            // things that are installed.
6719            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6720                final int N = pkg.providers.size();
6721                int i;
6722                for (i=0; i<N; i++) {
6723                    PackageParser.Provider p = pkg.providers.get(i);
6724                    if (p.info.authority != null) {
6725                        String names[] = p.info.authority.split(";");
6726                        for (int j = 0; j < names.length; j++) {
6727                            if (mProvidersByAuthority.containsKey(names[j])) {
6728                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6729                                final String otherPackageName =
6730                                        ((other != null && other.getComponentName() != null) ?
6731                                                other.getComponentName().getPackageName() : "?");
6732                                throw new PackageManagerException(
6733                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6734                                                "Can't install because provider name " + names[j]
6735                                                + " (in package " + pkg.applicationInfo.packageName
6736                                                + ") is already used by " + otherPackageName);
6737                            }
6738                        }
6739                    }
6740                }
6741            }
6742
6743            if (pkg.mAdoptPermissions != null) {
6744                // This package wants to adopt ownership of permissions from
6745                // another package.
6746                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6747                    final String origName = pkg.mAdoptPermissions.get(i);
6748                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6749                    if (orig != null) {
6750                        if (verifyPackageUpdateLPr(orig, pkg)) {
6751                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6752                                    + pkg.packageName);
6753                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6754                        }
6755                    }
6756                }
6757            }
6758        }
6759
6760        final String pkgName = pkg.packageName;
6761
6762        final long scanFileTime = scanFile.lastModified();
6763        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6764        pkg.applicationInfo.processName = fixProcessName(
6765                pkg.applicationInfo.packageName,
6766                pkg.applicationInfo.processName,
6767                pkg.applicationInfo.uid);
6768
6769        File dataPath;
6770        if (mPlatformPackage == pkg) {
6771            // The system package is special.
6772            dataPath = new File(Environment.getDataDirectory(), "system");
6773
6774            pkg.applicationInfo.dataDir = dataPath.getPath();
6775
6776        } else {
6777            // This is a normal package, need to make its data directory.
6778            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6779                    UserHandle.USER_OWNER, pkg.packageName);
6780
6781            boolean uidError = false;
6782            if (dataPath.exists()) {
6783                int currentUid = 0;
6784                try {
6785                    StructStat stat = Os.stat(dataPath.getPath());
6786                    currentUid = stat.st_uid;
6787                } catch (ErrnoException e) {
6788                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6789                }
6790
6791                // If we have mismatched owners for the data path, we have a problem.
6792                if (currentUid != pkg.applicationInfo.uid) {
6793                    boolean recovered = false;
6794                    if (currentUid == 0) {
6795                        // The directory somehow became owned by root.  Wow.
6796                        // This is probably because the system was stopped while
6797                        // installd was in the middle of messing with its libs
6798                        // directory.  Ask installd to fix that.
6799                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6800                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6801                        if (ret >= 0) {
6802                            recovered = true;
6803                            String msg = "Package " + pkg.packageName
6804                                    + " unexpectedly changed to uid 0; recovered to " +
6805                                    + pkg.applicationInfo.uid;
6806                            reportSettingsProblem(Log.WARN, msg);
6807                        }
6808                    }
6809                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6810                            || (scanFlags&SCAN_BOOTING) != 0)) {
6811                        // If this is a system app, we can at least delete its
6812                        // current data so the application will still work.
6813                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6814                        if (ret >= 0) {
6815                            // TODO: Kill the processes first
6816                            // Old data gone!
6817                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6818                                    ? "System package " : "Third party package ";
6819                            String msg = prefix + pkg.packageName
6820                                    + " has changed from uid: "
6821                                    + currentUid + " to "
6822                                    + pkg.applicationInfo.uid + "; old data erased";
6823                            reportSettingsProblem(Log.WARN, msg);
6824                            recovered = true;
6825
6826                            // And now re-install the app.
6827                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6828                                    pkg.applicationInfo.seinfo);
6829                            if (ret == -1) {
6830                                // Ack should not happen!
6831                                msg = prefix + pkg.packageName
6832                                        + " could not have data directory re-created after delete.";
6833                                reportSettingsProblem(Log.WARN, msg);
6834                                throw new PackageManagerException(
6835                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6836                            }
6837                        }
6838                        if (!recovered) {
6839                            mHasSystemUidErrors = true;
6840                        }
6841                    } else if (!recovered) {
6842                        // If we allow this install to proceed, we will be broken.
6843                        // Abort, abort!
6844                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6845                                "scanPackageLI");
6846                    }
6847                    if (!recovered) {
6848                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6849                            + pkg.applicationInfo.uid + "/fs_"
6850                            + currentUid;
6851                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6852                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6853                        String msg = "Package " + pkg.packageName
6854                                + " has mismatched uid: "
6855                                + currentUid + " on disk, "
6856                                + pkg.applicationInfo.uid + " in settings";
6857                        // writer
6858                        synchronized (mPackages) {
6859                            mSettings.mReadMessages.append(msg);
6860                            mSettings.mReadMessages.append('\n');
6861                            uidError = true;
6862                            if (!pkgSetting.uidError) {
6863                                reportSettingsProblem(Log.ERROR, msg);
6864                            }
6865                        }
6866                    }
6867                }
6868                pkg.applicationInfo.dataDir = dataPath.getPath();
6869                if (mShouldRestoreconData) {
6870                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6871                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6872                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6873                }
6874            } else {
6875                if (DEBUG_PACKAGE_SCANNING) {
6876                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6877                        Log.v(TAG, "Want this data dir: " + dataPath);
6878                }
6879                //invoke installer to do the actual installation
6880                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6881                        pkg.applicationInfo.seinfo);
6882                if (ret < 0) {
6883                    // Error from installer
6884                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6885                            "Unable to create data dirs [errorCode=" + ret + "]");
6886                }
6887
6888                if (dataPath.exists()) {
6889                    pkg.applicationInfo.dataDir = dataPath.getPath();
6890                } else {
6891                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6892                    pkg.applicationInfo.dataDir = null;
6893                }
6894            }
6895
6896            pkgSetting.uidError = uidError;
6897        }
6898
6899        final String path = scanFile.getPath();
6900        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6901
6902        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6903            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6904
6905            // Some system apps still use directory structure for native libraries
6906            // in which case we might end up not detecting abi solely based on apk
6907            // structure. Try to detect abi based on directory structure.
6908            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6909                    pkg.applicationInfo.primaryCpuAbi == null) {
6910                setBundledAppAbisAndRoots(pkg, pkgSetting);
6911                setNativeLibraryPaths(pkg);
6912            }
6913
6914        } else {
6915            if ((scanFlags & SCAN_MOVE) != 0) {
6916                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6917                // but we already have this packages package info in the PackageSetting. We just
6918                // use that and derive the native library path based on the new codepath.
6919                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6920                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6921            }
6922
6923            // Set native library paths again. For moves, the path will be updated based on the
6924            // ABIs we've determined above. For non-moves, the path will be updated based on the
6925            // ABIs we determined during compilation, but the path will depend on the final
6926            // package path (after the rename away from the stage path).
6927            setNativeLibraryPaths(pkg);
6928        }
6929
6930        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6931        final int[] userIds = sUserManager.getUserIds();
6932        synchronized (mInstallLock) {
6933            // Make sure all user data directories are ready to roll; we're okay
6934            // if they already exist
6935            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6936                for (int userId : userIds) {
6937                    if (userId != 0) {
6938                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6939                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6940                                pkg.applicationInfo.seinfo);
6941                    }
6942                }
6943            }
6944
6945            // Create a native library symlink only if we have native libraries
6946            // and if the native libraries are 32 bit libraries. We do not provide
6947            // this symlink for 64 bit libraries.
6948            if (pkg.applicationInfo.primaryCpuAbi != null &&
6949                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6950                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6951                for (int userId : userIds) {
6952                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6953                            nativeLibPath, userId) < 0) {
6954                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6955                                "Failed linking native library dir (user=" + userId + ")");
6956                    }
6957                }
6958            }
6959        }
6960
6961        // This is a special case for the "system" package, where the ABI is
6962        // dictated by the zygote configuration (and init.rc). We should keep track
6963        // of this ABI so that we can deal with "normal" applications that run under
6964        // the same UID correctly.
6965        if (mPlatformPackage == pkg) {
6966            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6967                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6968        }
6969
6970        // If there's a mismatch between the abi-override in the package setting
6971        // and the abiOverride specified for the install. Warn about this because we
6972        // would've already compiled the app without taking the package setting into
6973        // account.
6974        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6975            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6976                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6977                        " for package: " + pkg.packageName);
6978            }
6979        }
6980
6981        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6982        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6983        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6984
6985        // Copy the derived override back to the parsed package, so that we can
6986        // update the package settings accordingly.
6987        pkg.cpuAbiOverride = cpuAbiOverride;
6988
6989        if (DEBUG_ABI_SELECTION) {
6990            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6991                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6992                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6993        }
6994
6995        // Push the derived path down into PackageSettings so we know what to
6996        // clean up at uninstall time.
6997        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6998
6999        if (DEBUG_ABI_SELECTION) {
7000            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7001                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7002                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7003        }
7004
7005        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7006            // We don't do this here during boot because we can do it all
7007            // at once after scanning all existing packages.
7008            //
7009            // We also do this *before* we perform dexopt on this package, so that
7010            // we can avoid redundant dexopts, and also to make sure we've got the
7011            // code and package path correct.
7012            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7013                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
7014        }
7015
7016        if ((scanFlags & SCAN_NO_DEX) == 0) {
7017            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7018                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
7019            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7020                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7021            }
7022        }
7023        if (mFactoryTest && pkg.requestedPermissions.contains(
7024                android.Manifest.permission.FACTORY_TEST)) {
7025            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7026        }
7027
7028        ArrayList<PackageParser.Package> clientLibPkgs = null;
7029
7030        // writer
7031        synchronized (mPackages) {
7032            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7033                // Only system apps can add new shared libraries.
7034                if (pkg.libraryNames != null) {
7035                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7036                        String name = pkg.libraryNames.get(i);
7037                        boolean allowed = false;
7038                        if (pkg.isUpdatedSystemApp()) {
7039                            // New library entries can only be added through the
7040                            // system image.  This is important to get rid of a lot
7041                            // of nasty edge cases: for example if we allowed a non-
7042                            // system update of the app to add a library, then uninstalling
7043                            // the update would make the library go away, and assumptions
7044                            // we made such as through app install filtering would now
7045                            // have allowed apps on the device which aren't compatible
7046                            // with it.  Better to just have the restriction here, be
7047                            // conservative, and create many fewer cases that can negatively
7048                            // impact the user experience.
7049                            final PackageSetting sysPs = mSettings
7050                                    .getDisabledSystemPkgLPr(pkg.packageName);
7051                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7052                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7053                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7054                                        allowed = true;
7055                                        allowed = true;
7056                                        break;
7057                                    }
7058                                }
7059                            }
7060                        } else {
7061                            allowed = true;
7062                        }
7063                        if (allowed) {
7064                            if (!mSharedLibraries.containsKey(name)) {
7065                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7066                            } else if (!name.equals(pkg.packageName)) {
7067                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7068                                        + name + " already exists; skipping");
7069                            }
7070                        } else {
7071                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7072                                    + name + " that is not declared on system image; skipping");
7073                        }
7074                    }
7075                    if ((scanFlags&SCAN_BOOTING) == 0) {
7076                        // If we are not booting, we need to update any applications
7077                        // that are clients of our shared library.  If we are booting,
7078                        // this will all be done once the scan is complete.
7079                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7080                    }
7081                }
7082            }
7083        }
7084
7085        // We also need to dexopt any apps that are dependent on this library.  Note that
7086        // if these fail, we should abort the install since installing the library will
7087        // result in some apps being broken.
7088        if (clientLibPkgs != null) {
7089            if ((scanFlags & SCAN_NO_DEX) == 0) {
7090                for (int i = 0; i < clientLibPkgs.size(); i++) {
7091                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7092                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7093                            null /* instruction sets */, forceDex,
7094                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7095                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7096                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7097                                "scanPackageLI failed to dexopt clientLibPkgs");
7098                    }
7099                }
7100            }
7101        }
7102
7103        // Also need to kill any apps that are dependent on the library.
7104        if (clientLibPkgs != null) {
7105            for (int i=0; i<clientLibPkgs.size(); i++) {
7106                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7107                killApplication(clientPkg.applicationInfo.packageName,
7108                        clientPkg.applicationInfo.uid, "update lib");
7109            }
7110        }
7111
7112        // Make sure we're not adding any bogus keyset info
7113        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7114        ksms.assertScannedPackageValid(pkg);
7115
7116        // writer
7117        synchronized (mPackages) {
7118            // We don't expect installation to fail beyond this point
7119
7120            // Add the new setting to mSettings
7121            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7122            // Add the new setting to mPackages
7123            mPackages.put(pkg.applicationInfo.packageName, pkg);
7124            // Make sure we don't accidentally delete its data.
7125            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7126            while (iter.hasNext()) {
7127                PackageCleanItem item = iter.next();
7128                if (pkgName.equals(item.packageName)) {
7129                    iter.remove();
7130                }
7131            }
7132
7133            // Take care of first install / last update times.
7134            if (currentTime != 0) {
7135                if (pkgSetting.firstInstallTime == 0) {
7136                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7137                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7138                    pkgSetting.lastUpdateTime = currentTime;
7139                }
7140            } else if (pkgSetting.firstInstallTime == 0) {
7141                // We need *something*.  Take time time stamp of the file.
7142                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7143            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7144                if (scanFileTime != pkgSetting.timeStamp) {
7145                    // A package on the system image has changed; consider this
7146                    // to be an update.
7147                    pkgSetting.lastUpdateTime = scanFileTime;
7148                }
7149            }
7150
7151            // Add the package's KeySets to the global KeySetManagerService
7152            ksms.addScannedPackageLPw(pkg);
7153
7154            int N = pkg.providers.size();
7155            StringBuilder r = null;
7156            int i;
7157            for (i=0; i<N; i++) {
7158                PackageParser.Provider p = pkg.providers.get(i);
7159                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7160                        p.info.processName, pkg.applicationInfo.uid);
7161                mProviders.addProvider(p);
7162                p.syncable = p.info.isSyncable;
7163                if (p.info.authority != null) {
7164                    String names[] = p.info.authority.split(";");
7165                    p.info.authority = null;
7166                    for (int j = 0; j < names.length; j++) {
7167                        if (j == 1 && p.syncable) {
7168                            // We only want the first authority for a provider to possibly be
7169                            // syncable, so if we already added this provider using a different
7170                            // authority clear the syncable flag. We copy the provider before
7171                            // changing it because the mProviders object contains a reference
7172                            // to a provider that we don't want to change.
7173                            // Only do this for the second authority since the resulting provider
7174                            // object can be the same for all future authorities for this provider.
7175                            p = new PackageParser.Provider(p);
7176                            p.syncable = false;
7177                        }
7178                        if (!mProvidersByAuthority.containsKey(names[j])) {
7179                            mProvidersByAuthority.put(names[j], p);
7180                            if (p.info.authority == null) {
7181                                p.info.authority = names[j];
7182                            } else {
7183                                p.info.authority = p.info.authority + ";" + names[j];
7184                            }
7185                            if (DEBUG_PACKAGE_SCANNING) {
7186                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7187                                    Log.d(TAG, "Registered content provider: " + names[j]
7188                                            + ", className = " + p.info.name + ", isSyncable = "
7189                                            + p.info.isSyncable);
7190                            }
7191                        } else {
7192                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7193                            Slog.w(TAG, "Skipping provider name " + names[j] +
7194                                    " (in package " + pkg.applicationInfo.packageName +
7195                                    "): name already used by "
7196                                    + ((other != null && other.getComponentName() != null)
7197                                            ? other.getComponentName().getPackageName() : "?"));
7198                        }
7199                    }
7200                }
7201                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7202                    if (r == null) {
7203                        r = new StringBuilder(256);
7204                    } else {
7205                        r.append(' ');
7206                    }
7207                    r.append(p.info.name);
7208                }
7209            }
7210            if (r != null) {
7211                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7212            }
7213
7214            N = pkg.services.size();
7215            r = null;
7216            for (i=0; i<N; i++) {
7217                PackageParser.Service s = pkg.services.get(i);
7218                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7219                        s.info.processName, pkg.applicationInfo.uid);
7220                mServices.addService(s);
7221                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7222                    if (r == null) {
7223                        r = new StringBuilder(256);
7224                    } else {
7225                        r.append(' ');
7226                    }
7227                    r.append(s.info.name);
7228                }
7229            }
7230            if (r != null) {
7231                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7232            }
7233
7234            N = pkg.receivers.size();
7235            r = null;
7236            for (i=0; i<N; i++) {
7237                PackageParser.Activity a = pkg.receivers.get(i);
7238                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7239                        a.info.processName, pkg.applicationInfo.uid);
7240                mReceivers.addActivity(a, "receiver");
7241                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7242                    if (r == null) {
7243                        r = new StringBuilder(256);
7244                    } else {
7245                        r.append(' ');
7246                    }
7247                    r.append(a.info.name);
7248                }
7249            }
7250            if (r != null) {
7251                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7252            }
7253
7254            N = pkg.activities.size();
7255            r = null;
7256            for (i=0; i<N; i++) {
7257                PackageParser.Activity a = pkg.activities.get(i);
7258                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7259                        a.info.processName, pkg.applicationInfo.uid);
7260                mActivities.addActivity(a, "activity");
7261                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7262                    if (r == null) {
7263                        r = new StringBuilder(256);
7264                    } else {
7265                        r.append(' ');
7266                    }
7267                    r.append(a.info.name);
7268                }
7269            }
7270            if (r != null) {
7271                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7272            }
7273
7274            N = pkg.permissionGroups.size();
7275            r = null;
7276            for (i=0; i<N; i++) {
7277                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7278                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7279                if (cur == null) {
7280                    mPermissionGroups.put(pg.info.name, pg);
7281                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7282                        if (r == null) {
7283                            r = new StringBuilder(256);
7284                        } else {
7285                            r.append(' ');
7286                        }
7287                        r.append(pg.info.name);
7288                    }
7289                } else {
7290                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7291                            + pg.info.packageName + " ignored: original from "
7292                            + cur.info.packageName);
7293                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7294                        if (r == null) {
7295                            r = new StringBuilder(256);
7296                        } else {
7297                            r.append(' ');
7298                        }
7299                        r.append("DUP:");
7300                        r.append(pg.info.name);
7301                    }
7302                }
7303            }
7304            if (r != null) {
7305                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7306            }
7307
7308            N = pkg.permissions.size();
7309            r = null;
7310            for (i=0; i<N; i++) {
7311                PackageParser.Permission p = pkg.permissions.get(i);
7312
7313                // Now that permission groups have a special meaning, we ignore permission
7314                // groups for legacy apps to prevent unexpected behavior. In particular,
7315                // permissions for one app being granted to someone just becuase they happen
7316                // to be in a group defined by another app (before this had no implications).
7317                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7318                    p.group = mPermissionGroups.get(p.info.group);
7319                    // Warn for a permission in an unknown group.
7320                    if (p.info.group != null && p.group == null) {
7321                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7322                                + p.info.packageName + " in an unknown group " + p.info.group);
7323                    }
7324                }
7325
7326                ArrayMap<String, BasePermission> permissionMap =
7327                        p.tree ? mSettings.mPermissionTrees
7328                                : mSettings.mPermissions;
7329                BasePermission bp = permissionMap.get(p.info.name);
7330
7331                // Allow system apps to redefine non-system permissions
7332                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7333                    final boolean currentOwnerIsSystem = (bp.perm != null
7334                            && isSystemApp(bp.perm.owner));
7335                    if (isSystemApp(p.owner)) {
7336                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7337                            // It's a built-in permission and no owner, take ownership now
7338                            bp.packageSetting = pkgSetting;
7339                            bp.perm = p;
7340                            bp.uid = pkg.applicationInfo.uid;
7341                            bp.sourcePackage = p.info.packageName;
7342                        } else if (!currentOwnerIsSystem) {
7343                            String msg = "New decl " + p.owner + " of permission  "
7344                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7345                            reportSettingsProblem(Log.WARN, msg);
7346                            bp = null;
7347                        }
7348                    }
7349                }
7350
7351                if (bp == null) {
7352                    bp = new BasePermission(p.info.name, p.info.packageName,
7353                            BasePermission.TYPE_NORMAL);
7354                    permissionMap.put(p.info.name, bp);
7355                }
7356
7357                if (bp.perm == null) {
7358                    if (bp.sourcePackage == null
7359                            || bp.sourcePackage.equals(p.info.packageName)) {
7360                        BasePermission tree = findPermissionTreeLP(p.info.name);
7361                        if (tree == null
7362                                || tree.sourcePackage.equals(p.info.packageName)) {
7363                            bp.packageSetting = pkgSetting;
7364                            bp.perm = p;
7365                            bp.uid = pkg.applicationInfo.uid;
7366                            bp.sourcePackage = p.info.packageName;
7367                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7368                                if (r == null) {
7369                                    r = new StringBuilder(256);
7370                                } else {
7371                                    r.append(' ');
7372                                }
7373                                r.append(p.info.name);
7374                            }
7375                        } else {
7376                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7377                                    + p.info.packageName + " ignored: base tree "
7378                                    + tree.name + " is from package "
7379                                    + tree.sourcePackage);
7380                        }
7381                    } else {
7382                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7383                                + p.info.packageName + " ignored: original from "
7384                                + bp.sourcePackage);
7385                    }
7386                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7387                    if (r == null) {
7388                        r = new StringBuilder(256);
7389                    } else {
7390                        r.append(' ');
7391                    }
7392                    r.append("DUP:");
7393                    r.append(p.info.name);
7394                }
7395                if (bp.perm == p) {
7396                    bp.protectionLevel = p.info.protectionLevel;
7397                }
7398            }
7399
7400            if (r != null) {
7401                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7402            }
7403
7404            N = pkg.instrumentation.size();
7405            r = null;
7406            for (i=0; i<N; i++) {
7407                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7408                a.info.packageName = pkg.applicationInfo.packageName;
7409                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7410                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7411                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7412                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7413                a.info.dataDir = pkg.applicationInfo.dataDir;
7414
7415                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7416                // need other information about the application, like the ABI and what not ?
7417                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7418                mInstrumentation.put(a.getComponentName(), a);
7419                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7420                    if (r == null) {
7421                        r = new StringBuilder(256);
7422                    } else {
7423                        r.append(' ');
7424                    }
7425                    r.append(a.info.name);
7426                }
7427            }
7428            if (r != null) {
7429                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7430            }
7431
7432            if (pkg.protectedBroadcasts != null) {
7433                N = pkg.protectedBroadcasts.size();
7434                for (i=0; i<N; i++) {
7435                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7436                }
7437            }
7438
7439            pkgSetting.setTimeStamp(scanFileTime);
7440
7441            // Create idmap files for pairs of (packages, overlay packages).
7442            // Note: "android", ie framework-res.apk, is handled by native layers.
7443            if (pkg.mOverlayTarget != null) {
7444                // This is an overlay package.
7445                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7446                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7447                        mOverlays.put(pkg.mOverlayTarget,
7448                                new ArrayMap<String, PackageParser.Package>());
7449                    }
7450                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7451                    map.put(pkg.packageName, pkg);
7452                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7453                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7454                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7455                                "scanPackageLI failed to createIdmap");
7456                    }
7457                }
7458            } else if (mOverlays.containsKey(pkg.packageName) &&
7459                    !pkg.packageName.equals("android")) {
7460                // This is a regular package, with one or more known overlay packages.
7461                createIdmapsForPackageLI(pkg);
7462            }
7463        }
7464
7465        return pkg;
7466    }
7467
7468    /**
7469     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7470     * is derived purely on the basis of the contents of {@code scanFile} and
7471     * {@code cpuAbiOverride}.
7472     *
7473     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7474     */
7475    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7476                                 String cpuAbiOverride, boolean extractLibs)
7477            throws PackageManagerException {
7478        // TODO: We can probably be smarter about this stuff. For installed apps,
7479        // we can calculate this information at install time once and for all. For
7480        // system apps, we can probably assume that this information doesn't change
7481        // after the first boot scan. As things stand, we do lots of unnecessary work.
7482
7483        // Give ourselves some initial paths; we'll come back for another
7484        // pass once we've determined ABI below.
7485        setNativeLibraryPaths(pkg);
7486
7487        // We would never need to extract libs for forward-locked and external packages,
7488        // since the container service will do it for us. We shouldn't attempt to
7489        // extract libs from system app when it was not updated.
7490        if (pkg.isForwardLocked() || isExternal(pkg) ||
7491            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7492            extractLibs = false;
7493        }
7494
7495        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7496        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7497
7498        NativeLibraryHelper.Handle handle = null;
7499        try {
7500            handle = NativeLibraryHelper.Handle.create(pkg);
7501            // TODO(multiArch): This can be null for apps that didn't go through the
7502            // usual installation process. We can calculate it again, like we
7503            // do during install time.
7504            //
7505            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7506            // unnecessary.
7507            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7508
7509            // Null out the abis so that they can be recalculated.
7510            pkg.applicationInfo.primaryCpuAbi = null;
7511            pkg.applicationInfo.secondaryCpuAbi = null;
7512            if (isMultiArch(pkg.applicationInfo)) {
7513                // Warn if we've set an abiOverride for multi-lib packages..
7514                // By definition, we need to copy both 32 and 64 bit libraries for
7515                // such packages.
7516                if (pkg.cpuAbiOverride != null
7517                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7518                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7519                }
7520
7521                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7522                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7523                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7524                    if (extractLibs) {
7525                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7526                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7527                                useIsaSpecificSubdirs);
7528                    } else {
7529                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7530                    }
7531                }
7532
7533                maybeThrowExceptionForMultiArchCopy(
7534                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7535
7536                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7537                    if (extractLibs) {
7538                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7539                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7540                                useIsaSpecificSubdirs);
7541                    } else {
7542                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7543                    }
7544                }
7545
7546                maybeThrowExceptionForMultiArchCopy(
7547                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7548
7549                if (abi64 >= 0) {
7550                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7551                }
7552
7553                if (abi32 >= 0) {
7554                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7555                    if (abi64 >= 0) {
7556                        pkg.applicationInfo.secondaryCpuAbi = abi;
7557                    } else {
7558                        pkg.applicationInfo.primaryCpuAbi = abi;
7559                    }
7560                }
7561            } else {
7562                String[] abiList = (cpuAbiOverride != null) ?
7563                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7564
7565                // Enable gross and lame hacks for apps that are built with old
7566                // SDK tools. We must scan their APKs for renderscript bitcode and
7567                // not launch them if it's present. Don't bother checking on devices
7568                // that don't have 64 bit support.
7569                boolean needsRenderScriptOverride = false;
7570                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7571                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7572                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7573                    needsRenderScriptOverride = true;
7574                }
7575
7576                final int copyRet;
7577                if (extractLibs) {
7578                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7579                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7580                } else {
7581                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7582                }
7583
7584                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7585                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7586                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7587                }
7588
7589                if (copyRet >= 0) {
7590                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7591                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7592                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7593                } else if (needsRenderScriptOverride) {
7594                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7595                }
7596            }
7597        } catch (IOException ioe) {
7598            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7599        } finally {
7600            IoUtils.closeQuietly(handle);
7601        }
7602
7603        // Now that we've calculated the ABIs and determined if it's an internal app,
7604        // we will go ahead and populate the nativeLibraryPath.
7605        setNativeLibraryPaths(pkg);
7606    }
7607
7608    /**
7609     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7610     * i.e, so that all packages can be run inside a single process if required.
7611     *
7612     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7613     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7614     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7615     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7616     * updating a package that belongs to a shared user.
7617     *
7618     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7619     * adds unnecessary complexity.
7620     */
7621    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7622            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7623        String requiredInstructionSet = null;
7624        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7625            requiredInstructionSet = VMRuntime.getInstructionSet(
7626                     scannedPackage.applicationInfo.primaryCpuAbi);
7627        }
7628
7629        PackageSetting requirer = null;
7630        for (PackageSetting ps : packagesForUser) {
7631            // If packagesForUser contains scannedPackage, we skip it. This will happen
7632            // when scannedPackage is an update of an existing package. Without this check,
7633            // we will never be able to change the ABI of any package belonging to a shared
7634            // user, even if it's compatible with other packages.
7635            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7636                if (ps.primaryCpuAbiString == null) {
7637                    continue;
7638                }
7639
7640                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7641                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7642                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7643                    // this but there's not much we can do.
7644                    String errorMessage = "Instruction set mismatch, "
7645                            + ((requirer == null) ? "[caller]" : requirer)
7646                            + " requires " + requiredInstructionSet + " whereas " + ps
7647                            + " requires " + instructionSet;
7648                    Slog.w(TAG, errorMessage);
7649                }
7650
7651                if (requiredInstructionSet == null) {
7652                    requiredInstructionSet = instructionSet;
7653                    requirer = ps;
7654                }
7655            }
7656        }
7657
7658        if (requiredInstructionSet != null) {
7659            String adjustedAbi;
7660            if (requirer != null) {
7661                // requirer != null implies that either scannedPackage was null or that scannedPackage
7662                // did not require an ABI, in which case we have to adjust scannedPackage to match
7663                // the ABI of the set (which is the same as requirer's ABI)
7664                adjustedAbi = requirer.primaryCpuAbiString;
7665                if (scannedPackage != null) {
7666                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7667                }
7668            } else {
7669                // requirer == null implies that we're updating all ABIs in the set to
7670                // match scannedPackage.
7671                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7672            }
7673
7674            for (PackageSetting ps : packagesForUser) {
7675                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7676                    if (ps.primaryCpuAbiString != null) {
7677                        continue;
7678                    }
7679
7680                    ps.primaryCpuAbiString = adjustedAbi;
7681                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7682                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7683                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7684
7685                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7686                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7687                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7688                            ps.primaryCpuAbiString = null;
7689                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7690                            return;
7691                        } else {
7692                            mInstaller.rmdex(ps.codePathString,
7693                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7694                        }
7695                    }
7696                }
7697            }
7698        }
7699    }
7700
7701    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7702        synchronized (mPackages) {
7703            mResolverReplaced = true;
7704            // Set up information for custom user intent resolution activity.
7705            mResolveActivity.applicationInfo = pkg.applicationInfo;
7706            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7707            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7708            mResolveActivity.processName = pkg.applicationInfo.packageName;
7709            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7710            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7711                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7712            mResolveActivity.theme = 0;
7713            mResolveActivity.exported = true;
7714            mResolveActivity.enabled = true;
7715            mResolveInfo.activityInfo = mResolveActivity;
7716            mResolveInfo.priority = 0;
7717            mResolveInfo.preferredOrder = 0;
7718            mResolveInfo.match = 0;
7719            mResolveComponentName = mCustomResolverComponentName;
7720            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7721                    mResolveComponentName);
7722        }
7723    }
7724
7725    private static String calculateBundledApkRoot(final String codePathString) {
7726        final File codePath = new File(codePathString);
7727        final File codeRoot;
7728        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7729            codeRoot = Environment.getRootDirectory();
7730        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7731            codeRoot = Environment.getOemDirectory();
7732        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7733            codeRoot = Environment.getVendorDirectory();
7734        } else {
7735            // Unrecognized code path; take its top real segment as the apk root:
7736            // e.g. /something/app/blah.apk => /something
7737            try {
7738                File f = codePath.getCanonicalFile();
7739                File parent = f.getParentFile();    // non-null because codePath is a file
7740                File tmp;
7741                while ((tmp = parent.getParentFile()) != null) {
7742                    f = parent;
7743                    parent = tmp;
7744                }
7745                codeRoot = f;
7746                Slog.w(TAG, "Unrecognized code path "
7747                        + codePath + " - using " + codeRoot);
7748            } catch (IOException e) {
7749                // Can't canonicalize the code path -- shenanigans?
7750                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7751                return Environment.getRootDirectory().getPath();
7752            }
7753        }
7754        return codeRoot.getPath();
7755    }
7756
7757    /**
7758     * Derive and set the location of native libraries for the given package,
7759     * which varies depending on where and how the package was installed.
7760     */
7761    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7762        final ApplicationInfo info = pkg.applicationInfo;
7763        final String codePath = pkg.codePath;
7764        final File codeFile = new File(codePath);
7765        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7766        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7767
7768        info.nativeLibraryRootDir = null;
7769        info.nativeLibraryRootRequiresIsa = false;
7770        info.nativeLibraryDir = null;
7771        info.secondaryNativeLibraryDir = null;
7772
7773        if (isApkFile(codeFile)) {
7774            // Monolithic install
7775            if (bundledApp) {
7776                // If "/system/lib64/apkname" exists, assume that is the per-package
7777                // native library directory to use; otherwise use "/system/lib/apkname".
7778                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7779                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7780                        getPrimaryInstructionSet(info));
7781
7782                // This is a bundled system app so choose the path based on the ABI.
7783                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7784                // is just the default path.
7785                final String apkName = deriveCodePathName(codePath);
7786                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7787                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7788                        apkName).getAbsolutePath();
7789
7790                if (info.secondaryCpuAbi != null) {
7791                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7792                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7793                            secondaryLibDir, apkName).getAbsolutePath();
7794                }
7795            } else if (asecApp) {
7796                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7797                        .getAbsolutePath();
7798            } else {
7799                final String apkName = deriveCodePathName(codePath);
7800                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7801                        .getAbsolutePath();
7802            }
7803
7804            info.nativeLibraryRootRequiresIsa = false;
7805            info.nativeLibraryDir = info.nativeLibraryRootDir;
7806        } else {
7807            // Cluster install
7808            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7809            info.nativeLibraryRootRequiresIsa = true;
7810
7811            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7812                    getPrimaryInstructionSet(info)).getAbsolutePath();
7813
7814            if (info.secondaryCpuAbi != null) {
7815                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7816                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7817            }
7818        }
7819    }
7820
7821    /**
7822     * Calculate the abis and roots for a bundled app. These can uniquely
7823     * be determined from the contents of the system partition, i.e whether
7824     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7825     * of this information, and instead assume that the system was built
7826     * sensibly.
7827     */
7828    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7829                                           PackageSetting pkgSetting) {
7830        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7831
7832        // If "/system/lib64/apkname" exists, assume that is the per-package
7833        // native library directory to use; otherwise use "/system/lib/apkname".
7834        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7835        setBundledAppAbi(pkg, apkRoot, apkName);
7836        // pkgSetting might be null during rescan following uninstall of updates
7837        // to a bundled app, so accommodate that possibility.  The settings in
7838        // that case will be established later from the parsed package.
7839        //
7840        // If the settings aren't null, sync them up with what we've just derived.
7841        // note that apkRoot isn't stored in the package settings.
7842        if (pkgSetting != null) {
7843            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7844            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7845        }
7846    }
7847
7848    /**
7849     * Deduces the ABI of a bundled app and sets the relevant fields on the
7850     * parsed pkg object.
7851     *
7852     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7853     *        under which system libraries are installed.
7854     * @param apkName the name of the installed package.
7855     */
7856    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7857        final File codeFile = new File(pkg.codePath);
7858
7859        final boolean has64BitLibs;
7860        final boolean has32BitLibs;
7861        if (isApkFile(codeFile)) {
7862            // Monolithic install
7863            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7864            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7865        } else {
7866            // Cluster install
7867            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7868            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7869                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7870                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7871                has64BitLibs = (new File(rootDir, isa)).exists();
7872            } else {
7873                has64BitLibs = false;
7874            }
7875            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7876                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7877                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7878                has32BitLibs = (new File(rootDir, isa)).exists();
7879            } else {
7880                has32BitLibs = false;
7881            }
7882        }
7883
7884        if (has64BitLibs && !has32BitLibs) {
7885            // The package has 64 bit libs, but not 32 bit libs. Its primary
7886            // ABI should be 64 bit. We can safely assume here that the bundled
7887            // native libraries correspond to the most preferred ABI in the list.
7888
7889            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7890            pkg.applicationInfo.secondaryCpuAbi = null;
7891        } else if (has32BitLibs && !has64BitLibs) {
7892            // The package has 32 bit libs but not 64 bit libs. Its primary
7893            // ABI should be 32 bit.
7894
7895            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7896            pkg.applicationInfo.secondaryCpuAbi = null;
7897        } else if (has32BitLibs && has64BitLibs) {
7898            // The application has both 64 and 32 bit bundled libraries. We check
7899            // here that the app declares multiArch support, and warn if it doesn't.
7900            //
7901            // We will be lenient here and record both ABIs. The primary will be the
7902            // ABI that's higher on the list, i.e, a device that's configured to prefer
7903            // 64 bit apps will see a 64 bit primary ABI,
7904
7905            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7906                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7907            }
7908
7909            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7910                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7911                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7912            } else {
7913                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7914                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7915            }
7916        } else {
7917            pkg.applicationInfo.primaryCpuAbi = null;
7918            pkg.applicationInfo.secondaryCpuAbi = null;
7919        }
7920    }
7921
7922    private void killApplication(String pkgName, int appId, String reason) {
7923        // Request the ActivityManager to kill the process(only for existing packages)
7924        // so that we do not end up in a confused state while the user is still using the older
7925        // version of the application while the new one gets installed.
7926        IActivityManager am = ActivityManagerNative.getDefault();
7927        if (am != null) {
7928            try {
7929                am.killApplicationWithAppId(pkgName, appId, reason);
7930            } catch (RemoteException e) {
7931            }
7932        }
7933    }
7934
7935    void removePackageLI(PackageSetting ps, boolean chatty) {
7936        if (DEBUG_INSTALL) {
7937            if (chatty)
7938                Log.d(TAG, "Removing package " + ps.name);
7939        }
7940
7941        // writer
7942        synchronized (mPackages) {
7943            mPackages.remove(ps.name);
7944            final PackageParser.Package pkg = ps.pkg;
7945            if (pkg != null) {
7946                cleanPackageDataStructuresLILPw(pkg, chatty);
7947            }
7948        }
7949    }
7950
7951    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7952        if (DEBUG_INSTALL) {
7953            if (chatty)
7954                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7955        }
7956
7957        // writer
7958        synchronized (mPackages) {
7959            mPackages.remove(pkg.applicationInfo.packageName);
7960            cleanPackageDataStructuresLILPw(pkg, chatty);
7961        }
7962    }
7963
7964    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7965        int N = pkg.providers.size();
7966        StringBuilder r = null;
7967        int i;
7968        for (i=0; i<N; i++) {
7969            PackageParser.Provider p = pkg.providers.get(i);
7970            mProviders.removeProvider(p);
7971            if (p.info.authority == null) {
7972
7973                /* There was another ContentProvider with this authority when
7974                 * this app was installed so this authority is null,
7975                 * Ignore it as we don't have to unregister the provider.
7976                 */
7977                continue;
7978            }
7979            String names[] = p.info.authority.split(";");
7980            for (int j = 0; j < names.length; j++) {
7981                if (mProvidersByAuthority.get(names[j]) == p) {
7982                    mProvidersByAuthority.remove(names[j]);
7983                    if (DEBUG_REMOVE) {
7984                        if (chatty)
7985                            Log.d(TAG, "Unregistered content provider: " + names[j]
7986                                    + ", className = " + p.info.name + ", isSyncable = "
7987                                    + p.info.isSyncable);
7988                    }
7989                }
7990            }
7991            if (DEBUG_REMOVE && chatty) {
7992                if (r == null) {
7993                    r = new StringBuilder(256);
7994                } else {
7995                    r.append(' ');
7996                }
7997                r.append(p.info.name);
7998            }
7999        }
8000        if (r != null) {
8001            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8002        }
8003
8004        N = pkg.services.size();
8005        r = null;
8006        for (i=0; i<N; i++) {
8007            PackageParser.Service s = pkg.services.get(i);
8008            mServices.removeService(s);
8009            if (chatty) {
8010                if (r == null) {
8011                    r = new StringBuilder(256);
8012                } else {
8013                    r.append(' ');
8014                }
8015                r.append(s.info.name);
8016            }
8017        }
8018        if (r != null) {
8019            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8020        }
8021
8022        N = pkg.receivers.size();
8023        r = null;
8024        for (i=0; i<N; i++) {
8025            PackageParser.Activity a = pkg.receivers.get(i);
8026            mReceivers.removeActivity(a, "receiver");
8027            if (DEBUG_REMOVE && chatty) {
8028                if (r == null) {
8029                    r = new StringBuilder(256);
8030                } else {
8031                    r.append(' ');
8032                }
8033                r.append(a.info.name);
8034            }
8035        }
8036        if (r != null) {
8037            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8038        }
8039
8040        N = pkg.activities.size();
8041        r = null;
8042        for (i=0; i<N; i++) {
8043            PackageParser.Activity a = pkg.activities.get(i);
8044            mActivities.removeActivity(a, "activity");
8045            if (DEBUG_REMOVE && chatty) {
8046                if (r == null) {
8047                    r = new StringBuilder(256);
8048                } else {
8049                    r.append(' ');
8050                }
8051                r.append(a.info.name);
8052            }
8053        }
8054        if (r != null) {
8055            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8056        }
8057
8058        N = pkg.permissions.size();
8059        r = null;
8060        for (i=0; i<N; i++) {
8061            PackageParser.Permission p = pkg.permissions.get(i);
8062            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8063            if (bp == null) {
8064                bp = mSettings.mPermissionTrees.get(p.info.name);
8065            }
8066            if (bp != null && bp.perm == p) {
8067                bp.perm = null;
8068                if (DEBUG_REMOVE && chatty) {
8069                    if (r == null) {
8070                        r = new StringBuilder(256);
8071                    } else {
8072                        r.append(' ');
8073                    }
8074                    r.append(p.info.name);
8075                }
8076            }
8077            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8078                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8079                if (appOpPerms != null) {
8080                    appOpPerms.remove(pkg.packageName);
8081                }
8082            }
8083        }
8084        if (r != null) {
8085            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8086        }
8087
8088        N = pkg.requestedPermissions.size();
8089        r = null;
8090        for (i=0; i<N; i++) {
8091            String perm = pkg.requestedPermissions.get(i);
8092            BasePermission bp = mSettings.mPermissions.get(perm);
8093            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8094                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8095                if (appOpPerms != null) {
8096                    appOpPerms.remove(pkg.packageName);
8097                    if (appOpPerms.isEmpty()) {
8098                        mAppOpPermissionPackages.remove(perm);
8099                    }
8100                }
8101            }
8102        }
8103        if (r != null) {
8104            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8105        }
8106
8107        N = pkg.instrumentation.size();
8108        r = null;
8109        for (i=0; i<N; i++) {
8110            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8111            mInstrumentation.remove(a.getComponentName());
8112            if (DEBUG_REMOVE && chatty) {
8113                if (r == null) {
8114                    r = new StringBuilder(256);
8115                } else {
8116                    r.append(' ');
8117                }
8118                r.append(a.info.name);
8119            }
8120        }
8121        if (r != null) {
8122            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8123        }
8124
8125        r = null;
8126        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8127            // Only system apps can hold shared libraries.
8128            if (pkg.libraryNames != null) {
8129                for (i=0; i<pkg.libraryNames.size(); i++) {
8130                    String name = pkg.libraryNames.get(i);
8131                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8132                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8133                        mSharedLibraries.remove(name);
8134                        if (DEBUG_REMOVE && chatty) {
8135                            if (r == null) {
8136                                r = new StringBuilder(256);
8137                            } else {
8138                                r.append(' ');
8139                            }
8140                            r.append(name);
8141                        }
8142                    }
8143                }
8144            }
8145        }
8146        if (r != null) {
8147            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8148        }
8149    }
8150
8151    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8152        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8153            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8154                return true;
8155            }
8156        }
8157        return false;
8158    }
8159
8160    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8161    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8162    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8163
8164    private void updatePermissionsLPw(String changingPkg,
8165            PackageParser.Package pkgInfo, int flags) {
8166        // Make sure there are no dangling permission trees.
8167        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8168        while (it.hasNext()) {
8169            final BasePermission bp = it.next();
8170            if (bp.packageSetting == null) {
8171                // We may not yet have parsed the package, so just see if
8172                // we still know about its settings.
8173                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8174            }
8175            if (bp.packageSetting == null) {
8176                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8177                        + " from package " + bp.sourcePackage);
8178                it.remove();
8179            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8180                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8181                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8182                            + " from package " + bp.sourcePackage);
8183                    flags |= UPDATE_PERMISSIONS_ALL;
8184                    it.remove();
8185                }
8186            }
8187        }
8188
8189        // Make sure all dynamic permissions have been assigned to a package,
8190        // and make sure there are no dangling permissions.
8191        it = mSettings.mPermissions.values().iterator();
8192        while (it.hasNext()) {
8193            final BasePermission bp = it.next();
8194            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8195                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8196                        + bp.name + " pkg=" + bp.sourcePackage
8197                        + " info=" + bp.pendingInfo);
8198                if (bp.packageSetting == null && bp.pendingInfo != null) {
8199                    final BasePermission tree = findPermissionTreeLP(bp.name);
8200                    if (tree != null && tree.perm != null) {
8201                        bp.packageSetting = tree.packageSetting;
8202                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8203                                new PermissionInfo(bp.pendingInfo));
8204                        bp.perm.info.packageName = tree.perm.info.packageName;
8205                        bp.perm.info.name = bp.name;
8206                        bp.uid = tree.uid;
8207                    }
8208                }
8209            }
8210            if (bp.packageSetting == null) {
8211                // We may not yet have parsed the package, so just see if
8212                // we still know about its settings.
8213                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8214            }
8215            if (bp.packageSetting == null) {
8216                Slog.w(TAG, "Removing dangling permission: " + bp.name
8217                        + " from package " + bp.sourcePackage);
8218                it.remove();
8219            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8220                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8221                    Slog.i(TAG, "Removing old permission: " + bp.name
8222                            + " from package " + bp.sourcePackage);
8223                    flags |= UPDATE_PERMISSIONS_ALL;
8224                    it.remove();
8225                }
8226            }
8227        }
8228
8229        // Now update the permissions for all packages, in particular
8230        // replace the granted permissions of the system packages.
8231        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8232            for (PackageParser.Package pkg : mPackages.values()) {
8233                if (pkg != pkgInfo) {
8234                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8235                            changingPkg);
8236                }
8237            }
8238        }
8239
8240        if (pkgInfo != null) {
8241            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8242        }
8243    }
8244
8245    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8246            String packageOfInterest) {
8247        // IMPORTANT: There are two types of permissions: install and runtime.
8248        // Install time permissions are granted when the app is installed to
8249        // all device users and users added in the future. Runtime permissions
8250        // are granted at runtime explicitly to specific users. Normal and signature
8251        // protected permissions are install time permissions. Dangerous permissions
8252        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8253        // otherwise they are runtime permissions. This function does not manage
8254        // runtime permissions except for the case an app targeting Lollipop MR1
8255        // being upgraded to target a newer SDK, in which case dangerous permissions
8256        // are transformed from install time to runtime ones.
8257
8258        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8259        if (ps == null) {
8260            return;
8261        }
8262
8263        PermissionsState permissionsState = ps.getPermissionsState();
8264        PermissionsState origPermissions = permissionsState;
8265
8266        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8267
8268        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8269
8270        boolean changedInstallPermission = false;
8271
8272        if (replace) {
8273            ps.installPermissionsFixed = false;
8274            if (!ps.isSharedUser()) {
8275                origPermissions = new PermissionsState(permissionsState);
8276                permissionsState.reset();
8277            }
8278        }
8279
8280        permissionsState.setGlobalGids(mGlobalGids);
8281
8282        final int N = pkg.requestedPermissions.size();
8283        for (int i=0; i<N; i++) {
8284            final String name = pkg.requestedPermissions.get(i);
8285            final BasePermission bp = mSettings.mPermissions.get(name);
8286
8287            if (DEBUG_INSTALL) {
8288                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8289            }
8290
8291            if (bp == null || bp.packageSetting == null) {
8292                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8293                    Slog.w(TAG, "Unknown permission " + name
8294                            + " in package " + pkg.packageName);
8295                }
8296                continue;
8297            }
8298
8299            final String perm = bp.name;
8300            boolean allowedSig = false;
8301            int grant = GRANT_DENIED;
8302
8303            // Keep track of app op permissions.
8304            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8305                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8306                if (pkgs == null) {
8307                    pkgs = new ArraySet<>();
8308                    mAppOpPermissionPackages.put(bp.name, pkgs);
8309                }
8310                pkgs.add(pkg.packageName);
8311            }
8312
8313            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8314            switch (level) {
8315                case PermissionInfo.PROTECTION_NORMAL: {
8316                    // For all apps normal permissions are install time ones.
8317                    grant = GRANT_INSTALL;
8318                } break;
8319
8320                case PermissionInfo.PROTECTION_DANGEROUS: {
8321                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8322                        // For legacy apps dangerous permissions are install time ones.
8323                        grant = GRANT_INSTALL_LEGACY;
8324                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8325                        // For legacy apps that became modern, install becomes runtime.
8326                        grant = GRANT_UPGRADE;
8327                    } else {
8328                        // For modern apps keep runtime permissions unchanged.
8329                        grant = GRANT_RUNTIME;
8330                    }
8331                } break;
8332
8333                case PermissionInfo.PROTECTION_SIGNATURE: {
8334                    // For all apps signature permissions are install time ones.
8335                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8336                    if (allowedSig) {
8337                        grant = GRANT_INSTALL;
8338                    }
8339                } break;
8340            }
8341
8342            if (DEBUG_INSTALL) {
8343                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8344            }
8345
8346            if (grant != GRANT_DENIED) {
8347                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8348                    // If this is an existing, non-system package, then
8349                    // we can't add any new permissions to it.
8350                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8351                        // Except...  if this is a permission that was added
8352                        // to the platform (note: need to only do this when
8353                        // updating the platform).
8354                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8355                            grant = GRANT_DENIED;
8356                        }
8357                    }
8358                }
8359
8360                switch (grant) {
8361                    case GRANT_INSTALL: {
8362                        // Revoke this as runtime permission to handle the case of
8363                        // a runtime permission being downgraded to an install one.
8364                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8365                            if (origPermissions.getRuntimePermissionState(
8366                                    bp.name, userId) != null) {
8367                                // Revoke the runtime permission and clear the flags.
8368                                origPermissions.revokeRuntimePermission(bp, userId);
8369                                origPermissions.updatePermissionFlags(bp, userId,
8370                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8371                                // If we revoked a permission permission, we have to write.
8372                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8373                                        changedRuntimePermissionUserIds, userId);
8374                            }
8375                        }
8376                        // Grant an install permission.
8377                        if (permissionsState.grantInstallPermission(bp) !=
8378                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8379                            changedInstallPermission = true;
8380                        }
8381                    } break;
8382
8383                    case GRANT_INSTALL_LEGACY: {
8384                        // Grant an install permission.
8385                        if (permissionsState.grantInstallPermission(bp) !=
8386                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8387                            changedInstallPermission = true;
8388                        }
8389                    } break;
8390
8391                    case GRANT_RUNTIME: {
8392                        // Grant previously granted runtime permissions.
8393                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8394                            PermissionState permissionState = origPermissions
8395                                    .getRuntimePermissionState(bp.name, userId);
8396                            final int flags = permissionState != null
8397                                    ? permissionState.getFlags() : 0;
8398                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8399                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8400                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8401                                    // If we cannot put the permission as it was, we have to write.
8402                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8403                                            changedRuntimePermissionUserIds, userId);
8404                                }
8405                            }
8406                            // Propagate the permission flags.
8407                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8408                        }
8409                    } break;
8410
8411                    case GRANT_UPGRADE: {
8412                        // Grant runtime permissions for a previously held install permission.
8413                        PermissionState permissionState = origPermissions
8414                                .getInstallPermissionState(bp.name);
8415                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8416
8417                        if (origPermissions.revokeInstallPermission(bp)
8418                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8419                            // We will be transferring the permission flags, so clear them.
8420                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8421                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8422                            changedInstallPermission = true;
8423                        }
8424
8425                        // If the permission is not to be promoted to runtime we ignore it and
8426                        // also its other flags as they are not applicable to install permissions.
8427                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8428                            for (int userId : currentUserIds) {
8429                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8430                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8431                                    // Transfer the permission flags.
8432                                    permissionsState.updatePermissionFlags(bp, userId,
8433                                            flags, flags);
8434                                    // If we granted the permission, we have to write.
8435                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8436                                            changedRuntimePermissionUserIds, userId);
8437                                }
8438                            }
8439                        }
8440                    } break;
8441
8442                    default: {
8443                        if (packageOfInterest == null
8444                                || packageOfInterest.equals(pkg.packageName)) {
8445                            Slog.w(TAG, "Not granting permission " + perm
8446                                    + " to package " + pkg.packageName
8447                                    + " because it was previously installed without");
8448                        }
8449                    } break;
8450                }
8451            } else {
8452                if (permissionsState.revokeInstallPermission(bp) !=
8453                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8454                    // Also drop the permission flags.
8455                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8456                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8457                    changedInstallPermission = true;
8458                    Slog.i(TAG, "Un-granting permission " + perm
8459                            + " from package " + pkg.packageName
8460                            + " (protectionLevel=" + bp.protectionLevel
8461                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8462                            + ")");
8463                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8464                    // Don't print warning for app op permissions, since it is fine for them
8465                    // not to be granted, there is a UI for the user to decide.
8466                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8467                        Slog.w(TAG, "Not granting permission " + perm
8468                                + " to package " + pkg.packageName
8469                                + " (protectionLevel=" + bp.protectionLevel
8470                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8471                                + ")");
8472                    }
8473                }
8474            }
8475        }
8476
8477        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8478                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8479            // This is the first that we have heard about this package, so the
8480            // permissions we have now selected are fixed until explicitly
8481            // changed.
8482            ps.installPermissionsFixed = true;
8483        }
8484
8485        // Persist the runtime permissions state for users with changes.
8486        for (int userId : changedRuntimePermissionUserIds) {
8487            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8488        }
8489    }
8490
8491    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8492        boolean allowed = false;
8493        final int NP = PackageParser.NEW_PERMISSIONS.length;
8494        for (int ip=0; ip<NP; ip++) {
8495            final PackageParser.NewPermissionInfo npi
8496                    = PackageParser.NEW_PERMISSIONS[ip];
8497            if (npi.name.equals(perm)
8498                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8499                allowed = true;
8500                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8501                        + pkg.packageName);
8502                break;
8503            }
8504        }
8505        return allowed;
8506    }
8507
8508    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8509            BasePermission bp, PermissionsState origPermissions) {
8510        boolean allowed;
8511        allowed = (compareSignatures(
8512                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8513                        == PackageManager.SIGNATURE_MATCH)
8514                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8515                        == PackageManager.SIGNATURE_MATCH);
8516        if (!allowed && (bp.protectionLevel
8517                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8518            if (isSystemApp(pkg)) {
8519                // For updated system applications, a system permission
8520                // is granted only if it had been defined by the original application.
8521                if (pkg.isUpdatedSystemApp()) {
8522                    final PackageSetting sysPs = mSettings
8523                            .getDisabledSystemPkgLPr(pkg.packageName);
8524                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8525                        // If the original was granted this permission, we take
8526                        // that grant decision as read and propagate it to the
8527                        // update.
8528                        if (sysPs.isPrivileged()) {
8529                            allowed = true;
8530                        }
8531                    } else {
8532                        // The system apk may have been updated with an older
8533                        // version of the one on the data partition, but which
8534                        // granted a new system permission that it didn't have
8535                        // before.  In this case we do want to allow the app to
8536                        // now get the new permission if the ancestral apk is
8537                        // privileged to get it.
8538                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8539                            for (int j=0;
8540                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8541                                if (perm.equals(
8542                                        sysPs.pkg.requestedPermissions.get(j))) {
8543                                    allowed = true;
8544                                    break;
8545                                }
8546                            }
8547                        }
8548                    }
8549                } else {
8550                    allowed = isPrivilegedApp(pkg);
8551                }
8552            }
8553        }
8554        if (!allowed) {
8555            if (!allowed && (bp.protectionLevel
8556                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8557                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8558                // If this was a previously normal/dangerous permission that got moved
8559                // to a system permission as part of the runtime permission redesign, then
8560                // we still want to blindly grant it to old apps.
8561                allowed = true;
8562            }
8563            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8564                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8565                // If this permission is to be granted to the system installer and
8566                // this app is an installer, then it gets the permission.
8567                allowed = true;
8568            }
8569            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8570                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8571                // If this permission is to be granted to the system verifier and
8572                // this app is a verifier, then it gets the permission.
8573                allowed = true;
8574            }
8575            if (!allowed && (bp.protectionLevel
8576                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8577                    && isSystemApp(pkg)) {
8578                // Any pre-installed system app is allowed to get this permission.
8579                allowed = true;
8580            }
8581            if (!allowed && (bp.protectionLevel
8582                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8583                // For development permissions, a development permission
8584                // is granted only if it was already granted.
8585                allowed = origPermissions.hasInstallPermission(perm);
8586            }
8587        }
8588        return allowed;
8589    }
8590
8591    final class ActivityIntentResolver
8592            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8593        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8594                boolean defaultOnly, int userId) {
8595            if (!sUserManager.exists(userId)) return null;
8596            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8597            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8598        }
8599
8600        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8601                int userId) {
8602            if (!sUserManager.exists(userId)) return null;
8603            mFlags = flags;
8604            return super.queryIntent(intent, resolvedType,
8605                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8606        }
8607
8608        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8609                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8610            if (!sUserManager.exists(userId)) return null;
8611            if (packageActivities == null) {
8612                return null;
8613            }
8614            mFlags = flags;
8615            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8616            final int N = packageActivities.size();
8617            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8618                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8619
8620            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8621            for (int i = 0; i < N; ++i) {
8622                intentFilters = packageActivities.get(i).intents;
8623                if (intentFilters != null && intentFilters.size() > 0) {
8624                    PackageParser.ActivityIntentInfo[] array =
8625                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8626                    intentFilters.toArray(array);
8627                    listCut.add(array);
8628                }
8629            }
8630            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8631        }
8632
8633        public final void addActivity(PackageParser.Activity a, String type) {
8634            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8635            mActivities.put(a.getComponentName(), a);
8636            if (DEBUG_SHOW_INFO)
8637                Log.v(
8638                TAG, "  " + type + " " +
8639                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8640            if (DEBUG_SHOW_INFO)
8641                Log.v(TAG, "    Class=" + a.info.name);
8642            final int NI = a.intents.size();
8643            for (int j=0; j<NI; j++) {
8644                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8645                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8646                    intent.setPriority(0);
8647                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8648                            + a.className + " with priority > 0, forcing to 0");
8649                }
8650                if (DEBUG_SHOW_INFO) {
8651                    Log.v(TAG, "    IntentFilter:");
8652                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8653                }
8654                if (!intent.debugCheck()) {
8655                    Log.w(TAG, "==> For Activity " + a.info.name);
8656                }
8657                addFilter(intent);
8658            }
8659        }
8660
8661        public final void removeActivity(PackageParser.Activity a, String type) {
8662            mActivities.remove(a.getComponentName());
8663            if (DEBUG_SHOW_INFO) {
8664                Log.v(TAG, "  " + type + " "
8665                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8666                                : a.info.name) + ":");
8667                Log.v(TAG, "    Class=" + a.info.name);
8668            }
8669            final int NI = a.intents.size();
8670            for (int j=0; j<NI; j++) {
8671                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8672                if (DEBUG_SHOW_INFO) {
8673                    Log.v(TAG, "    IntentFilter:");
8674                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8675                }
8676                removeFilter(intent);
8677            }
8678        }
8679
8680        @Override
8681        protected boolean allowFilterResult(
8682                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8683            ActivityInfo filterAi = filter.activity.info;
8684            for (int i=dest.size()-1; i>=0; i--) {
8685                ActivityInfo destAi = dest.get(i).activityInfo;
8686                if (destAi.name == filterAi.name
8687                        && destAi.packageName == filterAi.packageName) {
8688                    return false;
8689                }
8690            }
8691            return true;
8692        }
8693
8694        @Override
8695        protected ActivityIntentInfo[] newArray(int size) {
8696            return new ActivityIntentInfo[size];
8697        }
8698
8699        @Override
8700        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8701            if (!sUserManager.exists(userId)) return true;
8702            PackageParser.Package p = filter.activity.owner;
8703            if (p != null) {
8704                PackageSetting ps = (PackageSetting)p.mExtras;
8705                if (ps != null) {
8706                    // System apps are never considered stopped for purposes of
8707                    // filtering, because there may be no way for the user to
8708                    // actually re-launch them.
8709                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8710                            && ps.getStopped(userId);
8711                }
8712            }
8713            return false;
8714        }
8715
8716        @Override
8717        protected boolean isPackageForFilter(String packageName,
8718                PackageParser.ActivityIntentInfo info) {
8719            return packageName.equals(info.activity.owner.packageName);
8720        }
8721
8722        @Override
8723        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8724                int match, int userId) {
8725            if (!sUserManager.exists(userId)) return null;
8726            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8727                return null;
8728            }
8729            final PackageParser.Activity activity = info.activity;
8730            if (mSafeMode && (activity.info.applicationInfo.flags
8731                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8732                return null;
8733            }
8734            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8735            if (ps == null) {
8736                return null;
8737            }
8738            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8739                    ps.readUserState(userId), userId);
8740            if (ai == null) {
8741                return null;
8742            }
8743            final ResolveInfo res = new ResolveInfo();
8744            res.activityInfo = ai;
8745            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8746                res.filter = info;
8747            }
8748            if (info != null) {
8749                res.handleAllWebDataURI = info.handleAllWebDataURI();
8750            }
8751            res.priority = info.getPriority();
8752            res.preferredOrder = activity.owner.mPreferredOrder;
8753            //System.out.println("Result: " + res.activityInfo.className +
8754            //                   " = " + res.priority);
8755            res.match = match;
8756            res.isDefault = info.hasDefault;
8757            res.labelRes = info.labelRes;
8758            res.nonLocalizedLabel = info.nonLocalizedLabel;
8759            if (userNeedsBadging(userId)) {
8760                res.noResourceId = true;
8761            } else {
8762                res.icon = info.icon;
8763            }
8764            res.iconResourceId = info.icon;
8765            res.system = res.activityInfo.applicationInfo.isSystemApp();
8766            return res;
8767        }
8768
8769        @Override
8770        protected void sortResults(List<ResolveInfo> results) {
8771            Collections.sort(results, mResolvePrioritySorter);
8772        }
8773
8774        @Override
8775        protected void dumpFilter(PrintWriter out, String prefix,
8776                PackageParser.ActivityIntentInfo filter) {
8777            out.print(prefix); out.print(
8778                    Integer.toHexString(System.identityHashCode(filter.activity)));
8779                    out.print(' ');
8780                    filter.activity.printComponentShortName(out);
8781                    out.print(" filter ");
8782                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8783        }
8784
8785        @Override
8786        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8787            return filter.activity;
8788        }
8789
8790        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8791            PackageParser.Activity activity = (PackageParser.Activity)label;
8792            out.print(prefix); out.print(
8793                    Integer.toHexString(System.identityHashCode(activity)));
8794                    out.print(' ');
8795                    activity.printComponentShortName(out);
8796            if (count > 1) {
8797                out.print(" ("); out.print(count); out.print(" filters)");
8798            }
8799            out.println();
8800        }
8801
8802//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8803//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8804//            final List<ResolveInfo> retList = Lists.newArrayList();
8805//            while (i.hasNext()) {
8806//                final ResolveInfo resolveInfo = i.next();
8807//                if (isEnabledLP(resolveInfo.activityInfo)) {
8808//                    retList.add(resolveInfo);
8809//                }
8810//            }
8811//            return retList;
8812//        }
8813
8814        // Keys are String (activity class name), values are Activity.
8815        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8816                = new ArrayMap<ComponentName, PackageParser.Activity>();
8817        private int mFlags;
8818    }
8819
8820    private final class ServiceIntentResolver
8821            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8822        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8823                boolean defaultOnly, int userId) {
8824            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8825            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8826        }
8827
8828        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8829                int userId) {
8830            if (!sUserManager.exists(userId)) return null;
8831            mFlags = flags;
8832            return super.queryIntent(intent, resolvedType,
8833                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8834        }
8835
8836        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8837                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8838            if (!sUserManager.exists(userId)) return null;
8839            if (packageServices == null) {
8840                return null;
8841            }
8842            mFlags = flags;
8843            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8844            final int N = packageServices.size();
8845            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8846                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8847
8848            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8849            for (int i = 0; i < N; ++i) {
8850                intentFilters = packageServices.get(i).intents;
8851                if (intentFilters != null && intentFilters.size() > 0) {
8852                    PackageParser.ServiceIntentInfo[] array =
8853                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8854                    intentFilters.toArray(array);
8855                    listCut.add(array);
8856                }
8857            }
8858            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8859        }
8860
8861        public final void addService(PackageParser.Service s) {
8862            mServices.put(s.getComponentName(), s);
8863            if (DEBUG_SHOW_INFO) {
8864                Log.v(TAG, "  "
8865                        + (s.info.nonLocalizedLabel != null
8866                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8867                Log.v(TAG, "    Class=" + s.info.name);
8868            }
8869            final int NI = s.intents.size();
8870            int j;
8871            for (j=0; j<NI; j++) {
8872                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8873                if (DEBUG_SHOW_INFO) {
8874                    Log.v(TAG, "    IntentFilter:");
8875                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8876                }
8877                if (!intent.debugCheck()) {
8878                    Log.w(TAG, "==> For Service " + s.info.name);
8879                }
8880                addFilter(intent);
8881            }
8882        }
8883
8884        public final void removeService(PackageParser.Service s) {
8885            mServices.remove(s.getComponentName());
8886            if (DEBUG_SHOW_INFO) {
8887                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8888                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8889                Log.v(TAG, "    Class=" + s.info.name);
8890            }
8891            final int NI = s.intents.size();
8892            int j;
8893            for (j=0; j<NI; j++) {
8894                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8895                if (DEBUG_SHOW_INFO) {
8896                    Log.v(TAG, "    IntentFilter:");
8897                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8898                }
8899                removeFilter(intent);
8900            }
8901        }
8902
8903        @Override
8904        protected boolean allowFilterResult(
8905                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8906            ServiceInfo filterSi = filter.service.info;
8907            for (int i=dest.size()-1; i>=0; i--) {
8908                ServiceInfo destAi = dest.get(i).serviceInfo;
8909                if (destAi.name == filterSi.name
8910                        && destAi.packageName == filterSi.packageName) {
8911                    return false;
8912                }
8913            }
8914            return true;
8915        }
8916
8917        @Override
8918        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8919            return new PackageParser.ServiceIntentInfo[size];
8920        }
8921
8922        @Override
8923        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8924            if (!sUserManager.exists(userId)) return true;
8925            PackageParser.Package p = filter.service.owner;
8926            if (p != null) {
8927                PackageSetting ps = (PackageSetting)p.mExtras;
8928                if (ps != null) {
8929                    // System apps are never considered stopped for purposes of
8930                    // filtering, because there may be no way for the user to
8931                    // actually re-launch them.
8932                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8933                            && ps.getStopped(userId);
8934                }
8935            }
8936            return false;
8937        }
8938
8939        @Override
8940        protected boolean isPackageForFilter(String packageName,
8941                PackageParser.ServiceIntentInfo info) {
8942            return packageName.equals(info.service.owner.packageName);
8943        }
8944
8945        @Override
8946        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8947                int match, int userId) {
8948            if (!sUserManager.exists(userId)) return null;
8949            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8950            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8951                return null;
8952            }
8953            final PackageParser.Service service = info.service;
8954            if (mSafeMode && (service.info.applicationInfo.flags
8955                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8956                return null;
8957            }
8958            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8959            if (ps == null) {
8960                return null;
8961            }
8962            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8963                    ps.readUserState(userId), userId);
8964            if (si == null) {
8965                return null;
8966            }
8967            final ResolveInfo res = new ResolveInfo();
8968            res.serviceInfo = si;
8969            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8970                res.filter = filter;
8971            }
8972            res.priority = info.getPriority();
8973            res.preferredOrder = service.owner.mPreferredOrder;
8974            res.match = match;
8975            res.isDefault = info.hasDefault;
8976            res.labelRes = info.labelRes;
8977            res.nonLocalizedLabel = info.nonLocalizedLabel;
8978            res.icon = info.icon;
8979            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8980            return res;
8981        }
8982
8983        @Override
8984        protected void sortResults(List<ResolveInfo> results) {
8985            Collections.sort(results, mResolvePrioritySorter);
8986        }
8987
8988        @Override
8989        protected void dumpFilter(PrintWriter out, String prefix,
8990                PackageParser.ServiceIntentInfo filter) {
8991            out.print(prefix); out.print(
8992                    Integer.toHexString(System.identityHashCode(filter.service)));
8993                    out.print(' ');
8994                    filter.service.printComponentShortName(out);
8995                    out.print(" filter ");
8996                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8997        }
8998
8999        @Override
9000        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9001            return filter.service;
9002        }
9003
9004        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9005            PackageParser.Service service = (PackageParser.Service)label;
9006            out.print(prefix); out.print(
9007                    Integer.toHexString(System.identityHashCode(service)));
9008                    out.print(' ');
9009                    service.printComponentShortName(out);
9010            if (count > 1) {
9011                out.print(" ("); out.print(count); out.print(" filters)");
9012            }
9013            out.println();
9014        }
9015
9016//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9017//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9018//            final List<ResolveInfo> retList = Lists.newArrayList();
9019//            while (i.hasNext()) {
9020//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9021//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9022//                    retList.add(resolveInfo);
9023//                }
9024//            }
9025//            return retList;
9026//        }
9027
9028        // Keys are String (activity class name), values are Activity.
9029        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9030                = new ArrayMap<ComponentName, PackageParser.Service>();
9031        private int mFlags;
9032    };
9033
9034    private final class ProviderIntentResolver
9035            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9036        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9037                boolean defaultOnly, int userId) {
9038            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9039            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9040        }
9041
9042        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9043                int userId) {
9044            if (!sUserManager.exists(userId))
9045                return null;
9046            mFlags = flags;
9047            return super.queryIntent(intent, resolvedType,
9048                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9049        }
9050
9051        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9052                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9053            if (!sUserManager.exists(userId))
9054                return null;
9055            if (packageProviders == null) {
9056                return null;
9057            }
9058            mFlags = flags;
9059            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9060            final int N = packageProviders.size();
9061            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9062                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9063
9064            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9065            for (int i = 0; i < N; ++i) {
9066                intentFilters = packageProviders.get(i).intents;
9067                if (intentFilters != null && intentFilters.size() > 0) {
9068                    PackageParser.ProviderIntentInfo[] array =
9069                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9070                    intentFilters.toArray(array);
9071                    listCut.add(array);
9072                }
9073            }
9074            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9075        }
9076
9077        public final void addProvider(PackageParser.Provider p) {
9078            if (mProviders.containsKey(p.getComponentName())) {
9079                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9080                return;
9081            }
9082
9083            mProviders.put(p.getComponentName(), p);
9084            if (DEBUG_SHOW_INFO) {
9085                Log.v(TAG, "  "
9086                        + (p.info.nonLocalizedLabel != null
9087                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9088                Log.v(TAG, "    Class=" + p.info.name);
9089            }
9090            final int NI = p.intents.size();
9091            int j;
9092            for (j = 0; j < NI; j++) {
9093                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9094                if (DEBUG_SHOW_INFO) {
9095                    Log.v(TAG, "    IntentFilter:");
9096                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9097                }
9098                if (!intent.debugCheck()) {
9099                    Log.w(TAG, "==> For Provider " + p.info.name);
9100                }
9101                addFilter(intent);
9102            }
9103        }
9104
9105        public final void removeProvider(PackageParser.Provider p) {
9106            mProviders.remove(p.getComponentName());
9107            if (DEBUG_SHOW_INFO) {
9108                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9109                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9110                Log.v(TAG, "    Class=" + p.info.name);
9111            }
9112            final int NI = p.intents.size();
9113            int j;
9114            for (j = 0; j < NI; j++) {
9115                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9116                if (DEBUG_SHOW_INFO) {
9117                    Log.v(TAG, "    IntentFilter:");
9118                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9119                }
9120                removeFilter(intent);
9121            }
9122        }
9123
9124        @Override
9125        protected boolean allowFilterResult(
9126                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9127            ProviderInfo filterPi = filter.provider.info;
9128            for (int i = dest.size() - 1; i >= 0; i--) {
9129                ProviderInfo destPi = dest.get(i).providerInfo;
9130                if (destPi.name == filterPi.name
9131                        && destPi.packageName == filterPi.packageName) {
9132                    return false;
9133                }
9134            }
9135            return true;
9136        }
9137
9138        @Override
9139        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9140            return new PackageParser.ProviderIntentInfo[size];
9141        }
9142
9143        @Override
9144        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9145            if (!sUserManager.exists(userId))
9146                return true;
9147            PackageParser.Package p = filter.provider.owner;
9148            if (p != null) {
9149                PackageSetting ps = (PackageSetting) p.mExtras;
9150                if (ps != null) {
9151                    // System apps are never considered stopped for purposes of
9152                    // filtering, because there may be no way for the user to
9153                    // actually re-launch them.
9154                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9155                            && ps.getStopped(userId);
9156                }
9157            }
9158            return false;
9159        }
9160
9161        @Override
9162        protected boolean isPackageForFilter(String packageName,
9163                PackageParser.ProviderIntentInfo info) {
9164            return packageName.equals(info.provider.owner.packageName);
9165        }
9166
9167        @Override
9168        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9169                int match, int userId) {
9170            if (!sUserManager.exists(userId))
9171                return null;
9172            final PackageParser.ProviderIntentInfo info = filter;
9173            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9174                return null;
9175            }
9176            final PackageParser.Provider provider = info.provider;
9177            if (mSafeMode && (provider.info.applicationInfo.flags
9178                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9179                return null;
9180            }
9181            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9182            if (ps == null) {
9183                return null;
9184            }
9185            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9186                    ps.readUserState(userId), userId);
9187            if (pi == null) {
9188                return null;
9189            }
9190            final ResolveInfo res = new ResolveInfo();
9191            res.providerInfo = pi;
9192            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9193                res.filter = filter;
9194            }
9195            res.priority = info.getPriority();
9196            res.preferredOrder = provider.owner.mPreferredOrder;
9197            res.match = match;
9198            res.isDefault = info.hasDefault;
9199            res.labelRes = info.labelRes;
9200            res.nonLocalizedLabel = info.nonLocalizedLabel;
9201            res.icon = info.icon;
9202            res.system = res.providerInfo.applicationInfo.isSystemApp();
9203            return res;
9204        }
9205
9206        @Override
9207        protected void sortResults(List<ResolveInfo> results) {
9208            Collections.sort(results, mResolvePrioritySorter);
9209        }
9210
9211        @Override
9212        protected void dumpFilter(PrintWriter out, String prefix,
9213                PackageParser.ProviderIntentInfo filter) {
9214            out.print(prefix);
9215            out.print(
9216                    Integer.toHexString(System.identityHashCode(filter.provider)));
9217            out.print(' ');
9218            filter.provider.printComponentShortName(out);
9219            out.print(" filter ");
9220            out.println(Integer.toHexString(System.identityHashCode(filter)));
9221        }
9222
9223        @Override
9224        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9225            return filter.provider;
9226        }
9227
9228        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9229            PackageParser.Provider provider = (PackageParser.Provider)label;
9230            out.print(prefix); out.print(
9231                    Integer.toHexString(System.identityHashCode(provider)));
9232                    out.print(' ');
9233                    provider.printComponentShortName(out);
9234            if (count > 1) {
9235                out.print(" ("); out.print(count); out.print(" filters)");
9236            }
9237            out.println();
9238        }
9239
9240        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9241                = new ArrayMap<ComponentName, PackageParser.Provider>();
9242        private int mFlags;
9243    };
9244
9245    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9246            new Comparator<ResolveInfo>() {
9247        public int compare(ResolveInfo r1, ResolveInfo r2) {
9248            int v1 = r1.priority;
9249            int v2 = r2.priority;
9250            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9251            if (v1 != v2) {
9252                return (v1 > v2) ? -1 : 1;
9253            }
9254            v1 = r1.preferredOrder;
9255            v2 = r2.preferredOrder;
9256            if (v1 != v2) {
9257                return (v1 > v2) ? -1 : 1;
9258            }
9259            if (r1.isDefault != r2.isDefault) {
9260                return r1.isDefault ? -1 : 1;
9261            }
9262            v1 = r1.match;
9263            v2 = r2.match;
9264            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9265            if (v1 != v2) {
9266                return (v1 > v2) ? -1 : 1;
9267            }
9268            if (r1.system != r2.system) {
9269                return r1.system ? -1 : 1;
9270            }
9271            return 0;
9272        }
9273    };
9274
9275    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9276            new Comparator<ProviderInfo>() {
9277        public int compare(ProviderInfo p1, ProviderInfo p2) {
9278            final int v1 = p1.initOrder;
9279            final int v2 = p2.initOrder;
9280            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9281        }
9282    };
9283
9284    final void sendPackageBroadcast(final String action, final String pkg,
9285            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9286            final int[] userIds) {
9287        mHandler.post(new Runnable() {
9288            @Override
9289            public void run() {
9290                try {
9291                    final IActivityManager am = ActivityManagerNative.getDefault();
9292                    if (am == null) return;
9293                    final int[] resolvedUserIds;
9294                    if (userIds == null) {
9295                        resolvedUserIds = am.getRunningUserIds();
9296                    } else {
9297                        resolvedUserIds = userIds;
9298                    }
9299                    for (int id : resolvedUserIds) {
9300                        final Intent intent = new Intent(action,
9301                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9302                        if (extras != null) {
9303                            intent.putExtras(extras);
9304                        }
9305                        if (targetPkg != null) {
9306                            intent.setPackage(targetPkg);
9307                        }
9308                        // Modify the UID when posting to other users
9309                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9310                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9311                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9312                            intent.putExtra(Intent.EXTRA_UID, uid);
9313                        }
9314                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9315                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9316                        if (DEBUG_BROADCASTS) {
9317                            RuntimeException here = new RuntimeException("here");
9318                            here.fillInStackTrace();
9319                            Slog.d(TAG, "Sending to user " + id + ": "
9320                                    + intent.toShortString(false, true, false, false)
9321                                    + " " + intent.getExtras(), here);
9322                        }
9323                        am.broadcastIntent(null, intent, null, finishedReceiver,
9324                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9325                                null, finishedReceiver != null, false, id);
9326                    }
9327                } catch (RemoteException ex) {
9328                }
9329            }
9330        });
9331    }
9332
9333    /**
9334     * Check if the external storage media is available. This is true if there
9335     * is a mounted external storage medium or if the external storage is
9336     * emulated.
9337     */
9338    private boolean isExternalMediaAvailable() {
9339        return mMediaMounted || Environment.isExternalStorageEmulated();
9340    }
9341
9342    @Override
9343    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9344        // writer
9345        synchronized (mPackages) {
9346            if (!isExternalMediaAvailable()) {
9347                // If the external storage is no longer mounted at this point,
9348                // the caller may not have been able to delete all of this
9349                // packages files and can not delete any more.  Bail.
9350                return null;
9351            }
9352            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9353            if (lastPackage != null) {
9354                pkgs.remove(lastPackage);
9355            }
9356            if (pkgs.size() > 0) {
9357                return pkgs.get(0);
9358            }
9359        }
9360        return null;
9361    }
9362
9363    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9364        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9365                userId, andCode ? 1 : 0, packageName);
9366        if (mSystemReady) {
9367            msg.sendToTarget();
9368        } else {
9369            if (mPostSystemReadyMessages == null) {
9370                mPostSystemReadyMessages = new ArrayList<>();
9371            }
9372            mPostSystemReadyMessages.add(msg);
9373        }
9374    }
9375
9376    void startCleaningPackages() {
9377        // reader
9378        synchronized (mPackages) {
9379            if (!isExternalMediaAvailable()) {
9380                return;
9381            }
9382            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9383                return;
9384            }
9385        }
9386        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9387        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9388        IActivityManager am = ActivityManagerNative.getDefault();
9389        if (am != null) {
9390            try {
9391                am.startService(null, intent, null, mContext.getOpPackageName(),
9392                        UserHandle.USER_OWNER);
9393            } catch (RemoteException e) {
9394            }
9395        }
9396    }
9397
9398    @Override
9399    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9400            int installFlags, String installerPackageName, VerificationParams verificationParams,
9401            String packageAbiOverride) {
9402        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9403                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9404    }
9405
9406    @Override
9407    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9408            int installFlags, String installerPackageName, VerificationParams verificationParams,
9409            String packageAbiOverride, int userId) {
9410        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9411
9412        final int callingUid = Binder.getCallingUid();
9413        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9414
9415        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9416            try {
9417                if (observer != null) {
9418                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9419                }
9420            } catch (RemoteException re) {
9421            }
9422            return;
9423        }
9424
9425        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9426            installFlags |= PackageManager.INSTALL_FROM_ADB;
9427
9428        } else {
9429            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9430            // about installerPackageName.
9431
9432            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9433            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9434        }
9435
9436        UserHandle user;
9437        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9438            user = UserHandle.ALL;
9439        } else {
9440            user = new UserHandle(userId);
9441        }
9442
9443        // Only system components can circumvent runtime permissions when installing.
9444        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9445                && mContext.checkCallingOrSelfPermission(Manifest.permission
9446                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9447            throw new SecurityException("You need the "
9448                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9449                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9450        }
9451
9452        verificationParams.setInstallerUid(callingUid);
9453
9454        final File originFile = new File(originPath);
9455        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9456
9457        final Message msg = mHandler.obtainMessage(INIT_COPY);
9458        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9459                null, verificationParams, user, packageAbiOverride);
9460        mHandler.sendMessage(msg);
9461    }
9462
9463    void installStage(String packageName, File stagedDir, String stagedCid,
9464            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9465            String installerPackageName, int installerUid, UserHandle user) {
9466        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9467                params.referrerUri, installerUid, null);
9468        verifParams.setInstallerUid(installerUid);
9469
9470        final OriginInfo origin;
9471        if (stagedDir != null) {
9472            origin = OriginInfo.fromStagedFile(stagedDir);
9473        } else {
9474            origin = OriginInfo.fromStagedContainer(stagedCid);
9475        }
9476
9477        final Message msg = mHandler.obtainMessage(INIT_COPY);
9478        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9479                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9480        mHandler.sendMessage(msg);
9481    }
9482
9483    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9484        Bundle extras = new Bundle(1);
9485        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9486
9487        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9488                packageName, extras, null, null, new int[] {userId});
9489        try {
9490            IActivityManager am = ActivityManagerNative.getDefault();
9491            final boolean isSystem =
9492                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9493            if (isSystem && am.isUserRunning(userId, false)) {
9494                // The just-installed/enabled app is bundled on the system, so presumed
9495                // to be able to run automatically without needing an explicit launch.
9496                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9497                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9498                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9499                        .setPackage(packageName);
9500                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9501                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9502            }
9503        } catch (RemoteException e) {
9504            // shouldn't happen
9505            Slog.w(TAG, "Unable to bootstrap installed package", e);
9506        }
9507    }
9508
9509    @Override
9510    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9511            int userId) {
9512        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9513        PackageSetting pkgSetting;
9514        final int uid = Binder.getCallingUid();
9515        enforceCrossUserPermission(uid, userId, true, true,
9516                "setApplicationHiddenSetting for user " + userId);
9517
9518        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9519            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9520            return false;
9521        }
9522
9523        long callingId = Binder.clearCallingIdentity();
9524        try {
9525            boolean sendAdded = false;
9526            boolean sendRemoved = false;
9527            // writer
9528            synchronized (mPackages) {
9529                pkgSetting = mSettings.mPackages.get(packageName);
9530                if (pkgSetting == null) {
9531                    return false;
9532                }
9533                if (pkgSetting.getHidden(userId) != hidden) {
9534                    pkgSetting.setHidden(hidden, userId);
9535                    mSettings.writePackageRestrictionsLPr(userId);
9536                    if (hidden) {
9537                        sendRemoved = true;
9538                    } else {
9539                        sendAdded = true;
9540                    }
9541                }
9542            }
9543            if (sendAdded) {
9544                sendPackageAddedForUser(packageName, pkgSetting, userId);
9545                return true;
9546            }
9547            if (sendRemoved) {
9548                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9549                        "hiding pkg");
9550                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9551            }
9552        } finally {
9553            Binder.restoreCallingIdentity(callingId);
9554        }
9555        return false;
9556    }
9557
9558    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9559            int userId) {
9560        final PackageRemovedInfo info = new PackageRemovedInfo();
9561        info.removedPackage = packageName;
9562        info.removedUsers = new int[] {userId};
9563        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9564        info.sendBroadcast(false, false, false);
9565    }
9566
9567    /**
9568     * Returns true if application is not found or there was an error. Otherwise it returns
9569     * the hidden state of the package for the given user.
9570     */
9571    @Override
9572    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9573        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9574        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9575                false, "getApplicationHidden for user " + userId);
9576        PackageSetting pkgSetting;
9577        long callingId = Binder.clearCallingIdentity();
9578        try {
9579            // writer
9580            synchronized (mPackages) {
9581                pkgSetting = mSettings.mPackages.get(packageName);
9582                if (pkgSetting == null) {
9583                    return true;
9584                }
9585                return pkgSetting.getHidden(userId);
9586            }
9587        } finally {
9588            Binder.restoreCallingIdentity(callingId);
9589        }
9590    }
9591
9592    /**
9593     * @hide
9594     */
9595    @Override
9596    public int installExistingPackageAsUser(String packageName, int userId) {
9597        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9598                null);
9599        PackageSetting pkgSetting;
9600        final int uid = Binder.getCallingUid();
9601        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9602                + userId);
9603        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9604            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9605        }
9606
9607        long callingId = Binder.clearCallingIdentity();
9608        try {
9609            boolean sendAdded = false;
9610
9611            // writer
9612            synchronized (mPackages) {
9613                pkgSetting = mSettings.mPackages.get(packageName);
9614                if (pkgSetting == null) {
9615                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9616                }
9617                if (!pkgSetting.getInstalled(userId)) {
9618                    pkgSetting.setInstalled(true, userId);
9619                    pkgSetting.setHidden(false, userId);
9620                    mSettings.writePackageRestrictionsLPr(userId);
9621                    sendAdded = true;
9622                }
9623            }
9624
9625            if (sendAdded) {
9626                sendPackageAddedForUser(packageName, pkgSetting, userId);
9627            }
9628        } finally {
9629            Binder.restoreCallingIdentity(callingId);
9630        }
9631
9632        return PackageManager.INSTALL_SUCCEEDED;
9633    }
9634
9635    boolean isUserRestricted(int userId, String restrictionKey) {
9636        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9637        if (restrictions.getBoolean(restrictionKey, false)) {
9638            Log.w(TAG, "User is restricted: " + restrictionKey);
9639            return true;
9640        }
9641        return false;
9642    }
9643
9644    @Override
9645    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9646        mContext.enforceCallingOrSelfPermission(
9647                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9648                "Only package verification agents can verify applications");
9649
9650        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9651        final PackageVerificationResponse response = new PackageVerificationResponse(
9652                verificationCode, Binder.getCallingUid());
9653        msg.arg1 = id;
9654        msg.obj = response;
9655        mHandler.sendMessage(msg);
9656    }
9657
9658    @Override
9659    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9660            long millisecondsToDelay) {
9661        mContext.enforceCallingOrSelfPermission(
9662                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9663                "Only package verification agents can extend verification timeouts");
9664
9665        final PackageVerificationState state = mPendingVerification.get(id);
9666        final PackageVerificationResponse response = new PackageVerificationResponse(
9667                verificationCodeAtTimeout, Binder.getCallingUid());
9668
9669        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9670            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9671        }
9672        if (millisecondsToDelay < 0) {
9673            millisecondsToDelay = 0;
9674        }
9675        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9676                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9677            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9678        }
9679
9680        if ((state != null) && !state.timeoutExtended()) {
9681            state.extendTimeout();
9682
9683            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9684            msg.arg1 = id;
9685            msg.obj = response;
9686            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9687        }
9688    }
9689
9690    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9691            int verificationCode, UserHandle user) {
9692        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9693        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9694        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9695        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9696        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9697
9698        mContext.sendBroadcastAsUser(intent, user,
9699                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9700    }
9701
9702    private ComponentName matchComponentForVerifier(String packageName,
9703            List<ResolveInfo> receivers) {
9704        ActivityInfo targetReceiver = null;
9705
9706        final int NR = receivers.size();
9707        for (int i = 0; i < NR; i++) {
9708            final ResolveInfo info = receivers.get(i);
9709            if (info.activityInfo == null) {
9710                continue;
9711            }
9712
9713            if (packageName.equals(info.activityInfo.packageName)) {
9714                targetReceiver = info.activityInfo;
9715                break;
9716            }
9717        }
9718
9719        if (targetReceiver == null) {
9720            return null;
9721        }
9722
9723        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9724    }
9725
9726    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9727            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9728        if (pkgInfo.verifiers.length == 0) {
9729            return null;
9730        }
9731
9732        final int N = pkgInfo.verifiers.length;
9733        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9734        for (int i = 0; i < N; i++) {
9735            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9736
9737            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9738                    receivers);
9739            if (comp == null) {
9740                continue;
9741            }
9742
9743            final int verifierUid = getUidForVerifier(verifierInfo);
9744            if (verifierUid == -1) {
9745                continue;
9746            }
9747
9748            if (DEBUG_VERIFY) {
9749                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9750                        + " with the correct signature");
9751            }
9752            sufficientVerifiers.add(comp);
9753            verificationState.addSufficientVerifier(verifierUid);
9754        }
9755
9756        return sufficientVerifiers;
9757    }
9758
9759    private int getUidForVerifier(VerifierInfo verifierInfo) {
9760        synchronized (mPackages) {
9761            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9762            if (pkg == null) {
9763                return -1;
9764            } else if (pkg.mSignatures.length != 1) {
9765                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9766                        + " has more than one signature; ignoring");
9767                return -1;
9768            }
9769
9770            /*
9771             * If the public key of the package's signature does not match
9772             * our expected public key, then this is a different package and
9773             * we should skip.
9774             */
9775
9776            final byte[] expectedPublicKey;
9777            try {
9778                final Signature verifierSig = pkg.mSignatures[0];
9779                final PublicKey publicKey = verifierSig.getPublicKey();
9780                expectedPublicKey = publicKey.getEncoded();
9781            } catch (CertificateException e) {
9782                return -1;
9783            }
9784
9785            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9786
9787            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9788                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9789                        + " does not have the expected public key; ignoring");
9790                return -1;
9791            }
9792
9793            return pkg.applicationInfo.uid;
9794        }
9795    }
9796
9797    @Override
9798    public void finishPackageInstall(int token) {
9799        enforceSystemOrRoot("Only the system is allowed to finish installs");
9800
9801        if (DEBUG_INSTALL) {
9802            Slog.v(TAG, "BM finishing package install for " + token);
9803        }
9804
9805        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9806        mHandler.sendMessage(msg);
9807    }
9808
9809    /**
9810     * Get the verification agent timeout.
9811     *
9812     * @return verification timeout in milliseconds
9813     */
9814    private long getVerificationTimeout() {
9815        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9816                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9817                DEFAULT_VERIFICATION_TIMEOUT);
9818    }
9819
9820    /**
9821     * Get the default verification agent response code.
9822     *
9823     * @return default verification response code
9824     */
9825    private int getDefaultVerificationResponse() {
9826        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9827                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9828                DEFAULT_VERIFICATION_RESPONSE);
9829    }
9830
9831    /**
9832     * Check whether or not package verification has been enabled.
9833     *
9834     * @return true if verification should be performed
9835     */
9836    private boolean isVerificationEnabled(int userId, int installFlags) {
9837        if (!DEFAULT_VERIFY_ENABLE) {
9838            return false;
9839        }
9840
9841        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9842
9843        // Check if installing from ADB
9844        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9845            // Do not run verification in a test harness environment
9846            if (ActivityManager.isRunningInTestHarness()) {
9847                return false;
9848            }
9849            if (ensureVerifyAppsEnabled) {
9850                return true;
9851            }
9852            // Check if the developer does not want package verification for ADB installs
9853            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9854                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9855                return false;
9856            }
9857        }
9858
9859        if (ensureVerifyAppsEnabled) {
9860            return true;
9861        }
9862
9863        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9864                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9865    }
9866
9867    @Override
9868    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9869            throws RemoteException {
9870        mContext.enforceCallingOrSelfPermission(
9871                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9872                "Only intentfilter verification agents can verify applications");
9873
9874        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9875        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9876                Binder.getCallingUid(), verificationCode, failedDomains);
9877        msg.arg1 = id;
9878        msg.obj = response;
9879        mHandler.sendMessage(msg);
9880    }
9881
9882    @Override
9883    public int getIntentVerificationStatus(String packageName, int userId) {
9884        synchronized (mPackages) {
9885            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9886        }
9887    }
9888
9889    @Override
9890    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9891        mContext.enforceCallingOrSelfPermission(
9892                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9893
9894        boolean result = false;
9895        synchronized (mPackages) {
9896            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9897        }
9898        if (result) {
9899            scheduleWritePackageRestrictionsLocked(userId);
9900        }
9901        return result;
9902    }
9903
9904    @Override
9905    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9906        synchronized (mPackages) {
9907            return mSettings.getIntentFilterVerificationsLPr(packageName);
9908        }
9909    }
9910
9911    @Override
9912    public List<IntentFilter> getAllIntentFilters(String packageName) {
9913        if (TextUtils.isEmpty(packageName)) {
9914            return Collections.<IntentFilter>emptyList();
9915        }
9916        synchronized (mPackages) {
9917            PackageParser.Package pkg = mPackages.get(packageName);
9918            if (pkg == null || pkg.activities == null) {
9919                return Collections.<IntentFilter>emptyList();
9920            }
9921            final int count = pkg.activities.size();
9922            ArrayList<IntentFilter> result = new ArrayList<>();
9923            for (int n=0; n<count; n++) {
9924                PackageParser.Activity activity = pkg.activities.get(n);
9925                if (activity.intents != null || activity.intents.size() > 0) {
9926                    result.addAll(activity.intents);
9927                }
9928            }
9929            return result;
9930        }
9931    }
9932
9933    @Override
9934    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9935        mContext.enforceCallingOrSelfPermission(
9936                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9937
9938        synchronized (mPackages) {
9939            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9940            if (packageName != null) {
9941                result |= updateIntentVerificationStatus(packageName,
9942                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9943                        UserHandle.myUserId());
9944                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9945                        packageName, userId);
9946            }
9947            return result;
9948        }
9949    }
9950
9951    @Override
9952    public String getDefaultBrowserPackageName(int userId) {
9953        synchronized (mPackages) {
9954            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9955        }
9956    }
9957
9958    /**
9959     * Get the "allow unknown sources" setting.
9960     *
9961     * @return the current "allow unknown sources" setting
9962     */
9963    private int getUnknownSourcesSettings() {
9964        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9965                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9966                -1);
9967    }
9968
9969    @Override
9970    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9971        final int uid = Binder.getCallingUid();
9972        // writer
9973        synchronized (mPackages) {
9974            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9975            if (targetPackageSetting == null) {
9976                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9977            }
9978
9979            PackageSetting installerPackageSetting;
9980            if (installerPackageName != null) {
9981                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9982                if (installerPackageSetting == null) {
9983                    throw new IllegalArgumentException("Unknown installer package: "
9984                            + installerPackageName);
9985                }
9986            } else {
9987                installerPackageSetting = null;
9988            }
9989
9990            Signature[] callerSignature;
9991            Object obj = mSettings.getUserIdLPr(uid);
9992            if (obj != null) {
9993                if (obj instanceof SharedUserSetting) {
9994                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9995                } else if (obj instanceof PackageSetting) {
9996                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9997                } else {
9998                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9999                }
10000            } else {
10001                throw new SecurityException("Unknown calling uid " + uid);
10002            }
10003
10004            // Verify: can't set installerPackageName to a package that is
10005            // not signed with the same cert as the caller.
10006            if (installerPackageSetting != null) {
10007                if (compareSignatures(callerSignature,
10008                        installerPackageSetting.signatures.mSignatures)
10009                        != PackageManager.SIGNATURE_MATCH) {
10010                    throw new SecurityException(
10011                            "Caller does not have same cert as new installer package "
10012                            + installerPackageName);
10013                }
10014            }
10015
10016            // Verify: if target already has an installer package, it must
10017            // be signed with the same cert as the caller.
10018            if (targetPackageSetting.installerPackageName != null) {
10019                PackageSetting setting = mSettings.mPackages.get(
10020                        targetPackageSetting.installerPackageName);
10021                // If the currently set package isn't valid, then it's always
10022                // okay to change it.
10023                if (setting != null) {
10024                    if (compareSignatures(callerSignature,
10025                            setting.signatures.mSignatures)
10026                            != PackageManager.SIGNATURE_MATCH) {
10027                        throw new SecurityException(
10028                                "Caller does not have same cert as old installer package "
10029                                + targetPackageSetting.installerPackageName);
10030                    }
10031                }
10032            }
10033
10034            // Okay!
10035            targetPackageSetting.installerPackageName = installerPackageName;
10036            scheduleWriteSettingsLocked();
10037        }
10038    }
10039
10040    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10041        // Queue up an async operation since the package installation may take a little while.
10042        mHandler.post(new Runnable() {
10043            public void run() {
10044                mHandler.removeCallbacks(this);
10045                 // Result object to be returned
10046                PackageInstalledInfo res = new PackageInstalledInfo();
10047                res.returnCode = currentStatus;
10048                res.uid = -1;
10049                res.pkg = null;
10050                res.removedInfo = new PackageRemovedInfo();
10051                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10052                    args.doPreInstall(res.returnCode);
10053                    synchronized (mInstallLock) {
10054                        installPackageLI(args, res);
10055                    }
10056                    args.doPostInstall(res.returnCode, res.uid);
10057                }
10058
10059                // A restore should be performed at this point if (a) the install
10060                // succeeded, (b) the operation is not an update, and (c) the new
10061                // package has not opted out of backup participation.
10062                final boolean update = res.removedInfo.removedPackage != null;
10063                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10064                boolean doRestore = !update
10065                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10066
10067                // Set up the post-install work request bookkeeping.  This will be used
10068                // and cleaned up by the post-install event handling regardless of whether
10069                // there's a restore pass performed.  Token values are >= 1.
10070                int token;
10071                if (mNextInstallToken < 0) mNextInstallToken = 1;
10072                token = mNextInstallToken++;
10073
10074                PostInstallData data = new PostInstallData(args, res);
10075                mRunningInstalls.put(token, data);
10076                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10077
10078                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10079                    // Pass responsibility to the Backup Manager.  It will perform a
10080                    // restore if appropriate, then pass responsibility back to the
10081                    // Package Manager to run the post-install observer callbacks
10082                    // and broadcasts.
10083                    IBackupManager bm = IBackupManager.Stub.asInterface(
10084                            ServiceManager.getService(Context.BACKUP_SERVICE));
10085                    if (bm != null) {
10086                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10087                                + " to BM for possible restore");
10088                        try {
10089                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10090                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10091                            } else {
10092                                doRestore = false;
10093                            }
10094                        } catch (RemoteException e) {
10095                            // can't happen; the backup manager is local
10096                        } catch (Exception e) {
10097                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10098                            doRestore = false;
10099                        }
10100                    } else {
10101                        Slog.e(TAG, "Backup Manager not found!");
10102                        doRestore = false;
10103                    }
10104                }
10105
10106                if (!doRestore) {
10107                    // No restore possible, or the Backup Manager was mysteriously not
10108                    // available -- just fire the post-install work request directly.
10109                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10110                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10111                    mHandler.sendMessage(msg);
10112                }
10113            }
10114        });
10115    }
10116
10117    private abstract class HandlerParams {
10118        private static final int MAX_RETRIES = 4;
10119
10120        /**
10121         * Number of times startCopy() has been attempted and had a non-fatal
10122         * error.
10123         */
10124        private int mRetries = 0;
10125
10126        /** User handle for the user requesting the information or installation. */
10127        private final UserHandle mUser;
10128
10129        HandlerParams(UserHandle user) {
10130            mUser = user;
10131        }
10132
10133        UserHandle getUser() {
10134            return mUser;
10135        }
10136
10137        final boolean startCopy() {
10138            boolean res;
10139            try {
10140                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10141
10142                if (++mRetries > MAX_RETRIES) {
10143                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10144                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10145                    handleServiceError();
10146                    return false;
10147                } else {
10148                    handleStartCopy();
10149                    res = true;
10150                }
10151            } catch (RemoteException e) {
10152                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10153                mHandler.sendEmptyMessage(MCS_RECONNECT);
10154                res = false;
10155            }
10156            handleReturnCode();
10157            return res;
10158        }
10159
10160        final void serviceError() {
10161            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10162            handleServiceError();
10163            handleReturnCode();
10164        }
10165
10166        abstract void handleStartCopy() throws RemoteException;
10167        abstract void handleServiceError();
10168        abstract void handleReturnCode();
10169    }
10170
10171    class MeasureParams extends HandlerParams {
10172        private final PackageStats mStats;
10173        private boolean mSuccess;
10174
10175        private final IPackageStatsObserver mObserver;
10176
10177        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10178            super(new UserHandle(stats.userHandle));
10179            mObserver = observer;
10180            mStats = stats;
10181        }
10182
10183        @Override
10184        public String toString() {
10185            return "MeasureParams{"
10186                + Integer.toHexString(System.identityHashCode(this))
10187                + " " + mStats.packageName + "}";
10188        }
10189
10190        @Override
10191        void handleStartCopy() throws RemoteException {
10192            synchronized (mInstallLock) {
10193                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10194            }
10195
10196            if (mSuccess) {
10197                final boolean mounted;
10198                if (Environment.isExternalStorageEmulated()) {
10199                    mounted = true;
10200                } else {
10201                    final String status = Environment.getExternalStorageState();
10202                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10203                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10204                }
10205
10206                if (mounted) {
10207                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10208
10209                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10210                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10211
10212                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10213                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10214
10215                    // Always subtract cache size, since it's a subdirectory
10216                    mStats.externalDataSize -= mStats.externalCacheSize;
10217
10218                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10219                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10220
10221                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10222                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10223                }
10224            }
10225        }
10226
10227        @Override
10228        void handleReturnCode() {
10229            if (mObserver != null) {
10230                try {
10231                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10232                } catch (RemoteException e) {
10233                    Slog.i(TAG, "Observer no longer exists.");
10234                }
10235            }
10236        }
10237
10238        @Override
10239        void handleServiceError() {
10240            Slog.e(TAG, "Could not measure application " + mStats.packageName
10241                            + " external storage");
10242        }
10243    }
10244
10245    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10246            throws RemoteException {
10247        long result = 0;
10248        for (File path : paths) {
10249            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10250        }
10251        return result;
10252    }
10253
10254    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10255        for (File path : paths) {
10256            try {
10257                mcs.clearDirectory(path.getAbsolutePath());
10258            } catch (RemoteException e) {
10259            }
10260        }
10261    }
10262
10263    static class OriginInfo {
10264        /**
10265         * Location where install is coming from, before it has been
10266         * copied/renamed into place. This could be a single monolithic APK
10267         * file, or a cluster directory. This location may be untrusted.
10268         */
10269        final File file;
10270        final String cid;
10271
10272        /**
10273         * Flag indicating that {@link #file} or {@link #cid} has already been
10274         * staged, meaning downstream users don't need to defensively copy the
10275         * contents.
10276         */
10277        final boolean staged;
10278
10279        /**
10280         * Flag indicating that {@link #file} or {@link #cid} is an already
10281         * installed app that is being moved.
10282         */
10283        final boolean existing;
10284
10285        final String resolvedPath;
10286        final File resolvedFile;
10287
10288        static OriginInfo fromNothing() {
10289            return new OriginInfo(null, null, false, false);
10290        }
10291
10292        static OriginInfo fromUntrustedFile(File file) {
10293            return new OriginInfo(file, null, false, false);
10294        }
10295
10296        static OriginInfo fromExistingFile(File file) {
10297            return new OriginInfo(file, null, false, true);
10298        }
10299
10300        static OriginInfo fromStagedFile(File file) {
10301            return new OriginInfo(file, null, true, false);
10302        }
10303
10304        static OriginInfo fromStagedContainer(String cid) {
10305            return new OriginInfo(null, cid, true, false);
10306        }
10307
10308        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10309            this.file = file;
10310            this.cid = cid;
10311            this.staged = staged;
10312            this.existing = existing;
10313
10314            if (cid != null) {
10315                resolvedPath = PackageHelper.getSdDir(cid);
10316                resolvedFile = new File(resolvedPath);
10317            } else if (file != null) {
10318                resolvedPath = file.getAbsolutePath();
10319                resolvedFile = file;
10320            } else {
10321                resolvedPath = null;
10322                resolvedFile = null;
10323            }
10324        }
10325    }
10326
10327    class MoveInfo {
10328        final int moveId;
10329        final String fromUuid;
10330        final String toUuid;
10331        final String packageName;
10332        final String dataAppName;
10333        final int appId;
10334        final String seinfo;
10335
10336        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10337                String dataAppName, int appId, String seinfo) {
10338            this.moveId = moveId;
10339            this.fromUuid = fromUuid;
10340            this.toUuid = toUuid;
10341            this.packageName = packageName;
10342            this.dataAppName = dataAppName;
10343            this.appId = appId;
10344            this.seinfo = seinfo;
10345        }
10346    }
10347
10348    class InstallParams extends HandlerParams {
10349        final OriginInfo origin;
10350        final MoveInfo move;
10351        final IPackageInstallObserver2 observer;
10352        int installFlags;
10353        final String installerPackageName;
10354        final String volumeUuid;
10355        final VerificationParams verificationParams;
10356        private InstallArgs mArgs;
10357        private int mRet;
10358        final String packageAbiOverride;
10359
10360        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10361                int installFlags, String installerPackageName, String volumeUuid,
10362                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10363            super(user);
10364            this.origin = origin;
10365            this.move = move;
10366            this.observer = observer;
10367            this.installFlags = installFlags;
10368            this.installerPackageName = installerPackageName;
10369            this.volumeUuid = volumeUuid;
10370            this.verificationParams = verificationParams;
10371            this.packageAbiOverride = packageAbiOverride;
10372        }
10373
10374        @Override
10375        public String toString() {
10376            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10377                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10378        }
10379
10380        public ManifestDigest getManifestDigest() {
10381            if (verificationParams == null) {
10382                return null;
10383            }
10384            return verificationParams.getManifestDigest();
10385        }
10386
10387        private int installLocationPolicy(PackageInfoLite pkgLite) {
10388            String packageName = pkgLite.packageName;
10389            int installLocation = pkgLite.installLocation;
10390            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10391            // reader
10392            synchronized (mPackages) {
10393                PackageParser.Package pkg = mPackages.get(packageName);
10394                if (pkg != null) {
10395                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10396                        // Check for downgrading.
10397                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10398                            try {
10399                                checkDowngrade(pkg, pkgLite);
10400                            } catch (PackageManagerException e) {
10401                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10402                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10403                            }
10404                        }
10405                        // Check for updated system application.
10406                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10407                            if (onSd) {
10408                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10409                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10410                            }
10411                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10412                        } else {
10413                            if (onSd) {
10414                                // Install flag overrides everything.
10415                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10416                            }
10417                            // If current upgrade specifies particular preference
10418                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10419                                // Application explicitly specified internal.
10420                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10421                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10422                                // App explictly prefers external. Let policy decide
10423                            } else {
10424                                // Prefer previous location
10425                                if (isExternal(pkg)) {
10426                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10427                                }
10428                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10429                            }
10430                        }
10431                    } else {
10432                        // Invalid install. Return error code
10433                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10434                    }
10435                }
10436            }
10437            // All the special cases have been taken care of.
10438            // Return result based on recommended install location.
10439            if (onSd) {
10440                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10441            }
10442            return pkgLite.recommendedInstallLocation;
10443        }
10444
10445        /*
10446         * Invoke remote method to get package information and install
10447         * location values. Override install location based on default
10448         * policy if needed and then create install arguments based
10449         * on the install location.
10450         */
10451        public void handleStartCopy() throws RemoteException {
10452            int ret = PackageManager.INSTALL_SUCCEEDED;
10453
10454            // If we're already staged, we've firmly committed to an install location
10455            if (origin.staged) {
10456                if (origin.file != null) {
10457                    installFlags |= PackageManager.INSTALL_INTERNAL;
10458                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10459                } else if (origin.cid != null) {
10460                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10461                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10462                } else {
10463                    throw new IllegalStateException("Invalid stage location");
10464                }
10465            }
10466
10467            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10468            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10469
10470            PackageInfoLite pkgLite = null;
10471
10472            if (onInt && onSd) {
10473                // Check if both bits are set.
10474                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10475                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10476            } else {
10477                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10478                        packageAbiOverride);
10479
10480                /*
10481                 * If we have too little free space, try to free cache
10482                 * before giving up.
10483                 */
10484                if (!origin.staged && pkgLite.recommendedInstallLocation
10485                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10486                    // TODO: focus freeing disk space on the target device
10487                    final StorageManager storage = StorageManager.from(mContext);
10488                    final long lowThreshold = storage.getStorageLowBytes(
10489                            Environment.getDataDirectory());
10490
10491                    final long sizeBytes = mContainerService.calculateInstalledSize(
10492                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10493
10494                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10495                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10496                                installFlags, packageAbiOverride);
10497                    }
10498
10499                    /*
10500                     * The cache free must have deleted the file we
10501                     * downloaded to install.
10502                     *
10503                     * TODO: fix the "freeCache" call to not delete
10504                     *       the file we care about.
10505                     */
10506                    if (pkgLite.recommendedInstallLocation
10507                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10508                        pkgLite.recommendedInstallLocation
10509                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10510                    }
10511                }
10512            }
10513
10514            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10515                int loc = pkgLite.recommendedInstallLocation;
10516                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10517                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10518                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10519                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10520                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10521                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10522                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10523                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10524                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10525                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10526                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10527                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10528                } else {
10529                    // Override with defaults if needed.
10530                    loc = installLocationPolicy(pkgLite);
10531                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10532                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10533                    } else if (!onSd && !onInt) {
10534                        // Override install location with flags
10535                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10536                            // Set the flag to install on external media.
10537                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10538                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10539                        } else {
10540                            // Make sure the flag for installing on external
10541                            // media is unset
10542                            installFlags |= PackageManager.INSTALL_INTERNAL;
10543                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10544                        }
10545                    }
10546                }
10547            }
10548
10549            final InstallArgs args = createInstallArgs(this);
10550            mArgs = args;
10551
10552            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10553                 /*
10554                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10555                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10556                 */
10557                int userIdentifier = getUser().getIdentifier();
10558                if (userIdentifier == UserHandle.USER_ALL
10559                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10560                    userIdentifier = UserHandle.USER_OWNER;
10561                }
10562
10563                /*
10564                 * Determine if we have any installed package verifiers. If we
10565                 * do, then we'll defer to them to verify the packages.
10566                 */
10567                final int requiredUid = mRequiredVerifierPackage == null ? -1
10568                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10569                if (!origin.existing && requiredUid != -1
10570                        && isVerificationEnabled(userIdentifier, installFlags)) {
10571                    final Intent verification = new Intent(
10572                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10573                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10574                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10575                            PACKAGE_MIME_TYPE);
10576                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10577
10578                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10579                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10580                            0 /* TODO: Which userId? */);
10581
10582                    if (DEBUG_VERIFY) {
10583                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10584                                + verification.toString() + " with " + pkgLite.verifiers.length
10585                                + " optional verifiers");
10586                    }
10587
10588                    final int verificationId = mPendingVerificationToken++;
10589
10590                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10591
10592                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10593                            installerPackageName);
10594
10595                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10596                            installFlags);
10597
10598                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10599                            pkgLite.packageName);
10600
10601                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10602                            pkgLite.versionCode);
10603
10604                    if (verificationParams != null) {
10605                        if (verificationParams.getVerificationURI() != null) {
10606                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10607                                 verificationParams.getVerificationURI());
10608                        }
10609                        if (verificationParams.getOriginatingURI() != null) {
10610                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10611                                  verificationParams.getOriginatingURI());
10612                        }
10613                        if (verificationParams.getReferrer() != null) {
10614                            verification.putExtra(Intent.EXTRA_REFERRER,
10615                                  verificationParams.getReferrer());
10616                        }
10617                        if (verificationParams.getOriginatingUid() >= 0) {
10618                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10619                                  verificationParams.getOriginatingUid());
10620                        }
10621                        if (verificationParams.getInstallerUid() >= 0) {
10622                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10623                                  verificationParams.getInstallerUid());
10624                        }
10625                    }
10626
10627                    final PackageVerificationState verificationState = new PackageVerificationState(
10628                            requiredUid, args);
10629
10630                    mPendingVerification.append(verificationId, verificationState);
10631
10632                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10633                            receivers, verificationState);
10634
10635                    /*
10636                     * If any sufficient verifiers were listed in the package
10637                     * manifest, attempt to ask them.
10638                     */
10639                    if (sufficientVerifiers != null) {
10640                        final int N = sufficientVerifiers.size();
10641                        if (N == 0) {
10642                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10643                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10644                        } else {
10645                            for (int i = 0; i < N; i++) {
10646                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10647
10648                                final Intent sufficientIntent = new Intent(verification);
10649                                sufficientIntent.setComponent(verifierComponent);
10650
10651                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10652                            }
10653                        }
10654                    }
10655
10656                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10657                            mRequiredVerifierPackage, receivers);
10658                    if (ret == PackageManager.INSTALL_SUCCEEDED
10659                            && mRequiredVerifierPackage != null) {
10660                        /*
10661                         * Send the intent to the required verification agent,
10662                         * but only start the verification timeout after the
10663                         * target BroadcastReceivers have run.
10664                         */
10665                        verification.setComponent(requiredVerifierComponent);
10666                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10667                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10668                                new BroadcastReceiver() {
10669                                    @Override
10670                                    public void onReceive(Context context, Intent intent) {
10671                                        final Message msg = mHandler
10672                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10673                                        msg.arg1 = verificationId;
10674                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10675                                    }
10676                                }, null, 0, null, null);
10677
10678                        /*
10679                         * We don't want the copy to proceed until verification
10680                         * succeeds, so null out this field.
10681                         */
10682                        mArgs = null;
10683                    }
10684                } else {
10685                    /*
10686                     * No package verification is enabled, so immediately start
10687                     * the remote call to initiate copy using temporary file.
10688                     */
10689                    ret = args.copyApk(mContainerService, true);
10690                }
10691            }
10692
10693            mRet = ret;
10694        }
10695
10696        @Override
10697        void handleReturnCode() {
10698            // If mArgs is null, then MCS couldn't be reached. When it
10699            // reconnects, it will try again to install. At that point, this
10700            // will succeed.
10701            if (mArgs != null) {
10702                processPendingInstall(mArgs, mRet);
10703            }
10704        }
10705
10706        @Override
10707        void handleServiceError() {
10708            mArgs = createInstallArgs(this);
10709            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10710        }
10711
10712        public boolean isForwardLocked() {
10713            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10714        }
10715    }
10716
10717    /**
10718     * Used during creation of InstallArgs
10719     *
10720     * @param installFlags package installation flags
10721     * @return true if should be installed on external storage
10722     */
10723    private static boolean installOnExternalAsec(int installFlags) {
10724        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10725            return false;
10726        }
10727        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10728            return true;
10729        }
10730        return false;
10731    }
10732
10733    /**
10734     * Used during creation of InstallArgs
10735     *
10736     * @param installFlags package installation flags
10737     * @return true if should be installed as forward locked
10738     */
10739    private static boolean installForwardLocked(int installFlags) {
10740        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10741    }
10742
10743    private InstallArgs createInstallArgs(InstallParams params) {
10744        if (params.move != null) {
10745            return new MoveInstallArgs(params);
10746        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10747            return new AsecInstallArgs(params);
10748        } else {
10749            return new FileInstallArgs(params);
10750        }
10751    }
10752
10753    /**
10754     * Create args that describe an existing installed package. Typically used
10755     * when cleaning up old installs, or used as a move source.
10756     */
10757    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10758            String resourcePath, String[] instructionSets) {
10759        final boolean isInAsec;
10760        if (installOnExternalAsec(installFlags)) {
10761            /* Apps on SD card are always in ASEC containers. */
10762            isInAsec = true;
10763        } else if (installForwardLocked(installFlags)
10764                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10765            /*
10766             * Forward-locked apps are only in ASEC containers if they're the
10767             * new style
10768             */
10769            isInAsec = true;
10770        } else {
10771            isInAsec = false;
10772        }
10773
10774        if (isInAsec) {
10775            return new AsecInstallArgs(codePath, instructionSets,
10776                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10777        } else {
10778            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10779        }
10780    }
10781
10782    static abstract class InstallArgs {
10783        /** @see InstallParams#origin */
10784        final OriginInfo origin;
10785        /** @see InstallParams#move */
10786        final MoveInfo move;
10787
10788        final IPackageInstallObserver2 observer;
10789        // Always refers to PackageManager flags only
10790        final int installFlags;
10791        final String installerPackageName;
10792        final String volumeUuid;
10793        final ManifestDigest manifestDigest;
10794        final UserHandle user;
10795        final String abiOverride;
10796
10797        // The list of instruction sets supported by this app. This is currently
10798        // only used during the rmdex() phase to clean up resources. We can get rid of this
10799        // if we move dex files under the common app path.
10800        /* nullable */ String[] instructionSets;
10801
10802        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10803                int installFlags, String installerPackageName, String volumeUuid,
10804                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10805                String abiOverride) {
10806            this.origin = origin;
10807            this.move = move;
10808            this.installFlags = installFlags;
10809            this.observer = observer;
10810            this.installerPackageName = installerPackageName;
10811            this.volumeUuid = volumeUuid;
10812            this.manifestDigest = manifestDigest;
10813            this.user = user;
10814            this.instructionSets = instructionSets;
10815            this.abiOverride = abiOverride;
10816        }
10817
10818        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10819        abstract int doPreInstall(int status);
10820
10821        /**
10822         * Rename package into final resting place. All paths on the given
10823         * scanned package should be updated to reflect the rename.
10824         */
10825        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10826        abstract int doPostInstall(int status, int uid);
10827
10828        /** @see PackageSettingBase#codePathString */
10829        abstract String getCodePath();
10830        /** @see PackageSettingBase#resourcePathString */
10831        abstract String getResourcePath();
10832
10833        // Need installer lock especially for dex file removal.
10834        abstract void cleanUpResourcesLI();
10835        abstract boolean doPostDeleteLI(boolean delete);
10836
10837        /**
10838         * Called before the source arguments are copied. This is used mostly
10839         * for MoveParams when it needs to read the source file to put it in the
10840         * destination.
10841         */
10842        int doPreCopy() {
10843            return PackageManager.INSTALL_SUCCEEDED;
10844        }
10845
10846        /**
10847         * Called after the source arguments are copied. This is used mostly for
10848         * MoveParams when it needs to read the source file to put it in the
10849         * destination.
10850         *
10851         * @return
10852         */
10853        int doPostCopy(int uid) {
10854            return PackageManager.INSTALL_SUCCEEDED;
10855        }
10856
10857        protected boolean isFwdLocked() {
10858            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10859        }
10860
10861        protected boolean isExternalAsec() {
10862            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10863        }
10864
10865        UserHandle getUser() {
10866            return user;
10867        }
10868    }
10869
10870    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10871        if (!allCodePaths.isEmpty()) {
10872            if (instructionSets == null) {
10873                throw new IllegalStateException("instructionSet == null");
10874            }
10875            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10876            for (String codePath : allCodePaths) {
10877                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10878                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10879                    if (retCode < 0) {
10880                        Slog.w(TAG, "Couldn't remove dex file for package: "
10881                                + " at location " + codePath + ", retcode=" + retCode);
10882                        // we don't consider this to be a failure of the core package deletion
10883                    }
10884                }
10885            }
10886        }
10887    }
10888
10889    /**
10890     * Logic to handle installation of non-ASEC applications, including copying
10891     * and renaming logic.
10892     */
10893    class FileInstallArgs extends InstallArgs {
10894        private File codeFile;
10895        private File resourceFile;
10896
10897        // Example topology:
10898        // /data/app/com.example/base.apk
10899        // /data/app/com.example/split_foo.apk
10900        // /data/app/com.example/lib/arm/libfoo.so
10901        // /data/app/com.example/lib/arm64/libfoo.so
10902        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10903
10904        /** New install */
10905        FileInstallArgs(InstallParams params) {
10906            super(params.origin, params.move, params.observer, params.installFlags,
10907                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10908                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10909            if (isFwdLocked()) {
10910                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10911            }
10912        }
10913
10914        /** Existing install */
10915        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10916            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10917                    null);
10918            this.codeFile = (codePath != null) ? new File(codePath) : null;
10919            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10920        }
10921
10922        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10923            if (origin.staged) {
10924                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10925                codeFile = origin.file;
10926                resourceFile = origin.file;
10927                return PackageManager.INSTALL_SUCCEEDED;
10928            }
10929
10930            try {
10931                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10932                codeFile = tempDir;
10933                resourceFile = tempDir;
10934            } catch (IOException e) {
10935                Slog.w(TAG, "Failed to create copy file: " + e);
10936                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10937            }
10938
10939            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10940                @Override
10941                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10942                    if (!FileUtils.isValidExtFilename(name)) {
10943                        throw new IllegalArgumentException("Invalid filename: " + name);
10944                    }
10945                    try {
10946                        final File file = new File(codeFile, name);
10947                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10948                                O_RDWR | O_CREAT, 0644);
10949                        Os.chmod(file.getAbsolutePath(), 0644);
10950                        return new ParcelFileDescriptor(fd);
10951                    } catch (ErrnoException e) {
10952                        throw new RemoteException("Failed to open: " + e.getMessage());
10953                    }
10954                }
10955            };
10956
10957            int ret = PackageManager.INSTALL_SUCCEEDED;
10958            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10959            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10960                Slog.e(TAG, "Failed to copy package");
10961                return ret;
10962            }
10963
10964            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10965            NativeLibraryHelper.Handle handle = null;
10966            try {
10967                handle = NativeLibraryHelper.Handle.create(codeFile);
10968                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10969                        abiOverride);
10970            } catch (IOException e) {
10971                Slog.e(TAG, "Copying native libraries failed", e);
10972                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10973            } finally {
10974                IoUtils.closeQuietly(handle);
10975            }
10976
10977            return ret;
10978        }
10979
10980        int doPreInstall(int status) {
10981            if (status != PackageManager.INSTALL_SUCCEEDED) {
10982                cleanUp();
10983            }
10984            return status;
10985        }
10986
10987        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10988            if (status != PackageManager.INSTALL_SUCCEEDED) {
10989                cleanUp();
10990                return false;
10991            }
10992
10993            final File targetDir = codeFile.getParentFile();
10994            final File beforeCodeFile = codeFile;
10995            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10996
10997            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10998            try {
10999                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11000            } catch (ErrnoException e) {
11001                Slog.w(TAG, "Failed to rename", e);
11002                return false;
11003            }
11004
11005            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11006                Slog.w(TAG, "Failed to restorecon");
11007                return false;
11008            }
11009
11010            // Reflect the rename internally
11011            codeFile = afterCodeFile;
11012            resourceFile = afterCodeFile;
11013
11014            // Reflect the rename in scanned details
11015            pkg.codePath = afterCodeFile.getAbsolutePath();
11016            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11017                    pkg.baseCodePath);
11018            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11019                    pkg.splitCodePaths);
11020
11021            // Reflect the rename in app info
11022            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11023            pkg.applicationInfo.setCodePath(pkg.codePath);
11024            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11025            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11026            pkg.applicationInfo.setResourcePath(pkg.codePath);
11027            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11028            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11029
11030            return true;
11031        }
11032
11033        int doPostInstall(int status, int uid) {
11034            if (status != PackageManager.INSTALL_SUCCEEDED) {
11035                cleanUp();
11036            }
11037            return status;
11038        }
11039
11040        @Override
11041        String getCodePath() {
11042            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11043        }
11044
11045        @Override
11046        String getResourcePath() {
11047            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11048        }
11049
11050        private boolean cleanUp() {
11051            if (codeFile == null || !codeFile.exists()) {
11052                return false;
11053            }
11054
11055            if (codeFile.isDirectory()) {
11056                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11057            } else {
11058                codeFile.delete();
11059            }
11060
11061            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11062                resourceFile.delete();
11063            }
11064
11065            return true;
11066        }
11067
11068        void cleanUpResourcesLI() {
11069            // Try enumerating all code paths before deleting
11070            List<String> allCodePaths = Collections.EMPTY_LIST;
11071            if (codeFile != null && codeFile.exists()) {
11072                try {
11073                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11074                    allCodePaths = pkg.getAllCodePaths();
11075                } catch (PackageParserException e) {
11076                    // Ignored; we tried our best
11077                }
11078            }
11079
11080            cleanUp();
11081            removeDexFiles(allCodePaths, instructionSets);
11082        }
11083
11084        boolean doPostDeleteLI(boolean delete) {
11085            // XXX err, shouldn't we respect the delete flag?
11086            cleanUpResourcesLI();
11087            return true;
11088        }
11089    }
11090
11091    private boolean isAsecExternal(String cid) {
11092        final String asecPath = PackageHelper.getSdFilesystem(cid);
11093        return !asecPath.startsWith(mAsecInternalPath);
11094    }
11095
11096    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11097            PackageManagerException {
11098        if (copyRet < 0) {
11099            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11100                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11101                throw new PackageManagerException(copyRet, message);
11102            }
11103        }
11104    }
11105
11106    /**
11107     * Extract the MountService "container ID" from the full code path of an
11108     * .apk.
11109     */
11110    static String cidFromCodePath(String fullCodePath) {
11111        int eidx = fullCodePath.lastIndexOf("/");
11112        String subStr1 = fullCodePath.substring(0, eidx);
11113        int sidx = subStr1.lastIndexOf("/");
11114        return subStr1.substring(sidx+1, eidx);
11115    }
11116
11117    /**
11118     * Logic to handle installation of ASEC applications, including copying and
11119     * renaming logic.
11120     */
11121    class AsecInstallArgs extends InstallArgs {
11122        static final String RES_FILE_NAME = "pkg.apk";
11123        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11124
11125        String cid;
11126        String packagePath;
11127        String resourcePath;
11128
11129        /** New install */
11130        AsecInstallArgs(InstallParams params) {
11131            super(params.origin, params.move, params.observer, params.installFlags,
11132                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11133                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11134        }
11135
11136        /** Existing install */
11137        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11138                        boolean isExternal, boolean isForwardLocked) {
11139            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11140                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11141                    instructionSets, null);
11142            // Hackily pretend we're still looking at a full code path
11143            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11144                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11145            }
11146
11147            // Extract cid from fullCodePath
11148            int eidx = fullCodePath.lastIndexOf("/");
11149            String subStr1 = fullCodePath.substring(0, eidx);
11150            int sidx = subStr1.lastIndexOf("/");
11151            cid = subStr1.substring(sidx+1, eidx);
11152            setMountPath(subStr1);
11153        }
11154
11155        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11156            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11157                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11158                    instructionSets, null);
11159            this.cid = cid;
11160            setMountPath(PackageHelper.getSdDir(cid));
11161        }
11162
11163        void createCopyFile() {
11164            cid = mInstallerService.allocateExternalStageCidLegacy();
11165        }
11166
11167        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11168            if (origin.staged) {
11169                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11170                cid = origin.cid;
11171                setMountPath(PackageHelper.getSdDir(cid));
11172                return PackageManager.INSTALL_SUCCEEDED;
11173            }
11174
11175            if (temp) {
11176                createCopyFile();
11177            } else {
11178                /*
11179                 * Pre-emptively destroy the container since it's destroyed if
11180                 * copying fails due to it existing anyway.
11181                 */
11182                PackageHelper.destroySdDir(cid);
11183            }
11184
11185            final String newMountPath = imcs.copyPackageToContainer(
11186                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11187                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11188
11189            if (newMountPath != null) {
11190                setMountPath(newMountPath);
11191                return PackageManager.INSTALL_SUCCEEDED;
11192            } else {
11193                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11194            }
11195        }
11196
11197        @Override
11198        String getCodePath() {
11199            return packagePath;
11200        }
11201
11202        @Override
11203        String getResourcePath() {
11204            return resourcePath;
11205        }
11206
11207        int doPreInstall(int status) {
11208            if (status != PackageManager.INSTALL_SUCCEEDED) {
11209                // Destroy container
11210                PackageHelper.destroySdDir(cid);
11211            } else {
11212                boolean mounted = PackageHelper.isContainerMounted(cid);
11213                if (!mounted) {
11214                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11215                            Process.SYSTEM_UID);
11216                    if (newMountPath != null) {
11217                        setMountPath(newMountPath);
11218                    } else {
11219                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11220                    }
11221                }
11222            }
11223            return status;
11224        }
11225
11226        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11227            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11228            String newMountPath = null;
11229            if (PackageHelper.isContainerMounted(cid)) {
11230                // Unmount the container
11231                if (!PackageHelper.unMountSdDir(cid)) {
11232                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11233                    return false;
11234                }
11235            }
11236            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11237                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11238                        " which might be stale. Will try to clean up.");
11239                // Clean up the stale container and proceed to recreate.
11240                if (!PackageHelper.destroySdDir(newCacheId)) {
11241                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11242                    return false;
11243                }
11244                // Successfully cleaned up stale container. Try to rename again.
11245                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11246                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11247                            + " inspite of cleaning it up.");
11248                    return false;
11249                }
11250            }
11251            if (!PackageHelper.isContainerMounted(newCacheId)) {
11252                Slog.w(TAG, "Mounting container " + newCacheId);
11253                newMountPath = PackageHelper.mountSdDir(newCacheId,
11254                        getEncryptKey(), Process.SYSTEM_UID);
11255            } else {
11256                newMountPath = PackageHelper.getSdDir(newCacheId);
11257            }
11258            if (newMountPath == null) {
11259                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11260                return false;
11261            }
11262            Log.i(TAG, "Succesfully renamed " + cid +
11263                    " to " + newCacheId +
11264                    " at new path: " + newMountPath);
11265            cid = newCacheId;
11266
11267            final File beforeCodeFile = new File(packagePath);
11268            setMountPath(newMountPath);
11269            final File afterCodeFile = new File(packagePath);
11270
11271            // Reflect the rename in scanned details
11272            pkg.codePath = afterCodeFile.getAbsolutePath();
11273            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11274                    pkg.baseCodePath);
11275            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11276                    pkg.splitCodePaths);
11277
11278            // Reflect the rename in app info
11279            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11280            pkg.applicationInfo.setCodePath(pkg.codePath);
11281            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11282            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11283            pkg.applicationInfo.setResourcePath(pkg.codePath);
11284            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11285            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11286
11287            return true;
11288        }
11289
11290        private void setMountPath(String mountPath) {
11291            final File mountFile = new File(mountPath);
11292
11293            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11294            if (monolithicFile.exists()) {
11295                packagePath = monolithicFile.getAbsolutePath();
11296                if (isFwdLocked()) {
11297                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11298                } else {
11299                    resourcePath = packagePath;
11300                }
11301            } else {
11302                packagePath = mountFile.getAbsolutePath();
11303                resourcePath = packagePath;
11304            }
11305        }
11306
11307        int doPostInstall(int status, int uid) {
11308            if (status != PackageManager.INSTALL_SUCCEEDED) {
11309                cleanUp();
11310            } else {
11311                final int groupOwner;
11312                final String protectedFile;
11313                if (isFwdLocked()) {
11314                    groupOwner = UserHandle.getSharedAppGid(uid);
11315                    protectedFile = RES_FILE_NAME;
11316                } else {
11317                    groupOwner = -1;
11318                    protectedFile = null;
11319                }
11320
11321                if (uid < Process.FIRST_APPLICATION_UID
11322                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11323                    Slog.e(TAG, "Failed to finalize " + cid);
11324                    PackageHelper.destroySdDir(cid);
11325                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11326                }
11327
11328                boolean mounted = PackageHelper.isContainerMounted(cid);
11329                if (!mounted) {
11330                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11331                }
11332            }
11333            return status;
11334        }
11335
11336        private void cleanUp() {
11337            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11338
11339            // Destroy secure container
11340            PackageHelper.destroySdDir(cid);
11341        }
11342
11343        private List<String> getAllCodePaths() {
11344            final File codeFile = new File(getCodePath());
11345            if (codeFile != null && codeFile.exists()) {
11346                try {
11347                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11348                    return pkg.getAllCodePaths();
11349                } catch (PackageParserException e) {
11350                    // Ignored; we tried our best
11351                }
11352            }
11353            return Collections.EMPTY_LIST;
11354        }
11355
11356        void cleanUpResourcesLI() {
11357            // Enumerate all code paths before deleting
11358            cleanUpResourcesLI(getAllCodePaths());
11359        }
11360
11361        private void cleanUpResourcesLI(List<String> allCodePaths) {
11362            cleanUp();
11363            removeDexFiles(allCodePaths, instructionSets);
11364        }
11365
11366        String getPackageName() {
11367            return getAsecPackageName(cid);
11368        }
11369
11370        boolean doPostDeleteLI(boolean delete) {
11371            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11372            final List<String> allCodePaths = getAllCodePaths();
11373            boolean mounted = PackageHelper.isContainerMounted(cid);
11374            if (mounted) {
11375                // Unmount first
11376                if (PackageHelper.unMountSdDir(cid)) {
11377                    mounted = false;
11378                }
11379            }
11380            if (!mounted && delete) {
11381                cleanUpResourcesLI(allCodePaths);
11382            }
11383            return !mounted;
11384        }
11385
11386        @Override
11387        int doPreCopy() {
11388            if (isFwdLocked()) {
11389                if (!PackageHelper.fixSdPermissions(cid,
11390                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11391                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11392                }
11393            }
11394
11395            return PackageManager.INSTALL_SUCCEEDED;
11396        }
11397
11398        @Override
11399        int doPostCopy(int uid) {
11400            if (isFwdLocked()) {
11401                if (uid < Process.FIRST_APPLICATION_UID
11402                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11403                                RES_FILE_NAME)) {
11404                    Slog.e(TAG, "Failed to finalize " + cid);
11405                    PackageHelper.destroySdDir(cid);
11406                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11407                }
11408            }
11409
11410            return PackageManager.INSTALL_SUCCEEDED;
11411        }
11412    }
11413
11414    /**
11415     * Logic to handle movement of existing installed applications.
11416     */
11417    class MoveInstallArgs extends InstallArgs {
11418        private File codeFile;
11419        private File resourceFile;
11420
11421        /** New install */
11422        MoveInstallArgs(InstallParams params) {
11423            super(params.origin, params.move, params.observer, params.installFlags,
11424                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11425                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11426        }
11427
11428        int copyApk(IMediaContainerService imcs, boolean temp) {
11429            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11430                    + move.fromUuid + " to " + move.toUuid);
11431            synchronized (mInstaller) {
11432                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11433                        move.dataAppName, move.appId, move.seinfo) != 0) {
11434                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11435                }
11436            }
11437
11438            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11439            resourceFile = codeFile;
11440            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11441
11442            return PackageManager.INSTALL_SUCCEEDED;
11443        }
11444
11445        int doPreInstall(int status) {
11446            if (status != PackageManager.INSTALL_SUCCEEDED) {
11447                cleanUp(move.toUuid);
11448            }
11449            return status;
11450        }
11451
11452        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11453            if (status != PackageManager.INSTALL_SUCCEEDED) {
11454                cleanUp(move.toUuid);
11455                return false;
11456            }
11457
11458            // Reflect the move in app info
11459            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11460            pkg.applicationInfo.setCodePath(pkg.codePath);
11461            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11462            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11463            pkg.applicationInfo.setResourcePath(pkg.codePath);
11464            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11465            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11466
11467            return true;
11468        }
11469
11470        int doPostInstall(int status, int uid) {
11471            if (status == PackageManager.INSTALL_SUCCEEDED) {
11472                cleanUp(move.fromUuid);
11473            } else {
11474                cleanUp(move.toUuid);
11475            }
11476            return status;
11477        }
11478
11479        @Override
11480        String getCodePath() {
11481            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11482        }
11483
11484        @Override
11485        String getResourcePath() {
11486            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11487        }
11488
11489        private boolean cleanUp(String volumeUuid) {
11490            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11491                    move.dataAppName);
11492            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11493            synchronized (mInstallLock) {
11494                // Clean up both app data and code
11495                removeDataDirsLI(volumeUuid, move.packageName);
11496                if (codeFile.isDirectory()) {
11497                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11498                } else {
11499                    codeFile.delete();
11500                }
11501            }
11502            return true;
11503        }
11504
11505        void cleanUpResourcesLI() {
11506            throw new UnsupportedOperationException();
11507        }
11508
11509        boolean doPostDeleteLI(boolean delete) {
11510            throw new UnsupportedOperationException();
11511        }
11512    }
11513
11514    static String getAsecPackageName(String packageCid) {
11515        int idx = packageCid.lastIndexOf("-");
11516        if (idx == -1) {
11517            return packageCid;
11518        }
11519        return packageCid.substring(0, idx);
11520    }
11521
11522    // Utility method used to create code paths based on package name and available index.
11523    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11524        String idxStr = "";
11525        int idx = 1;
11526        // Fall back to default value of idx=1 if prefix is not
11527        // part of oldCodePath
11528        if (oldCodePath != null) {
11529            String subStr = oldCodePath;
11530            // Drop the suffix right away
11531            if (suffix != null && subStr.endsWith(suffix)) {
11532                subStr = subStr.substring(0, subStr.length() - suffix.length());
11533            }
11534            // If oldCodePath already contains prefix find out the
11535            // ending index to either increment or decrement.
11536            int sidx = subStr.lastIndexOf(prefix);
11537            if (sidx != -1) {
11538                subStr = subStr.substring(sidx + prefix.length());
11539                if (subStr != null) {
11540                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11541                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11542                    }
11543                    try {
11544                        idx = Integer.parseInt(subStr);
11545                        if (idx <= 1) {
11546                            idx++;
11547                        } else {
11548                            idx--;
11549                        }
11550                    } catch(NumberFormatException e) {
11551                    }
11552                }
11553            }
11554        }
11555        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11556        return prefix + idxStr;
11557    }
11558
11559    private File getNextCodePath(File targetDir, String packageName) {
11560        int suffix = 1;
11561        File result;
11562        do {
11563            result = new File(targetDir, packageName + "-" + suffix);
11564            suffix++;
11565        } while (result.exists());
11566        return result;
11567    }
11568
11569    // Utility method that returns the relative package path with respect
11570    // to the installation directory. Like say for /data/data/com.test-1.apk
11571    // string com.test-1 is returned.
11572    static String deriveCodePathName(String codePath) {
11573        if (codePath == null) {
11574            return null;
11575        }
11576        final File codeFile = new File(codePath);
11577        final String name = codeFile.getName();
11578        if (codeFile.isDirectory()) {
11579            return name;
11580        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11581            final int lastDot = name.lastIndexOf('.');
11582            return name.substring(0, lastDot);
11583        } else {
11584            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11585            return null;
11586        }
11587    }
11588
11589    class PackageInstalledInfo {
11590        String name;
11591        int uid;
11592        // The set of users that originally had this package installed.
11593        int[] origUsers;
11594        // The set of users that now have this package installed.
11595        int[] newUsers;
11596        PackageParser.Package pkg;
11597        int returnCode;
11598        String returnMsg;
11599        PackageRemovedInfo removedInfo;
11600
11601        public void setError(int code, String msg) {
11602            returnCode = code;
11603            returnMsg = msg;
11604            Slog.w(TAG, msg);
11605        }
11606
11607        public void setError(String msg, PackageParserException e) {
11608            returnCode = e.error;
11609            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11610            Slog.w(TAG, msg, e);
11611        }
11612
11613        public void setError(String msg, PackageManagerException e) {
11614            returnCode = e.error;
11615            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11616            Slog.w(TAG, msg, e);
11617        }
11618
11619        // In some error cases we want to convey more info back to the observer
11620        String origPackage;
11621        String origPermission;
11622    }
11623
11624    /*
11625     * Install a non-existing package.
11626     */
11627    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11628            UserHandle user, String installerPackageName, String volumeUuid,
11629            PackageInstalledInfo res) {
11630        // Remember this for later, in case we need to rollback this install
11631        String pkgName = pkg.packageName;
11632
11633        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11634        final boolean dataDirExists = Environment
11635                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11636        synchronized(mPackages) {
11637            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11638                // A package with the same name is already installed, though
11639                // it has been renamed to an older name.  The package we
11640                // are trying to install should be installed as an update to
11641                // the existing one, but that has not been requested, so bail.
11642                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11643                        + " without first uninstalling package running as "
11644                        + mSettings.mRenamedPackages.get(pkgName));
11645                return;
11646            }
11647            if (mPackages.containsKey(pkgName)) {
11648                // Don't allow installation over an existing package with the same name.
11649                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11650                        + " without first uninstalling.");
11651                return;
11652            }
11653        }
11654
11655        try {
11656            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11657                    System.currentTimeMillis(), user);
11658
11659            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11660            // delete the partially installed application. the data directory will have to be
11661            // restored if it was already existing
11662            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11663                // remove package from internal structures.  Note that we want deletePackageX to
11664                // delete the package data and cache directories that it created in
11665                // scanPackageLocked, unless those directories existed before we even tried to
11666                // install.
11667                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11668                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11669                                res.removedInfo, true);
11670            }
11671
11672        } catch (PackageManagerException e) {
11673            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11674        }
11675    }
11676
11677    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11678        // Can't rotate keys during boot or if sharedUser.
11679        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11680                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11681            return false;
11682        }
11683        // app is using upgradeKeySets; make sure all are valid
11684        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11685        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11686        for (int i = 0; i < upgradeKeySets.length; i++) {
11687            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11688                Slog.wtf(TAG, "Package "
11689                         + (oldPs.name != null ? oldPs.name : "<null>")
11690                         + " contains upgrade-key-set reference to unknown key-set: "
11691                         + upgradeKeySets[i]
11692                         + " reverting to signatures check.");
11693                return false;
11694            }
11695        }
11696        return true;
11697    }
11698
11699    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11700        // Upgrade keysets are being used.  Determine if new package has a superset of the
11701        // required keys.
11702        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11703        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11704        for (int i = 0; i < upgradeKeySets.length; i++) {
11705            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11706            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11707                return true;
11708            }
11709        }
11710        return false;
11711    }
11712
11713    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11714            UserHandle user, String installerPackageName, String volumeUuid,
11715            PackageInstalledInfo res) {
11716        final PackageParser.Package oldPackage;
11717        final String pkgName = pkg.packageName;
11718        final int[] allUsers;
11719        final boolean[] perUserInstalled;
11720        final boolean weFroze;
11721
11722        // First find the old package info and check signatures
11723        synchronized(mPackages) {
11724            oldPackage = mPackages.get(pkgName);
11725            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11726            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11727            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11728                if(!checkUpgradeKeySetLP(ps, pkg)) {
11729                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11730                            "New package not signed by keys specified by upgrade-keysets: "
11731                            + pkgName);
11732                    return;
11733                }
11734            } else {
11735                // default to original signature matching
11736                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11737                    != PackageManager.SIGNATURE_MATCH) {
11738                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11739                            "New package has a different signature: " + pkgName);
11740                    return;
11741                }
11742            }
11743
11744            // In case of rollback, remember per-user/profile install state
11745            allUsers = sUserManager.getUserIds();
11746            perUserInstalled = new boolean[allUsers.length];
11747            for (int i = 0; i < allUsers.length; i++) {
11748                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11749            }
11750
11751            // Mark the app as frozen to prevent launching during the upgrade
11752            // process, and then kill all running instances
11753            if (!ps.frozen) {
11754                ps.frozen = true;
11755                weFroze = true;
11756            } else {
11757                weFroze = false;
11758            }
11759        }
11760
11761        // Now that we're guarded by frozen state, kill app during upgrade
11762        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11763
11764        try {
11765            boolean sysPkg = (isSystemApp(oldPackage));
11766            if (sysPkg) {
11767                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11768                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11769            } else {
11770                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11771                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11772            }
11773        } finally {
11774            // Regardless of success or failure of upgrade steps above, always
11775            // unfreeze the package if we froze it
11776            if (weFroze) {
11777                unfreezePackage(pkgName);
11778            }
11779        }
11780    }
11781
11782    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11783            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11784            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11785            String volumeUuid, PackageInstalledInfo res) {
11786        String pkgName = deletedPackage.packageName;
11787        boolean deletedPkg = true;
11788        boolean updatedSettings = false;
11789
11790        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11791                + deletedPackage);
11792        long origUpdateTime;
11793        if (pkg.mExtras != null) {
11794            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11795        } else {
11796            origUpdateTime = 0;
11797        }
11798
11799        // First delete the existing package while retaining the data directory
11800        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11801                res.removedInfo, true)) {
11802            // If the existing package wasn't successfully deleted
11803            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11804            deletedPkg = false;
11805        } else {
11806            // Successfully deleted the old package; proceed with replace.
11807
11808            // If deleted package lived in a container, give users a chance to
11809            // relinquish resources before killing.
11810            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11811                if (DEBUG_INSTALL) {
11812                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11813                }
11814                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11815                final ArrayList<String> pkgList = new ArrayList<String>(1);
11816                pkgList.add(deletedPackage.applicationInfo.packageName);
11817                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11818            }
11819
11820            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11821            try {
11822                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11823                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11824                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11825                        perUserInstalled, res, user);
11826                updatedSettings = true;
11827            } catch (PackageManagerException e) {
11828                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11829            }
11830        }
11831
11832        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11833            // remove package from internal structures.  Note that we want deletePackageX to
11834            // delete the package data and cache directories that it created in
11835            // scanPackageLocked, unless those directories existed before we even tried to
11836            // install.
11837            if(updatedSettings) {
11838                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11839                deletePackageLI(
11840                        pkgName, null, true, allUsers, perUserInstalled,
11841                        PackageManager.DELETE_KEEP_DATA,
11842                                res.removedInfo, true);
11843            }
11844            // Since we failed to install the new package we need to restore the old
11845            // package that we deleted.
11846            if (deletedPkg) {
11847                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11848                File restoreFile = new File(deletedPackage.codePath);
11849                // Parse old package
11850                boolean oldExternal = isExternal(deletedPackage);
11851                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11852                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11853                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11854                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11855                try {
11856                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11857                } catch (PackageManagerException e) {
11858                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11859                            + e.getMessage());
11860                    return;
11861                }
11862                // Restore of old package succeeded. Update permissions.
11863                // writer
11864                synchronized (mPackages) {
11865                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11866                            UPDATE_PERMISSIONS_ALL);
11867                    // can downgrade to reader
11868                    mSettings.writeLPr();
11869                }
11870                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11871            }
11872        }
11873    }
11874
11875    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11876            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11877            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11878            String volumeUuid, PackageInstalledInfo res) {
11879        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11880                + ", old=" + deletedPackage);
11881        boolean disabledSystem = false;
11882        boolean updatedSettings = false;
11883        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11884        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11885                != 0) {
11886            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11887        }
11888        String packageName = deletedPackage.packageName;
11889        if (packageName == null) {
11890            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11891                    "Attempt to delete null packageName.");
11892            return;
11893        }
11894        PackageParser.Package oldPkg;
11895        PackageSetting oldPkgSetting;
11896        // reader
11897        synchronized (mPackages) {
11898            oldPkg = mPackages.get(packageName);
11899            oldPkgSetting = mSettings.mPackages.get(packageName);
11900            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11901                    (oldPkgSetting == null)) {
11902                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11903                        "Couldn't find package:" + packageName + " information");
11904                return;
11905            }
11906        }
11907
11908        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11909        res.removedInfo.removedPackage = packageName;
11910        // Remove existing system package
11911        removePackageLI(oldPkgSetting, true);
11912        // writer
11913        synchronized (mPackages) {
11914            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11915            if (!disabledSystem && deletedPackage != null) {
11916                // We didn't need to disable the .apk as a current system package,
11917                // which means we are replacing another update that is already
11918                // installed.  We need to make sure to delete the older one's .apk.
11919                res.removedInfo.args = createInstallArgsForExisting(0,
11920                        deletedPackage.applicationInfo.getCodePath(),
11921                        deletedPackage.applicationInfo.getResourcePath(),
11922                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11923            } else {
11924                res.removedInfo.args = null;
11925            }
11926        }
11927
11928        // Successfully disabled the old package. Now proceed with re-installation
11929        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11930
11931        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11932        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11933
11934        PackageParser.Package newPackage = null;
11935        try {
11936            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11937            if (newPackage.mExtras != null) {
11938                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11939                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11940                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11941
11942                // is the update attempting to change shared user? that isn't going to work...
11943                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11944                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11945                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11946                            + " to " + newPkgSetting.sharedUser);
11947                    updatedSettings = true;
11948                }
11949            }
11950
11951            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11952                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11953                        perUserInstalled, res, user);
11954                updatedSettings = true;
11955            }
11956
11957        } catch (PackageManagerException e) {
11958            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11959        }
11960
11961        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11962            // Re installation failed. Restore old information
11963            // Remove new pkg information
11964            if (newPackage != null) {
11965                removeInstalledPackageLI(newPackage, true);
11966            }
11967            // Add back the old system package
11968            try {
11969                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11970            } catch (PackageManagerException e) {
11971                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11972            }
11973            // Restore the old system information in Settings
11974            synchronized (mPackages) {
11975                if (disabledSystem) {
11976                    mSettings.enableSystemPackageLPw(packageName);
11977                }
11978                if (updatedSettings) {
11979                    mSettings.setInstallerPackageName(packageName,
11980                            oldPkgSetting.installerPackageName);
11981                }
11982                mSettings.writeLPr();
11983            }
11984        }
11985    }
11986
11987    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11988            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11989            UserHandle user) {
11990        String pkgName = newPackage.packageName;
11991        synchronized (mPackages) {
11992            //write settings. the installStatus will be incomplete at this stage.
11993            //note that the new package setting would have already been
11994            //added to mPackages. It hasn't been persisted yet.
11995            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11996            mSettings.writeLPr();
11997        }
11998
11999        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12000
12001        synchronized (mPackages) {
12002            updatePermissionsLPw(newPackage.packageName, newPackage,
12003                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12004                            ? UPDATE_PERMISSIONS_ALL : 0));
12005            // For system-bundled packages, we assume that installing an upgraded version
12006            // of the package implies that the user actually wants to run that new code,
12007            // so we enable the package.
12008            PackageSetting ps = mSettings.mPackages.get(pkgName);
12009            if (ps != null) {
12010                if (isSystemApp(newPackage)) {
12011                    // NB: implicit assumption that system package upgrades apply to all users
12012                    if (DEBUG_INSTALL) {
12013                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12014                    }
12015                    if (res.origUsers != null) {
12016                        for (int userHandle : res.origUsers) {
12017                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12018                                    userHandle, installerPackageName);
12019                        }
12020                    }
12021                    // Also convey the prior install/uninstall state
12022                    if (allUsers != null && perUserInstalled != null) {
12023                        for (int i = 0; i < allUsers.length; i++) {
12024                            if (DEBUG_INSTALL) {
12025                                Slog.d(TAG, "    user " + allUsers[i]
12026                                        + " => " + perUserInstalled[i]);
12027                            }
12028                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12029                        }
12030                        // these install state changes will be persisted in the
12031                        // upcoming call to mSettings.writeLPr().
12032                    }
12033                }
12034                // It's implied that when a user requests installation, they want the app to be
12035                // installed and enabled.
12036                int userId = user.getIdentifier();
12037                if (userId != UserHandle.USER_ALL) {
12038                    ps.setInstalled(true, userId);
12039                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12040                }
12041            }
12042            res.name = pkgName;
12043            res.uid = newPackage.applicationInfo.uid;
12044            res.pkg = newPackage;
12045            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12046            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12047            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12048            //to update install status
12049            mSettings.writeLPr();
12050        }
12051    }
12052
12053    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12054        final int installFlags = args.installFlags;
12055        final String installerPackageName = args.installerPackageName;
12056        final String volumeUuid = args.volumeUuid;
12057        final File tmpPackageFile = new File(args.getCodePath());
12058        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12059        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12060                || (args.volumeUuid != null));
12061        boolean replace = false;
12062        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12063        if (args.move != null) {
12064            // moving a complete application; perfom an initial scan on the new install location
12065            scanFlags |= SCAN_INITIAL;
12066        }
12067        // Result object to be returned
12068        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12069
12070        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12071        // Retrieve PackageSettings and parse package
12072        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12073                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12074                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12075        PackageParser pp = new PackageParser();
12076        pp.setSeparateProcesses(mSeparateProcesses);
12077        pp.setDisplayMetrics(mMetrics);
12078
12079        final PackageParser.Package pkg;
12080        try {
12081            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12082        } catch (PackageParserException e) {
12083            res.setError("Failed parse during installPackageLI", e);
12084            return;
12085        }
12086
12087        // Mark that we have an install time CPU ABI override.
12088        pkg.cpuAbiOverride = args.abiOverride;
12089
12090        String pkgName = res.name = pkg.packageName;
12091        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12092            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12093                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12094                return;
12095            }
12096        }
12097
12098        try {
12099            pp.collectCertificates(pkg, parseFlags);
12100            pp.collectManifestDigest(pkg);
12101        } catch (PackageParserException e) {
12102            res.setError("Failed collect during installPackageLI", e);
12103            return;
12104        }
12105
12106        /* If the installer passed in a manifest digest, compare it now. */
12107        if (args.manifestDigest != null) {
12108            if (DEBUG_INSTALL) {
12109                final String parsedManifest = pkg.manifestDigest == null ? "null"
12110                        : pkg.manifestDigest.toString();
12111                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12112                        + parsedManifest);
12113            }
12114
12115            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12116                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12117                return;
12118            }
12119        } else if (DEBUG_INSTALL) {
12120            final String parsedManifest = pkg.manifestDigest == null
12121                    ? "null" : pkg.manifestDigest.toString();
12122            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12123        }
12124
12125        // Get rid of all references to package scan path via parser.
12126        pp = null;
12127        String oldCodePath = null;
12128        boolean systemApp = false;
12129        synchronized (mPackages) {
12130            // Check if installing already existing package
12131            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12132                String oldName = mSettings.mRenamedPackages.get(pkgName);
12133                if (pkg.mOriginalPackages != null
12134                        && pkg.mOriginalPackages.contains(oldName)
12135                        && mPackages.containsKey(oldName)) {
12136                    // This package is derived from an original package,
12137                    // and this device has been updating from that original
12138                    // name.  We must continue using the original name, so
12139                    // rename the new package here.
12140                    pkg.setPackageName(oldName);
12141                    pkgName = pkg.packageName;
12142                    replace = true;
12143                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12144                            + oldName + " pkgName=" + pkgName);
12145                } else if (mPackages.containsKey(pkgName)) {
12146                    // This package, under its official name, already exists
12147                    // on the device; we should replace it.
12148                    replace = true;
12149                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12150                }
12151
12152                // Prevent apps opting out from runtime permissions
12153                if (replace) {
12154                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12155                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12156                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12157                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12158                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12159                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12160                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12161                                        + " doesn't support runtime permissions but the old"
12162                                        + " target SDK " + oldTargetSdk + " does.");
12163                        return;
12164                    }
12165                }
12166            }
12167
12168            PackageSetting ps = mSettings.mPackages.get(pkgName);
12169            if (ps != null) {
12170                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12171
12172                // Quick sanity check that we're signed correctly if updating;
12173                // we'll check this again later when scanning, but we want to
12174                // bail early here before tripping over redefined permissions.
12175                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12176                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12177                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12178                                + pkg.packageName + " upgrade keys do not match the "
12179                                + "previously installed version");
12180                        return;
12181                    }
12182                } else {
12183                    try {
12184                        verifySignaturesLP(ps, pkg);
12185                    } catch (PackageManagerException e) {
12186                        res.setError(e.error, e.getMessage());
12187                        return;
12188                    }
12189                }
12190
12191                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12192                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12193                    systemApp = (ps.pkg.applicationInfo.flags &
12194                            ApplicationInfo.FLAG_SYSTEM) != 0;
12195                }
12196                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12197            }
12198
12199            // Check whether the newly-scanned package wants to define an already-defined perm
12200            int N = pkg.permissions.size();
12201            for (int i = N-1; i >= 0; i--) {
12202                PackageParser.Permission perm = pkg.permissions.get(i);
12203                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12204                if (bp != null) {
12205                    // If the defining package is signed with our cert, it's okay.  This
12206                    // also includes the "updating the same package" case, of course.
12207                    // "updating same package" could also involve key-rotation.
12208                    final boolean sigsOk;
12209                    if (bp.sourcePackage.equals(pkg.packageName)
12210                            && (bp.packageSetting instanceof PackageSetting)
12211                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12212                                    scanFlags))) {
12213                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12214                    } else {
12215                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12216                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12217                    }
12218                    if (!sigsOk) {
12219                        // If the owning package is the system itself, we log but allow
12220                        // install to proceed; we fail the install on all other permission
12221                        // redefinitions.
12222                        if (!bp.sourcePackage.equals("android")) {
12223                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12224                                    + pkg.packageName + " attempting to redeclare permission "
12225                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12226                            res.origPermission = perm.info.name;
12227                            res.origPackage = bp.sourcePackage;
12228                            return;
12229                        } else {
12230                            Slog.w(TAG, "Package " + pkg.packageName
12231                                    + " attempting to redeclare system permission "
12232                                    + perm.info.name + "; ignoring new declaration");
12233                            pkg.permissions.remove(i);
12234                        }
12235                    }
12236                }
12237            }
12238
12239        }
12240
12241        if (systemApp && onExternal) {
12242            // Disable updates to system apps on sdcard
12243            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12244                    "Cannot install updates to system apps on sdcard");
12245            return;
12246        }
12247
12248        if (args.move != null) {
12249            // We did an in-place move, so dex is ready to roll
12250            scanFlags |= SCAN_NO_DEX;
12251            scanFlags |= SCAN_MOVE;
12252        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12253            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12254            scanFlags |= SCAN_NO_DEX;
12255
12256            try {
12257                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12258                        true /* extract libs */);
12259            } catch (PackageManagerException pme) {
12260                Slog.e(TAG, "Error deriving application ABI", pme);
12261                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12262                return;
12263            }
12264
12265            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12266            int result = mPackageDexOptimizer
12267                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12268                            false /* defer */, false /* inclDependencies */);
12269            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12270                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12271                return;
12272            }
12273        }
12274
12275        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12276            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12277            return;
12278        }
12279
12280        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12281
12282        if (replace) {
12283            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12284                    installerPackageName, volumeUuid, res);
12285        } else {
12286            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12287                    args.user, installerPackageName, volumeUuid, res);
12288        }
12289        synchronized (mPackages) {
12290            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12291            if (ps != null) {
12292                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12293            }
12294        }
12295    }
12296
12297    private void startIntentFilterVerifications(int userId, boolean replacing,
12298            PackageParser.Package pkg) {
12299        if (mIntentFilterVerifierComponent == null) {
12300            Slog.w(TAG, "No IntentFilter verification will not be done as "
12301                    + "there is no IntentFilterVerifier available!");
12302            return;
12303        }
12304
12305        final int verifierUid = getPackageUid(
12306                mIntentFilterVerifierComponent.getPackageName(),
12307                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12308
12309        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12310        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12311        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12312        mHandler.sendMessage(msg);
12313    }
12314
12315    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12316            PackageParser.Package pkg) {
12317        int size = pkg.activities.size();
12318        if (size == 0) {
12319            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12320                    "No activity, so no need to verify any IntentFilter!");
12321            return;
12322        }
12323
12324        final boolean hasDomainURLs = hasDomainURLs(pkg);
12325        if (!hasDomainURLs) {
12326            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12327                    "No domain URLs, so no need to verify any IntentFilter!");
12328            return;
12329        }
12330
12331        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12332                + " if any IntentFilter from the " + size
12333                + " Activities needs verification ...");
12334
12335        int count = 0;
12336        final String packageName = pkg.packageName;
12337
12338        synchronized (mPackages) {
12339            // If this is a new install and we see that we've already run verification for this
12340            // package, we have nothing to do: it means the state was restored from backup.
12341            if (!replacing) {
12342                IntentFilterVerificationInfo ivi =
12343                        mSettings.getIntentFilterVerificationLPr(packageName);
12344                if (ivi != null) {
12345                    if (DEBUG_DOMAIN_VERIFICATION) {
12346                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12347                                + ivi.getStatusString());
12348                    }
12349                    return;
12350                }
12351            }
12352
12353            // If any filters need to be verified, then all need to be.
12354            boolean needToVerify = false;
12355            for (PackageParser.Activity a : pkg.activities) {
12356                for (ActivityIntentInfo filter : a.intents) {
12357                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12358                        if (DEBUG_DOMAIN_VERIFICATION) {
12359                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12360                        }
12361                        needToVerify = true;
12362                        break;
12363                    }
12364                }
12365            }
12366
12367            if (needToVerify) {
12368                final int verificationId = mIntentFilterVerificationToken++;
12369                for (PackageParser.Activity a : pkg.activities) {
12370                    for (ActivityIntentInfo filter : a.intents) {
12371                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12372                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12373                                    "Verification needed for IntentFilter:" + filter.toString());
12374                            mIntentFilterVerifier.addOneIntentFilterVerification(
12375                                    verifierUid, userId, verificationId, filter, packageName);
12376                            count++;
12377                        }
12378                    }
12379                }
12380            }
12381        }
12382
12383        if (count > 0) {
12384            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12385                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12386                    +  " for userId:" + userId);
12387            mIntentFilterVerifier.startVerifications(userId);
12388        } else {
12389            if (DEBUG_DOMAIN_VERIFICATION) {
12390                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12391            }
12392        }
12393    }
12394
12395    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12396        final ComponentName cn  = filter.activity.getComponentName();
12397        final String packageName = cn.getPackageName();
12398
12399        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12400                packageName);
12401        if (ivi == null) {
12402            return true;
12403        }
12404        int status = ivi.getStatus();
12405        switch (status) {
12406            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12407            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12408                return true;
12409
12410            default:
12411                // Nothing to do
12412                return false;
12413        }
12414    }
12415
12416    private static boolean isMultiArch(PackageSetting ps) {
12417        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12418    }
12419
12420    private static boolean isMultiArch(ApplicationInfo info) {
12421        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12422    }
12423
12424    private static boolean isExternal(PackageParser.Package pkg) {
12425        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12426    }
12427
12428    private static boolean isExternal(PackageSetting ps) {
12429        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12430    }
12431
12432    private static boolean isExternal(ApplicationInfo info) {
12433        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12434    }
12435
12436    private static boolean isSystemApp(PackageParser.Package pkg) {
12437        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12438    }
12439
12440    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12441        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12442    }
12443
12444    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12445        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12446    }
12447
12448    private static boolean isSystemApp(PackageSetting ps) {
12449        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12450    }
12451
12452    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12453        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12454    }
12455
12456    private int packageFlagsToInstallFlags(PackageSetting ps) {
12457        int installFlags = 0;
12458        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12459            // This existing package was an external ASEC install when we have
12460            // the external flag without a UUID
12461            installFlags |= PackageManager.INSTALL_EXTERNAL;
12462        }
12463        if (ps.isForwardLocked()) {
12464            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12465        }
12466        return installFlags;
12467    }
12468
12469    private void deleteTempPackageFiles() {
12470        final FilenameFilter filter = new FilenameFilter() {
12471            public boolean accept(File dir, String name) {
12472                return name.startsWith("vmdl") && name.endsWith(".tmp");
12473            }
12474        };
12475        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12476            file.delete();
12477        }
12478    }
12479
12480    @Override
12481    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12482            int flags) {
12483        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12484                flags);
12485    }
12486
12487    @Override
12488    public void deletePackage(final String packageName,
12489            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12490        mContext.enforceCallingOrSelfPermission(
12491                android.Manifest.permission.DELETE_PACKAGES, null);
12492        Preconditions.checkNotNull(packageName);
12493        Preconditions.checkNotNull(observer);
12494        final int uid = Binder.getCallingUid();
12495        if (UserHandle.getUserId(uid) != userId) {
12496            mContext.enforceCallingPermission(
12497                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12498                    "deletePackage for user " + userId);
12499        }
12500        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12501            try {
12502                observer.onPackageDeleted(packageName,
12503                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12504            } catch (RemoteException re) {
12505            }
12506            return;
12507        }
12508
12509        boolean uninstallBlocked = false;
12510        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12511            int[] users = sUserManager.getUserIds();
12512            for (int i = 0; i < users.length; ++i) {
12513                if (getBlockUninstallForUser(packageName, users[i])) {
12514                    uninstallBlocked = true;
12515                    break;
12516                }
12517            }
12518        } else {
12519            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12520        }
12521        if (uninstallBlocked) {
12522            try {
12523                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12524                        null);
12525            } catch (RemoteException re) {
12526            }
12527            return;
12528        }
12529
12530        if (DEBUG_REMOVE) {
12531            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12532        }
12533        // Queue up an async operation since the package deletion may take a little while.
12534        mHandler.post(new Runnable() {
12535            public void run() {
12536                mHandler.removeCallbacks(this);
12537                final int returnCode = deletePackageX(packageName, userId, flags);
12538                if (observer != null) {
12539                    try {
12540                        observer.onPackageDeleted(packageName, returnCode, null);
12541                    } catch (RemoteException e) {
12542                        Log.i(TAG, "Observer no longer exists.");
12543                    } //end catch
12544                } //end if
12545            } //end run
12546        });
12547    }
12548
12549    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12550        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12551                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12552        try {
12553            if (dpm != null) {
12554                if (dpm.isDeviceOwner(packageName)) {
12555                    return true;
12556                }
12557                int[] users;
12558                if (userId == UserHandle.USER_ALL) {
12559                    users = sUserManager.getUserIds();
12560                } else {
12561                    users = new int[]{userId};
12562                }
12563                for (int i = 0; i < users.length; ++i) {
12564                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12565                        return true;
12566                    }
12567                }
12568            }
12569        } catch (RemoteException e) {
12570        }
12571        return false;
12572    }
12573
12574    /**
12575     *  This method is an internal method that could be get invoked either
12576     *  to delete an installed package or to clean up a failed installation.
12577     *  After deleting an installed package, a broadcast is sent to notify any
12578     *  listeners that the package has been installed. For cleaning up a failed
12579     *  installation, the broadcast is not necessary since the package's
12580     *  installation wouldn't have sent the initial broadcast either
12581     *  The key steps in deleting a package are
12582     *  deleting the package information in internal structures like mPackages,
12583     *  deleting the packages base directories through installd
12584     *  updating mSettings to reflect current status
12585     *  persisting settings for later use
12586     *  sending a broadcast if necessary
12587     */
12588    private int deletePackageX(String packageName, int userId, int flags) {
12589        final PackageRemovedInfo info = new PackageRemovedInfo();
12590        final boolean res;
12591
12592        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12593                ? UserHandle.ALL : new UserHandle(userId);
12594
12595        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12596            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12597            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12598        }
12599
12600        boolean removedForAllUsers = false;
12601        boolean systemUpdate = false;
12602
12603        // for the uninstall-updates case and restricted profiles, remember the per-
12604        // userhandle installed state
12605        int[] allUsers;
12606        boolean[] perUserInstalled;
12607        synchronized (mPackages) {
12608            PackageSetting ps = mSettings.mPackages.get(packageName);
12609            allUsers = sUserManager.getUserIds();
12610            perUserInstalled = new boolean[allUsers.length];
12611            for (int i = 0; i < allUsers.length; i++) {
12612                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12613            }
12614        }
12615
12616        synchronized (mInstallLock) {
12617            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12618            res = deletePackageLI(packageName, removeForUser,
12619                    true, allUsers, perUserInstalled,
12620                    flags | REMOVE_CHATTY, info, true);
12621            systemUpdate = info.isRemovedPackageSystemUpdate;
12622            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12623                removedForAllUsers = true;
12624            }
12625            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12626                    + " removedForAllUsers=" + removedForAllUsers);
12627        }
12628
12629        if (res) {
12630            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12631
12632            // If the removed package was a system update, the old system package
12633            // was re-enabled; we need to broadcast this information
12634            if (systemUpdate) {
12635                Bundle extras = new Bundle(1);
12636                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12637                        ? info.removedAppId : info.uid);
12638                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12639
12640                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12641                        extras, null, null, null);
12642                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12643                        extras, null, null, null);
12644                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12645                        null, packageName, null, null);
12646            }
12647        }
12648        // Force a gc here.
12649        Runtime.getRuntime().gc();
12650        // Delete the resources here after sending the broadcast to let
12651        // other processes clean up before deleting resources.
12652        if (info.args != null) {
12653            synchronized (mInstallLock) {
12654                info.args.doPostDeleteLI(true);
12655            }
12656        }
12657
12658        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12659    }
12660
12661    class PackageRemovedInfo {
12662        String removedPackage;
12663        int uid = -1;
12664        int removedAppId = -1;
12665        int[] removedUsers = null;
12666        boolean isRemovedPackageSystemUpdate = false;
12667        // Clean up resources deleted packages.
12668        InstallArgs args = null;
12669
12670        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12671            Bundle extras = new Bundle(1);
12672            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12673            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12674            if (replacing) {
12675                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12676            }
12677            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12678            if (removedPackage != null) {
12679                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12680                        extras, null, null, removedUsers);
12681                if (fullRemove && !replacing) {
12682                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12683                            extras, null, null, removedUsers);
12684                }
12685            }
12686            if (removedAppId >= 0) {
12687                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12688                        removedUsers);
12689            }
12690        }
12691    }
12692
12693    /*
12694     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12695     * flag is not set, the data directory is removed as well.
12696     * make sure this flag is set for partially installed apps. If not its meaningless to
12697     * delete a partially installed application.
12698     */
12699    private void removePackageDataLI(PackageSetting ps,
12700            int[] allUserHandles, boolean[] perUserInstalled,
12701            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12702        String packageName = ps.name;
12703        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12704        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12705        // Retrieve object to delete permissions for shared user later on
12706        final PackageSetting deletedPs;
12707        // reader
12708        synchronized (mPackages) {
12709            deletedPs = mSettings.mPackages.get(packageName);
12710            if (outInfo != null) {
12711                outInfo.removedPackage = packageName;
12712                outInfo.removedUsers = deletedPs != null
12713                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12714                        : null;
12715            }
12716        }
12717        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12718            removeDataDirsLI(ps.volumeUuid, packageName);
12719            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12720        }
12721        // writer
12722        synchronized (mPackages) {
12723            if (deletedPs != null) {
12724                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12725                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12726                    clearDefaultBrowserIfNeeded(packageName);
12727                    if (outInfo != null) {
12728                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12729                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12730                    }
12731                    updatePermissionsLPw(deletedPs.name, null, 0);
12732                    if (deletedPs.sharedUser != null) {
12733                        // Remove permissions associated with package. Since runtime
12734                        // permissions are per user we have to kill the removed package
12735                        // or packages running under the shared user of the removed
12736                        // package if revoking the permissions requested only by the removed
12737                        // package is successful and this causes a change in gids.
12738                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12739                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12740                                    userId);
12741                            if (userIdToKill == UserHandle.USER_ALL
12742                                    || userIdToKill >= UserHandle.USER_OWNER) {
12743                                // If gids changed for this user, kill all affected packages.
12744                                mHandler.post(new Runnable() {
12745                                    @Override
12746                                    public void run() {
12747                                        // This has to happen with no lock held.
12748                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12749                                                KILL_APP_REASON_GIDS_CHANGED);
12750                                    }
12751                                });
12752                                break;
12753                            }
12754                        }
12755                    }
12756                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12757                }
12758                // make sure to preserve per-user disabled state if this removal was just
12759                // a downgrade of a system app to the factory package
12760                if (allUserHandles != null && perUserInstalled != null) {
12761                    if (DEBUG_REMOVE) {
12762                        Slog.d(TAG, "Propagating install state across downgrade");
12763                    }
12764                    for (int i = 0; i < allUserHandles.length; i++) {
12765                        if (DEBUG_REMOVE) {
12766                            Slog.d(TAG, "    user " + allUserHandles[i]
12767                                    + " => " + perUserInstalled[i]);
12768                        }
12769                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12770                    }
12771                }
12772            }
12773            // can downgrade to reader
12774            if (writeSettings) {
12775                // Save settings now
12776                mSettings.writeLPr();
12777            }
12778        }
12779        if (outInfo != null) {
12780            // A user ID was deleted here. Go through all users and remove it
12781            // from KeyStore.
12782            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12783        }
12784    }
12785
12786    static boolean locationIsPrivileged(File path) {
12787        try {
12788            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12789                    .getCanonicalPath();
12790            return path.getCanonicalPath().startsWith(privilegedAppDir);
12791        } catch (IOException e) {
12792            Slog.e(TAG, "Unable to access code path " + path);
12793        }
12794        return false;
12795    }
12796
12797    /*
12798     * Tries to delete system package.
12799     */
12800    private boolean deleteSystemPackageLI(PackageSetting newPs,
12801            int[] allUserHandles, boolean[] perUserInstalled,
12802            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12803        final boolean applyUserRestrictions
12804                = (allUserHandles != null) && (perUserInstalled != null);
12805        PackageSetting disabledPs = null;
12806        // Confirm if the system package has been updated
12807        // An updated system app can be deleted. This will also have to restore
12808        // the system pkg from system partition
12809        // reader
12810        synchronized (mPackages) {
12811            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12812        }
12813        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12814                + " disabledPs=" + disabledPs);
12815        if (disabledPs == null) {
12816            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12817            return false;
12818        } else if (DEBUG_REMOVE) {
12819            Slog.d(TAG, "Deleting system pkg from data partition");
12820        }
12821        if (DEBUG_REMOVE) {
12822            if (applyUserRestrictions) {
12823                Slog.d(TAG, "Remembering install states:");
12824                for (int i = 0; i < allUserHandles.length; i++) {
12825                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12826                }
12827            }
12828        }
12829        // Delete the updated package
12830        outInfo.isRemovedPackageSystemUpdate = true;
12831        if (disabledPs.versionCode < newPs.versionCode) {
12832            // Delete data for downgrades
12833            flags &= ~PackageManager.DELETE_KEEP_DATA;
12834        } else {
12835            // Preserve data by setting flag
12836            flags |= PackageManager.DELETE_KEEP_DATA;
12837        }
12838        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12839                allUserHandles, perUserInstalled, outInfo, writeSettings);
12840        if (!ret) {
12841            return false;
12842        }
12843        // writer
12844        synchronized (mPackages) {
12845            // Reinstate the old system package
12846            mSettings.enableSystemPackageLPw(newPs.name);
12847            // Remove any native libraries from the upgraded package.
12848            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12849        }
12850        // Install the system package
12851        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12852        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12853        if (locationIsPrivileged(disabledPs.codePath)) {
12854            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12855        }
12856
12857        final PackageParser.Package newPkg;
12858        try {
12859            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12860        } catch (PackageManagerException e) {
12861            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12862            return false;
12863        }
12864
12865        // writer
12866        synchronized (mPackages) {
12867            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12868
12869            // Propagate the permissions state as we do want to drop on the floor
12870            // runtime permissions. The update permissions method below will take
12871            // care of removing obsolete permissions and grant install permissions.
12872            ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState());
12873            updatePermissionsLPw(newPkg.packageName, newPkg,
12874                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12875
12876            if (applyUserRestrictions) {
12877                if (DEBUG_REMOVE) {
12878                    Slog.d(TAG, "Propagating install state across reinstall");
12879                }
12880                for (int i = 0; i < allUserHandles.length; i++) {
12881                    if (DEBUG_REMOVE) {
12882                        Slog.d(TAG, "    user " + allUserHandles[i]
12883                                + " => " + perUserInstalled[i]);
12884                    }
12885                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12886                }
12887                // Regardless of writeSettings we need to ensure that this restriction
12888                // state propagation is persisted
12889                mSettings.writeAllUsersPackageRestrictionsLPr();
12890            }
12891            // can downgrade to reader here
12892            if (writeSettings) {
12893                mSettings.writeLPr();
12894            }
12895        }
12896        return true;
12897    }
12898
12899    private boolean deleteInstalledPackageLI(PackageSetting ps,
12900            boolean deleteCodeAndResources, int flags,
12901            int[] allUserHandles, boolean[] perUserInstalled,
12902            PackageRemovedInfo outInfo, boolean writeSettings) {
12903        if (outInfo != null) {
12904            outInfo.uid = ps.appId;
12905        }
12906
12907        // Delete package data from internal structures and also remove data if flag is set
12908        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12909
12910        // Delete application code and resources
12911        if (deleteCodeAndResources && (outInfo != null)) {
12912            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12913                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12914            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12915        }
12916        return true;
12917    }
12918
12919    @Override
12920    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12921            int userId) {
12922        mContext.enforceCallingOrSelfPermission(
12923                android.Manifest.permission.DELETE_PACKAGES, null);
12924        synchronized (mPackages) {
12925            PackageSetting ps = mSettings.mPackages.get(packageName);
12926            if (ps == null) {
12927                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12928                return false;
12929            }
12930            if (!ps.getInstalled(userId)) {
12931                // Can't block uninstall for an app that is not installed or enabled.
12932                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12933                return false;
12934            }
12935            ps.setBlockUninstall(blockUninstall, userId);
12936            mSettings.writePackageRestrictionsLPr(userId);
12937        }
12938        return true;
12939    }
12940
12941    @Override
12942    public boolean getBlockUninstallForUser(String packageName, int userId) {
12943        synchronized (mPackages) {
12944            PackageSetting ps = mSettings.mPackages.get(packageName);
12945            if (ps == null) {
12946                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12947                return false;
12948            }
12949            return ps.getBlockUninstall(userId);
12950        }
12951    }
12952
12953    /*
12954     * This method handles package deletion in general
12955     */
12956    private boolean deletePackageLI(String packageName, UserHandle user,
12957            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12958            int flags, PackageRemovedInfo outInfo,
12959            boolean writeSettings) {
12960        if (packageName == null) {
12961            Slog.w(TAG, "Attempt to delete null packageName.");
12962            return false;
12963        }
12964        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12965        PackageSetting ps;
12966        boolean dataOnly = false;
12967        int removeUser = -1;
12968        int appId = -1;
12969        synchronized (mPackages) {
12970            ps = mSettings.mPackages.get(packageName);
12971            if (ps == null) {
12972                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12973                return false;
12974            }
12975            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12976                    && user.getIdentifier() != UserHandle.USER_ALL) {
12977                // The caller is asking that the package only be deleted for a single
12978                // user.  To do this, we just mark its uninstalled state and delete
12979                // its data.  If this is a system app, we only allow this to happen if
12980                // they have set the special DELETE_SYSTEM_APP which requests different
12981                // semantics than normal for uninstalling system apps.
12982                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12983                ps.setUserState(user.getIdentifier(),
12984                        COMPONENT_ENABLED_STATE_DEFAULT,
12985                        false, //installed
12986                        true,  //stopped
12987                        true,  //notLaunched
12988                        false, //hidden
12989                        null, null, null,
12990                        false, // blockUninstall
12991                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0);
12992                if (!isSystemApp(ps)) {
12993                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12994                        // Other user still have this package installed, so all
12995                        // we need to do is clear this user's data and save that
12996                        // it is uninstalled.
12997                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12998                        removeUser = user.getIdentifier();
12999                        appId = ps.appId;
13000                        scheduleWritePackageRestrictionsLocked(removeUser);
13001                    } else {
13002                        // We need to set it back to 'installed' so the uninstall
13003                        // broadcasts will be sent correctly.
13004                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13005                        ps.setInstalled(true, user.getIdentifier());
13006                    }
13007                } else {
13008                    // This is a system app, so we assume that the
13009                    // other users still have this package installed, so all
13010                    // we need to do is clear this user's data and save that
13011                    // it is uninstalled.
13012                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13013                    removeUser = user.getIdentifier();
13014                    appId = ps.appId;
13015                    scheduleWritePackageRestrictionsLocked(removeUser);
13016                }
13017            }
13018        }
13019
13020        if (removeUser >= 0) {
13021            // From above, we determined that we are deleting this only
13022            // for a single user.  Continue the work here.
13023            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13024            if (outInfo != null) {
13025                outInfo.removedPackage = packageName;
13026                outInfo.removedAppId = appId;
13027                outInfo.removedUsers = new int[] {removeUser};
13028            }
13029            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13030            removeKeystoreDataIfNeeded(removeUser, appId);
13031            schedulePackageCleaning(packageName, removeUser, false);
13032            synchronized (mPackages) {
13033                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13034                    scheduleWritePackageRestrictionsLocked(removeUser);
13035                }
13036                resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser);
13037            }
13038            return true;
13039        }
13040
13041        if (dataOnly) {
13042            // Delete application data first
13043            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13044            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13045            return true;
13046        }
13047
13048        boolean ret = false;
13049        if (isSystemApp(ps)) {
13050            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13051            // When an updated system application is deleted we delete the existing resources as well and
13052            // fall back to existing code in system partition
13053            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13054                    flags, outInfo, writeSettings);
13055        } else {
13056            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13057            // Kill application pre-emptively especially for apps on sd.
13058            killApplication(packageName, ps.appId, "uninstall pkg");
13059            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13060                    allUserHandles, perUserInstalled,
13061                    outInfo, writeSettings);
13062        }
13063
13064        return ret;
13065    }
13066
13067    private final class ClearStorageConnection implements ServiceConnection {
13068        IMediaContainerService mContainerService;
13069
13070        @Override
13071        public void onServiceConnected(ComponentName name, IBinder service) {
13072            synchronized (this) {
13073                mContainerService = IMediaContainerService.Stub.asInterface(service);
13074                notifyAll();
13075            }
13076        }
13077
13078        @Override
13079        public void onServiceDisconnected(ComponentName name) {
13080        }
13081    }
13082
13083    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13084        final boolean mounted;
13085        if (Environment.isExternalStorageEmulated()) {
13086            mounted = true;
13087        } else {
13088            final String status = Environment.getExternalStorageState();
13089
13090            mounted = status.equals(Environment.MEDIA_MOUNTED)
13091                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13092        }
13093
13094        if (!mounted) {
13095            return;
13096        }
13097
13098        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13099        int[] users;
13100        if (userId == UserHandle.USER_ALL) {
13101            users = sUserManager.getUserIds();
13102        } else {
13103            users = new int[] { userId };
13104        }
13105        final ClearStorageConnection conn = new ClearStorageConnection();
13106        if (mContext.bindServiceAsUser(
13107                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13108            try {
13109                for (int curUser : users) {
13110                    long timeout = SystemClock.uptimeMillis() + 5000;
13111                    synchronized (conn) {
13112                        long now = SystemClock.uptimeMillis();
13113                        while (conn.mContainerService == null && now < timeout) {
13114                            try {
13115                                conn.wait(timeout - now);
13116                            } catch (InterruptedException e) {
13117                            }
13118                        }
13119                    }
13120                    if (conn.mContainerService == null) {
13121                        return;
13122                    }
13123
13124                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13125                    clearDirectory(conn.mContainerService,
13126                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13127                    if (allData) {
13128                        clearDirectory(conn.mContainerService,
13129                                userEnv.buildExternalStorageAppDataDirs(packageName));
13130                        clearDirectory(conn.mContainerService,
13131                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13132                    }
13133                }
13134            } finally {
13135                mContext.unbindService(conn);
13136            }
13137        }
13138    }
13139
13140    @Override
13141    public void clearApplicationUserData(final String packageName,
13142            final IPackageDataObserver observer, final int userId) {
13143        mContext.enforceCallingOrSelfPermission(
13144                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13145        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13146        // Queue up an async operation since the package deletion may take a little while.
13147        mHandler.post(new Runnable() {
13148            public void run() {
13149                mHandler.removeCallbacks(this);
13150                final boolean succeeded;
13151                synchronized (mInstallLock) {
13152                    succeeded = clearApplicationUserDataLI(packageName, userId);
13153                }
13154                clearExternalStorageDataSync(packageName, userId, true);
13155                if (succeeded) {
13156                    // invoke DeviceStorageMonitor's update method to clear any notifications
13157                    DeviceStorageMonitorInternal
13158                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13159                    if (dsm != null) {
13160                        dsm.checkMemory();
13161                    }
13162                }
13163                if(observer != null) {
13164                    try {
13165                        observer.onRemoveCompleted(packageName, succeeded);
13166                    } catch (RemoteException e) {
13167                        Log.i(TAG, "Observer no longer exists.");
13168                    }
13169                } //end if observer
13170            } //end run
13171        });
13172    }
13173
13174    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13175        if (packageName == null) {
13176            Slog.w(TAG, "Attempt to delete null packageName.");
13177            return false;
13178        }
13179
13180        // Try finding details about the requested package
13181        PackageParser.Package pkg;
13182        synchronized (mPackages) {
13183            pkg = mPackages.get(packageName);
13184            if (pkg == null) {
13185                final PackageSetting ps = mSettings.mPackages.get(packageName);
13186                if (ps != null) {
13187                    pkg = ps.pkg;
13188                }
13189            }
13190
13191            if (pkg == null) {
13192                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13193                return false;
13194            }
13195
13196            PackageSetting ps = (PackageSetting) pkg.mExtras;
13197            resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
13198        }
13199
13200        // Always delete data directories for package, even if we found no other
13201        // record of app. This helps users recover from UID mismatches without
13202        // resorting to a full data wipe.
13203        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13204        if (retCode < 0) {
13205            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13206            return false;
13207        }
13208
13209        final int appId = pkg.applicationInfo.uid;
13210        removeKeystoreDataIfNeeded(userId, appId);
13211
13212        // Create a native library symlink only if we have native libraries
13213        // and if the native libraries are 32 bit libraries. We do not provide
13214        // this symlink for 64 bit libraries.
13215        if (pkg.applicationInfo.primaryCpuAbi != null &&
13216                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13217            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13218            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13219                    nativeLibPath, userId) < 0) {
13220                Slog.w(TAG, "Failed linking native library dir");
13221                return false;
13222            }
13223        }
13224
13225        return true;
13226    }
13227
13228    /**
13229     * Reverts user permission state changes (permissions and flags).
13230     *
13231     * @param ps The package for which to reset.
13232     * @param userId The device user for which to do a reset.
13233     */
13234    private void resetUserChangesToRuntimePermissionsAndFlagsLocked(
13235            final PackageSetting ps, final int userId) {
13236        if (ps.pkg == null) {
13237            return;
13238        }
13239
13240        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13241                | FLAG_PERMISSION_USER_FIXED
13242                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13243
13244        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13245                | FLAG_PERMISSION_POLICY_FIXED;
13246
13247        boolean writeInstallPermissions = false;
13248        boolean writeRuntimePermissions = false;
13249
13250        final int permissionCount = ps.pkg.requestedPermissions.size();
13251        for (int i = 0; i < permissionCount; i++) {
13252            String permission = ps.pkg.requestedPermissions.get(i);
13253
13254            BasePermission bp = mSettings.mPermissions.get(permission);
13255            if (bp == null) {
13256                continue;
13257            }
13258
13259            // If shared user we just reset the state to which only this app contributed.
13260            if (ps.sharedUser != null) {
13261                boolean used = false;
13262                final int packageCount = ps.sharedUser.packages.size();
13263                for (int j = 0; j < packageCount; j++) {
13264                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13265                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13266                            && pkg.pkg.requestedPermissions.contains(permission)) {
13267                        used = true;
13268                        break;
13269                    }
13270                }
13271                if (used) {
13272                    continue;
13273                }
13274            }
13275
13276            PermissionsState permissionsState = ps.getPermissionsState();
13277
13278            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13279
13280            // Always clear the user settable flags.
13281            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13282                    bp.name) != null;
13283            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13284                if (hasInstallState) {
13285                    writeInstallPermissions = true;
13286                } else {
13287                    writeRuntimePermissions = true;
13288                }
13289            }
13290
13291            // Below is only runtime permission handling.
13292            if (!bp.isRuntime()) {
13293                continue;
13294            }
13295
13296            // Never clobber system or policy.
13297            if ((oldFlags & policyOrSystemFlags) != 0) {
13298                continue;
13299            }
13300
13301            // If this permission was granted by default, make sure it is.
13302            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13303                if (permissionsState.grantRuntimePermission(bp, userId)
13304                        != PERMISSION_OPERATION_FAILURE) {
13305                    writeRuntimePermissions = true;
13306                }
13307            } else {
13308                // Otherwise, reset the permission.
13309                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13310                switch (revokeResult) {
13311                    case PERMISSION_OPERATION_SUCCESS: {
13312                        writeRuntimePermissions = true;
13313                    } break;
13314
13315                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13316                        writeRuntimePermissions = true;
13317                        // If gids changed for this user, kill all affected packages.
13318                        mHandler.post(new Runnable() {
13319                            @Override
13320                            public void run() {
13321                                // This has to happen with no lock held.
13322                                killSettingPackagesForUser(ps, userId,
13323                                        KILL_APP_REASON_GIDS_CHANGED);
13324                            }
13325                        });
13326                    } break;
13327                }
13328            }
13329        }
13330
13331        // Synchronously write as we are taking permissions away.
13332        if (writeRuntimePermissions) {
13333            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13334        }
13335
13336        // Synchronously write as we are taking permissions away.
13337        if (writeInstallPermissions) {
13338            mSettings.writeLPr();
13339        }
13340    }
13341
13342    /**
13343     * Remove entries from the keystore daemon. Will only remove it if the
13344     * {@code appId} is valid.
13345     */
13346    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13347        if (appId < 0) {
13348            return;
13349        }
13350
13351        final KeyStore keyStore = KeyStore.getInstance();
13352        if (keyStore != null) {
13353            if (userId == UserHandle.USER_ALL) {
13354                for (final int individual : sUserManager.getUserIds()) {
13355                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13356                }
13357            } else {
13358                keyStore.clearUid(UserHandle.getUid(userId, appId));
13359            }
13360        } else {
13361            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13362        }
13363    }
13364
13365    @Override
13366    public void deleteApplicationCacheFiles(final String packageName,
13367            final IPackageDataObserver observer) {
13368        mContext.enforceCallingOrSelfPermission(
13369                android.Manifest.permission.DELETE_CACHE_FILES, null);
13370        // Queue up an async operation since the package deletion may take a little while.
13371        final int userId = UserHandle.getCallingUserId();
13372        mHandler.post(new Runnable() {
13373            public void run() {
13374                mHandler.removeCallbacks(this);
13375                final boolean succeded;
13376                synchronized (mInstallLock) {
13377                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13378                }
13379                clearExternalStorageDataSync(packageName, userId, false);
13380                if (observer != null) {
13381                    try {
13382                        observer.onRemoveCompleted(packageName, succeded);
13383                    } catch (RemoteException e) {
13384                        Log.i(TAG, "Observer no longer exists.");
13385                    }
13386                } //end if observer
13387            } //end run
13388        });
13389    }
13390
13391    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13392        if (packageName == null) {
13393            Slog.w(TAG, "Attempt to delete null packageName.");
13394            return false;
13395        }
13396        PackageParser.Package p;
13397        synchronized (mPackages) {
13398            p = mPackages.get(packageName);
13399        }
13400        if (p == null) {
13401            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13402            return false;
13403        }
13404        final ApplicationInfo applicationInfo = p.applicationInfo;
13405        if (applicationInfo == null) {
13406            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13407            return false;
13408        }
13409        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13410        if (retCode < 0) {
13411            Slog.w(TAG, "Couldn't remove cache files for package: "
13412                       + packageName + " u" + userId);
13413            return false;
13414        }
13415        return true;
13416    }
13417
13418    @Override
13419    public void getPackageSizeInfo(final String packageName, int userHandle,
13420            final IPackageStatsObserver observer) {
13421        mContext.enforceCallingOrSelfPermission(
13422                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13423        if (packageName == null) {
13424            throw new IllegalArgumentException("Attempt to get size of null packageName");
13425        }
13426
13427        PackageStats stats = new PackageStats(packageName, userHandle);
13428
13429        /*
13430         * Queue up an async operation since the package measurement may take a
13431         * little while.
13432         */
13433        Message msg = mHandler.obtainMessage(INIT_COPY);
13434        msg.obj = new MeasureParams(stats, observer);
13435        mHandler.sendMessage(msg);
13436    }
13437
13438    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13439            PackageStats pStats) {
13440        if (packageName == null) {
13441            Slog.w(TAG, "Attempt to get size of null packageName.");
13442            return false;
13443        }
13444        PackageParser.Package p;
13445        boolean dataOnly = false;
13446        String libDirRoot = null;
13447        String asecPath = null;
13448        PackageSetting ps = null;
13449        synchronized (mPackages) {
13450            p = mPackages.get(packageName);
13451            ps = mSettings.mPackages.get(packageName);
13452            if(p == null) {
13453                dataOnly = true;
13454                if((ps == null) || (ps.pkg == null)) {
13455                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13456                    return false;
13457                }
13458                p = ps.pkg;
13459            }
13460            if (ps != null) {
13461                libDirRoot = ps.legacyNativeLibraryPathString;
13462            }
13463            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13464                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13465                if (secureContainerId != null) {
13466                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13467                }
13468            }
13469        }
13470        String publicSrcDir = null;
13471        if(!dataOnly) {
13472            final ApplicationInfo applicationInfo = p.applicationInfo;
13473            if (applicationInfo == null) {
13474                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13475                return false;
13476            }
13477            if (p.isForwardLocked()) {
13478                publicSrcDir = applicationInfo.getBaseResourcePath();
13479            }
13480        }
13481        // TODO: extend to measure size of split APKs
13482        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13483        // not just the first level.
13484        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13485        // just the primary.
13486        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13487        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13488                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13489        if (res < 0) {
13490            return false;
13491        }
13492
13493        // Fix-up for forward-locked applications in ASEC containers.
13494        if (!isExternal(p)) {
13495            pStats.codeSize += pStats.externalCodeSize;
13496            pStats.externalCodeSize = 0L;
13497        }
13498
13499        return true;
13500    }
13501
13502
13503    @Override
13504    public void addPackageToPreferred(String packageName) {
13505        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13506    }
13507
13508    @Override
13509    public void removePackageFromPreferred(String packageName) {
13510        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13511    }
13512
13513    @Override
13514    public List<PackageInfo> getPreferredPackages(int flags) {
13515        return new ArrayList<PackageInfo>();
13516    }
13517
13518    private int getUidTargetSdkVersionLockedLPr(int uid) {
13519        Object obj = mSettings.getUserIdLPr(uid);
13520        if (obj instanceof SharedUserSetting) {
13521            final SharedUserSetting sus = (SharedUserSetting) obj;
13522            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13523            final Iterator<PackageSetting> it = sus.packages.iterator();
13524            while (it.hasNext()) {
13525                final PackageSetting ps = it.next();
13526                if (ps.pkg != null) {
13527                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13528                    if (v < vers) vers = v;
13529                }
13530            }
13531            return vers;
13532        } else if (obj instanceof PackageSetting) {
13533            final PackageSetting ps = (PackageSetting) obj;
13534            if (ps.pkg != null) {
13535                return ps.pkg.applicationInfo.targetSdkVersion;
13536            }
13537        }
13538        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13539    }
13540
13541    @Override
13542    public void addPreferredActivity(IntentFilter filter, int match,
13543            ComponentName[] set, ComponentName activity, int userId) {
13544        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13545                "Adding preferred");
13546    }
13547
13548    private void addPreferredActivityInternal(IntentFilter filter, int match,
13549            ComponentName[] set, ComponentName activity, boolean always, int userId,
13550            String opname) {
13551        // writer
13552        int callingUid = Binder.getCallingUid();
13553        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13554        if (filter.countActions() == 0) {
13555            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13556            return;
13557        }
13558        synchronized (mPackages) {
13559            if (mContext.checkCallingOrSelfPermission(
13560                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13561                    != PackageManager.PERMISSION_GRANTED) {
13562                if (getUidTargetSdkVersionLockedLPr(callingUid)
13563                        < Build.VERSION_CODES.FROYO) {
13564                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13565                            + callingUid);
13566                    return;
13567                }
13568                mContext.enforceCallingOrSelfPermission(
13569                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13570            }
13571
13572            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13573            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13574                    + userId + ":");
13575            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13576            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13577            scheduleWritePackageRestrictionsLocked(userId);
13578        }
13579    }
13580
13581    @Override
13582    public void replacePreferredActivity(IntentFilter filter, int match,
13583            ComponentName[] set, ComponentName activity, int userId) {
13584        if (filter.countActions() != 1) {
13585            throw new IllegalArgumentException(
13586                    "replacePreferredActivity expects filter to have only 1 action.");
13587        }
13588        if (filter.countDataAuthorities() != 0
13589                || filter.countDataPaths() != 0
13590                || filter.countDataSchemes() > 1
13591                || filter.countDataTypes() != 0) {
13592            throw new IllegalArgumentException(
13593                    "replacePreferredActivity expects filter to have no data authorities, " +
13594                    "paths, or types; and at most one scheme.");
13595        }
13596
13597        final int callingUid = Binder.getCallingUid();
13598        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13599        synchronized (mPackages) {
13600            if (mContext.checkCallingOrSelfPermission(
13601                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13602                    != PackageManager.PERMISSION_GRANTED) {
13603                if (getUidTargetSdkVersionLockedLPr(callingUid)
13604                        < Build.VERSION_CODES.FROYO) {
13605                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13606                            + Binder.getCallingUid());
13607                    return;
13608                }
13609                mContext.enforceCallingOrSelfPermission(
13610                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13611            }
13612
13613            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13614            if (pir != null) {
13615                // Get all of the existing entries that exactly match this filter.
13616                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13617                if (existing != null && existing.size() == 1) {
13618                    PreferredActivity cur = existing.get(0);
13619                    if (DEBUG_PREFERRED) {
13620                        Slog.i(TAG, "Checking replace of preferred:");
13621                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13622                        if (!cur.mPref.mAlways) {
13623                            Slog.i(TAG, "  -- CUR; not mAlways!");
13624                        } else {
13625                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13626                            Slog.i(TAG, "  -- CUR: mSet="
13627                                    + Arrays.toString(cur.mPref.mSetComponents));
13628                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13629                            Slog.i(TAG, "  -- NEW: mMatch="
13630                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13631                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13632                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13633                        }
13634                    }
13635                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13636                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13637                            && cur.mPref.sameSet(set)) {
13638                        // Setting the preferred activity to what it happens to be already
13639                        if (DEBUG_PREFERRED) {
13640                            Slog.i(TAG, "Replacing with same preferred activity "
13641                                    + cur.mPref.mShortComponent + " for user "
13642                                    + userId + ":");
13643                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13644                        }
13645                        return;
13646                    }
13647                }
13648
13649                if (existing != null) {
13650                    if (DEBUG_PREFERRED) {
13651                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13652                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13653                    }
13654                    for (int i = 0; i < existing.size(); i++) {
13655                        PreferredActivity pa = existing.get(i);
13656                        if (DEBUG_PREFERRED) {
13657                            Slog.i(TAG, "Removing existing preferred activity "
13658                                    + pa.mPref.mComponent + ":");
13659                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13660                        }
13661                        pir.removeFilter(pa);
13662                    }
13663                }
13664            }
13665            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13666                    "Replacing preferred");
13667        }
13668    }
13669
13670    @Override
13671    public void clearPackagePreferredActivities(String packageName) {
13672        final int uid = Binder.getCallingUid();
13673        // writer
13674        synchronized (mPackages) {
13675            PackageParser.Package pkg = mPackages.get(packageName);
13676            if (pkg == null || pkg.applicationInfo.uid != uid) {
13677                if (mContext.checkCallingOrSelfPermission(
13678                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13679                        != PackageManager.PERMISSION_GRANTED) {
13680                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13681                            < Build.VERSION_CODES.FROYO) {
13682                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13683                                + Binder.getCallingUid());
13684                        return;
13685                    }
13686                    mContext.enforceCallingOrSelfPermission(
13687                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13688                }
13689            }
13690
13691            int user = UserHandle.getCallingUserId();
13692            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13693                scheduleWritePackageRestrictionsLocked(user);
13694            }
13695        }
13696    }
13697
13698    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13699    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13700        ArrayList<PreferredActivity> removed = null;
13701        boolean changed = false;
13702        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13703            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13704            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13705            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13706                continue;
13707            }
13708            Iterator<PreferredActivity> it = pir.filterIterator();
13709            while (it.hasNext()) {
13710                PreferredActivity pa = it.next();
13711                // Mark entry for removal only if it matches the package name
13712                // and the entry is of type "always".
13713                if (packageName == null ||
13714                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13715                                && pa.mPref.mAlways)) {
13716                    if (removed == null) {
13717                        removed = new ArrayList<PreferredActivity>();
13718                    }
13719                    removed.add(pa);
13720                }
13721            }
13722            if (removed != null) {
13723                for (int j=0; j<removed.size(); j++) {
13724                    PreferredActivity pa = removed.get(j);
13725                    pir.removeFilter(pa);
13726                }
13727                changed = true;
13728            }
13729        }
13730        return changed;
13731    }
13732
13733    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13734    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13735        if (userId == UserHandle.USER_ALL) {
13736            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13737                    sUserManager.getUserIds())) {
13738                for (int oneUserId : sUserManager.getUserIds()) {
13739                    scheduleWritePackageRestrictionsLocked(oneUserId);
13740                }
13741            }
13742        } else {
13743            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13744                scheduleWritePackageRestrictionsLocked(userId);
13745            }
13746        }
13747    }
13748
13749
13750    void clearDefaultBrowserIfNeeded(String packageName) {
13751        for (int oneUserId : sUserManager.getUserIds()) {
13752            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13753            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13754            if (packageName.equals(defaultBrowserPackageName)) {
13755                setDefaultBrowserPackageName(null, oneUserId);
13756            }
13757        }
13758    }
13759
13760    @Override
13761    public void resetPreferredActivities(int userId) {
13762        mContext.enforceCallingOrSelfPermission(
13763                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13764        // writer
13765        synchronized (mPackages) {
13766            clearPackagePreferredActivitiesLPw(null, userId);
13767            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13768            applyFactoryDefaultBrowserLPw(userId);
13769            primeDomainVerificationsLPw(userId);
13770
13771            scheduleWritePackageRestrictionsLocked(userId);
13772        }
13773    }
13774
13775    @Override
13776    public int getPreferredActivities(List<IntentFilter> outFilters,
13777            List<ComponentName> outActivities, String packageName) {
13778
13779        int num = 0;
13780        final int userId = UserHandle.getCallingUserId();
13781        // reader
13782        synchronized (mPackages) {
13783            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13784            if (pir != null) {
13785                final Iterator<PreferredActivity> it = pir.filterIterator();
13786                while (it.hasNext()) {
13787                    final PreferredActivity pa = it.next();
13788                    if (packageName == null
13789                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13790                                    && pa.mPref.mAlways)) {
13791                        if (outFilters != null) {
13792                            outFilters.add(new IntentFilter(pa));
13793                        }
13794                        if (outActivities != null) {
13795                            outActivities.add(pa.mPref.mComponent);
13796                        }
13797                    }
13798                }
13799            }
13800        }
13801
13802        return num;
13803    }
13804
13805    @Override
13806    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13807            int userId) {
13808        int callingUid = Binder.getCallingUid();
13809        if (callingUid != Process.SYSTEM_UID) {
13810            throw new SecurityException(
13811                    "addPersistentPreferredActivity can only be run by the system");
13812        }
13813        if (filter.countActions() == 0) {
13814            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13815            return;
13816        }
13817        synchronized (mPackages) {
13818            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13819                    " :");
13820            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13821            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13822                    new PersistentPreferredActivity(filter, activity));
13823            scheduleWritePackageRestrictionsLocked(userId);
13824        }
13825    }
13826
13827    @Override
13828    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13829        int callingUid = Binder.getCallingUid();
13830        if (callingUid != Process.SYSTEM_UID) {
13831            throw new SecurityException(
13832                    "clearPackagePersistentPreferredActivities can only be run by the system");
13833        }
13834        ArrayList<PersistentPreferredActivity> removed = null;
13835        boolean changed = false;
13836        synchronized (mPackages) {
13837            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13838                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13839                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13840                        .valueAt(i);
13841                if (userId != thisUserId) {
13842                    continue;
13843                }
13844                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13845                while (it.hasNext()) {
13846                    PersistentPreferredActivity ppa = it.next();
13847                    // Mark entry for removal only if it matches the package name.
13848                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13849                        if (removed == null) {
13850                            removed = new ArrayList<PersistentPreferredActivity>();
13851                        }
13852                        removed.add(ppa);
13853                    }
13854                }
13855                if (removed != null) {
13856                    for (int j=0; j<removed.size(); j++) {
13857                        PersistentPreferredActivity ppa = removed.get(j);
13858                        ppir.removeFilter(ppa);
13859                    }
13860                    changed = true;
13861                }
13862            }
13863
13864            if (changed) {
13865                scheduleWritePackageRestrictionsLocked(userId);
13866            }
13867        }
13868    }
13869
13870    /**
13871     * Common machinery for picking apart a restored XML blob and passing
13872     * it to a caller-supplied functor to be applied to the running system.
13873     */
13874    private void restoreFromXml(XmlPullParser parser, int userId,
13875            String expectedStartTag, BlobXmlRestorer functor)
13876            throws IOException, XmlPullParserException {
13877        int type;
13878        while ((type = parser.next()) != XmlPullParser.START_TAG
13879                && type != XmlPullParser.END_DOCUMENT) {
13880        }
13881        if (type != XmlPullParser.START_TAG) {
13882            // oops didn't find a start tag?!
13883            if (DEBUG_BACKUP) {
13884                Slog.e(TAG, "Didn't find start tag during restore");
13885            }
13886            return;
13887        }
13888
13889        // this is supposed to be TAG_PREFERRED_BACKUP
13890        if (!expectedStartTag.equals(parser.getName())) {
13891            if (DEBUG_BACKUP) {
13892                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13893            }
13894            return;
13895        }
13896
13897        // skip interfering stuff, then we're aligned with the backing implementation
13898        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13899        functor.apply(parser, userId);
13900    }
13901
13902    private interface BlobXmlRestorer {
13903        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13904    }
13905
13906    /**
13907     * Non-Binder method, support for the backup/restore mechanism: write the
13908     * full set of preferred activities in its canonical XML format.  Returns the
13909     * XML output as a byte array, or null if there is none.
13910     */
13911    @Override
13912    public byte[] getPreferredActivityBackup(int userId) {
13913        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13914            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13915        }
13916
13917        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13918        try {
13919            final XmlSerializer serializer = new FastXmlSerializer();
13920            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13921            serializer.startDocument(null, true);
13922            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13923
13924            synchronized (mPackages) {
13925                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13926            }
13927
13928            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13929            serializer.endDocument();
13930            serializer.flush();
13931        } catch (Exception e) {
13932            if (DEBUG_BACKUP) {
13933                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13934            }
13935            return null;
13936        }
13937
13938        return dataStream.toByteArray();
13939    }
13940
13941    @Override
13942    public void restorePreferredActivities(byte[] backup, int userId) {
13943        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13944            throw new SecurityException("Only the system may call restorePreferredActivities()");
13945        }
13946
13947        try {
13948            final XmlPullParser parser = Xml.newPullParser();
13949            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13950            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13951                    new BlobXmlRestorer() {
13952                        @Override
13953                        public void apply(XmlPullParser parser, int userId)
13954                                throws XmlPullParserException, IOException {
13955                            synchronized (mPackages) {
13956                                mSettings.readPreferredActivitiesLPw(parser, userId);
13957                            }
13958                        }
13959                    } );
13960        } catch (Exception e) {
13961            if (DEBUG_BACKUP) {
13962                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13963            }
13964        }
13965    }
13966
13967    /**
13968     * Non-Binder method, support for the backup/restore mechanism: write the
13969     * default browser (etc) settings in its canonical XML format.  Returns the default
13970     * browser XML representation as a byte array, or null if there is none.
13971     */
13972    @Override
13973    public byte[] getDefaultAppsBackup(int userId) {
13974        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13975            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13976        }
13977
13978        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13979        try {
13980            final XmlSerializer serializer = new FastXmlSerializer();
13981            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13982            serializer.startDocument(null, true);
13983            serializer.startTag(null, TAG_DEFAULT_APPS);
13984
13985            synchronized (mPackages) {
13986                mSettings.writeDefaultAppsLPr(serializer, userId);
13987            }
13988
13989            serializer.endTag(null, TAG_DEFAULT_APPS);
13990            serializer.endDocument();
13991            serializer.flush();
13992        } catch (Exception e) {
13993            if (DEBUG_BACKUP) {
13994                Slog.e(TAG, "Unable to write default apps for backup", e);
13995            }
13996            return null;
13997        }
13998
13999        return dataStream.toByteArray();
14000    }
14001
14002    @Override
14003    public void restoreDefaultApps(byte[] backup, int userId) {
14004        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14005            throw new SecurityException("Only the system may call restoreDefaultApps()");
14006        }
14007
14008        try {
14009            final XmlPullParser parser = Xml.newPullParser();
14010            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14011            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14012                    new BlobXmlRestorer() {
14013                        @Override
14014                        public void apply(XmlPullParser parser, int userId)
14015                                throws XmlPullParserException, IOException {
14016                            synchronized (mPackages) {
14017                                mSettings.readDefaultAppsLPw(parser, userId);
14018                            }
14019                        }
14020                    } );
14021        } catch (Exception e) {
14022            if (DEBUG_BACKUP) {
14023                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14024            }
14025        }
14026    }
14027
14028    @Override
14029    public byte[] getIntentFilterVerificationBackup(int userId) {
14030        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14031            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14032        }
14033
14034        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14035        try {
14036            final XmlSerializer serializer = new FastXmlSerializer();
14037            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14038            serializer.startDocument(null, true);
14039            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14040
14041            synchronized (mPackages) {
14042                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14043            }
14044
14045            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14046            serializer.endDocument();
14047            serializer.flush();
14048        } catch (Exception e) {
14049            if (DEBUG_BACKUP) {
14050                Slog.e(TAG, "Unable to write default apps for backup", e);
14051            }
14052            return null;
14053        }
14054
14055        return dataStream.toByteArray();
14056    }
14057
14058    @Override
14059    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14060        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14061            throw new SecurityException("Only the system may call restorePreferredActivities()");
14062        }
14063
14064        try {
14065            final XmlPullParser parser = Xml.newPullParser();
14066            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14067            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14068                    new BlobXmlRestorer() {
14069                        @Override
14070                        public void apply(XmlPullParser parser, int userId)
14071                                throws XmlPullParserException, IOException {
14072                            synchronized (mPackages) {
14073                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14074                                mSettings.writeLPr();
14075                            }
14076                        }
14077                    } );
14078        } catch (Exception e) {
14079            if (DEBUG_BACKUP) {
14080                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14081            }
14082        }
14083    }
14084
14085    @Override
14086    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14087            int sourceUserId, int targetUserId, int flags) {
14088        mContext.enforceCallingOrSelfPermission(
14089                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14090        int callingUid = Binder.getCallingUid();
14091        enforceOwnerRights(ownerPackage, callingUid);
14092        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14093        if (intentFilter.countActions() == 0) {
14094            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14095            return;
14096        }
14097        synchronized (mPackages) {
14098            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14099                    ownerPackage, targetUserId, flags);
14100            CrossProfileIntentResolver resolver =
14101                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14102            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14103            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14104            if (existing != null) {
14105                int size = existing.size();
14106                for (int i = 0; i < size; i++) {
14107                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14108                        return;
14109                    }
14110                }
14111            }
14112            resolver.addFilter(newFilter);
14113            scheduleWritePackageRestrictionsLocked(sourceUserId);
14114        }
14115    }
14116
14117    @Override
14118    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14119        mContext.enforceCallingOrSelfPermission(
14120                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14121        int callingUid = Binder.getCallingUid();
14122        enforceOwnerRights(ownerPackage, callingUid);
14123        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14124        synchronized (mPackages) {
14125            CrossProfileIntentResolver resolver =
14126                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14127            ArraySet<CrossProfileIntentFilter> set =
14128                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14129            for (CrossProfileIntentFilter filter : set) {
14130                if (filter.getOwnerPackage().equals(ownerPackage)) {
14131                    resolver.removeFilter(filter);
14132                }
14133            }
14134            scheduleWritePackageRestrictionsLocked(sourceUserId);
14135        }
14136    }
14137
14138    // Enforcing that callingUid is owning pkg on userId
14139    private void enforceOwnerRights(String pkg, int callingUid) {
14140        // The system owns everything.
14141        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14142            return;
14143        }
14144        int callingUserId = UserHandle.getUserId(callingUid);
14145        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14146        if (pi == null) {
14147            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14148                    + callingUserId);
14149        }
14150        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14151            throw new SecurityException("Calling uid " + callingUid
14152                    + " does not own package " + pkg);
14153        }
14154    }
14155
14156    @Override
14157    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14158        Intent intent = new Intent(Intent.ACTION_MAIN);
14159        intent.addCategory(Intent.CATEGORY_HOME);
14160
14161        final int callingUserId = UserHandle.getCallingUserId();
14162        List<ResolveInfo> list = queryIntentActivities(intent, null,
14163                PackageManager.GET_META_DATA, callingUserId);
14164        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14165                true, false, false, callingUserId);
14166
14167        allHomeCandidates.clear();
14168        if (list != null) {
14169            for (ResolveInfo ri : list) {
14170                allHomeCandidates.add(ri);
14171            }
14172        }
14173        return (preferred == null || preferred.activityInfo == null)
14174                ? null
14175                : new ComponentName(preferred.activityInfo.packageName,
14176                        preferred.activityInfo.name);
14177    }
14178
14179    @Override
14180    public void setApplicationEnabledSetting(String appPackageName,
14181            int newState, int flags, int userId, String callingPackage) {
14182        if (!sUserManager.exists(userId)) return;
14183        if (callingPackage == null) {
14184            callingPackage = Integer.toString(Binder.getCallingUid());
14185        }
14186        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14187    }
14188
14189    @Override
14190    public void setComponentEnabledSetting(ComponentName componentName,
14191            int newState, int flags, int userId) {
14192        if (!sUserManager.exists(userId)) return;
14193        setEnabledSetting(componentName.getPackageName(),
14194                componentName.getClassName(), newState, flags, userId, null);
14195    }
14196
14197    private void setEnabledSetting(final String packageName, String className, int newState,
14198            final int flags, int userId, String callingPackage) {
14199        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14200              || newState == COMPONENT_ENABLED_STATE_ENABLED
14201              || newState == COMPONENT_ENABLED_STATE_DISABLED
14202              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14203              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14204            throw new IllegalArgumentException("Invalid new component state: "
14205                    + newState);
14206        }
14207        PackageSetting pkgSetting;
14208        final int uid = Binder.getCallingUid();
14209        final int permission = mContext.checkCallingOrSelfPermission(
14210                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14211        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14212        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14213        boolean sendNow = false;
14214        boolean isApp = (className == null);
14215        String componentName = isApp ? packageName : className;
14216        int packageUid = -1;
14217        ArrayList<String> components;
14218
14219        // writer
14220        synchronized (mPackages) {
14221            pkgSetting = mSettings.mPackages.get(packageName);
14222            if (pkgSetting == null) {
14223                if (className == null) {
14224                    throw new IllegalArgumentException(
14225                            "Unknown package: " + packageName);
14226                }
14227                throw new IllegalArgumentException(
14228                        "Unknown component: " + packageName
14229                        + "/" + className);
14230            }
14231            // Allow root and verify that userId is not being specified by a different user
14232            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14233                throw new SecurityException(
14234                        "Permission Denial: attempt to change component state from pid="
14235                        + Binder.getCallingPid()
14236                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14237            }
14238            if (className == null) {
14239                // We're dealing with an application/package level state change
14240                if (pkgSetting.getEnabled(userId) == newState) {
14241                    // Nothing to do
14242                    return;
14243                }
14244                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14245                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14246                    // Don't care about who enables an app.
14247                    callingPackage = null;
14248                }
14249                pkgSetting.setEnabled(newState, userId, callingPackage);
14250                // pkgSetting.pkg.mSetEnabled = newState;
14251            } else {
14252                // We're dealing with a component level state change
14253                // First, verify that this is a valid class name.
14254                PackageParser.Package pkg = pkgSetting.pkg;
14255                if (pkg == null || !pkg.hasComponentClassName(className)) {
14256                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14257                        throw new IllegalArgumentException("Component class " + className
14258                                + " does not exist in " + packageName);
14259                    } else {
14260                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14261                                + className + " does not exist in " + packageName);
14262                    }
14263                }
14264                switch (newState) {
14265                case COMPONENT_ENABLED_STATE_ENABLED:
14266                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14267                        return;
14268                    }
14269                    break;
14270                case COMPONENT_ENABLED_STATE_DISABLED:
14271                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14272                        return;
14273                    }
14274                    break;
14275                case COMPONENT_ENABLED_STATE_DEFAULT:
14276                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14277                        return;
14278                    }
14279                    break;
14280                default:
14281                    Slog.e(TAG, "Invalid new component state: " + newState);
14282                    return;
14283                }
14284            }
14285            scheduleWritePackageRestrictionsLocked(userId);
14286            components = mPendingBroadcasts.get(userId, packageName);
14287            final boolean newPackage = components == null;
14288            if (newPackage) {
14289                components = new ArrayList<String>();
14290            }
14291            if (!components.contains(componentName)) {
14292                components.add(componentName);
14293            }
14294            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14295                sendNow = true;
14296                // Purge entry from pending broadcast list if another one exists already
14297                // since we are sending one right away.
14298                mPendingBroadcasts.remove(userId, packageName);
14299            } else {
14300                if (newPackage) {
14301                    mPendingBroadcasts.put(userId, packageName, components);
14302                }
14303                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14304                    // Schedule a message
14305                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14306                }
14307            }
14308        }
14309
14310        long callingId = Binder.clearCallingIdentity();
14311        try {
14312            if (sendNow) {
14313                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14314                sendPackageChangedBroadcast(packageName,
14315                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14316            }
14317        } finally {
14318            Binder.restoreCallingIdentity(callingId);
14319        }
14320    }
14321
14322    private void sendPackageChangedBroadcast(String packageName,
14323            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14324        if (DEBUG_INSTALL)
14325            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14326                    + componentNames);
14327        Bundle extras = new Bundle(4);
14328        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14329        String nameList[] = new String[componentNames.size()];
14330        componentNames.toArray(nameList);
14331        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14332        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14333        extras.putInt(Intent.EXTRA_UID, packageUid);
14334        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14335                new int[] {UserHandle.getUserId(packageUid)});
14336    }
14337
14338    @Override
14339    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14340        if (!sUserManager.exists(userId)) return;
14341        final int uid = Binder.getCallingUid();
14342        final int permission = mContext.checkCallingOrSelfPermission(
14343                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14344        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14345        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14346        // writer
14347        synchronized (mPackages) {
14348            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14349                    allowedByPermission, uid, userId)) {
14350                scheduleWritePackageRestrictionsLocked(userId);
14351            }
14352        }
14353    }
14354
14355    @Override
14356    public String getInstallerPackageName(String packageName) {
14357        // reader
14358        synchronized (mPackages) {
14359            return mSettings.getInstallerPackageNameLPr(packageName);
14360        }
14361    }
14362
14363    @Override
14364    public int getApplicationEnabledSetting(String packageName, int userId) {
14365        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14366        int uid = Binder.getCallingUid();
14367        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14368        // reader
14369        synchronized (mPackages) {
14370            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14371        }
14372    }
14373
14374    @Override
14375    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14376        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14377        int uid = Binder.getCallingUid();
14378        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14379        // reader
14380        synchronized (mPackages) {
14381            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14382        }
14383    }
14384
14385    @Override
14386    public void enterSafeMode() {
14387        enforceSystemOrRoot("Only the system can request entering safe mode");
14388
14389        if (!mSystemReady) {
14390            mSafeMode = true;
14391        }
14392    }
14393
14394    @Override
14395    public void systemReady() {
14396        mSystemReady = true;
14397
14398        // Read the compatibilty setting when the system is ready.
14399        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14400                mContext.getContentResolver(),
14401                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14402        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14403        if (DEBUG_SETTINGS) {
14404            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14405        }
14406
14407        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14408
14409        synchronized (mPackages) {
14410            // Verify that all of the preferred activity components actually
14411            // exist.  It is possible for applications to be updated and at
14412            // that point remove a previously declared activity component that
14413            // had been set as a preferred activity.  We try to clean this up
14414            // the next time we encounter that preferred activity, but it is
14415            // possible for the user flow to never be able to return to that
14416            // situation so here we do a sanity check to make sure we haven't
14417            // left any junk around.
14418            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14419            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14420                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14421                removed.clear();
14422                for (PreferredActivity pa : pir.filterSet()) {
14423                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14424                        removed.add(pa);
14425                    }
14426                }
14427                if (removed.size() > 0) {
14428                    for (int r=0; r<removed.size(); r++) {
14429                        PreferredActivity pa = removed.get(r);
14430                        Slog.w(TAG, "Removing dangling preferred activity: "
14431                                + pa.mPref.mComponent);
14432                        pir.removeFilter(pa);
14433                    }
14434                    mSettings.writePackageRestrictionsLPr(
14435                            mSettings.mPreferredActivities.keyAt(i));
14436                }
14437            }
14438
14439            for (int userId : UserManagerService.getInstance().getUserIds()) {
14440                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14441                    grantPermissionsUserIds = ArrayUtils.appendInt(
14442                            grantPermissionsUserIds, userId);
14443                }
14444            }
14445        }
14446        sUserManager.systemReady();
14447
14448        // If we upgraded grant all default permissions before kicking off.
14449        for (int userId : grantPermissionsUserIds) {
14450            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14451        }
14452
14453        // Kick off any messages waiting for system ready
14454        if (mPostSystemReadyMessages != null) {
14455            for (Message msg : mPostSystemReadyMessages) {
14456                msg.sendToTarget();
14457            }
14458            mPostSystemReadyMessages = null;
14459        }
14460
14461        // Watch for external volumes that come and go over time
14462        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14463        storage.registerListener(mStorageListener);
14464
14465        mInstallerService.systemReady();
14466        mPackageDexOptimizer.systemReady();
14467    }
14468
14469    @Override
14470    public boolean isSafeMode() {
14471        return mSafeMode;
14472    }
14473
14474    @Override
14475    public boolean hasSystemUidErrors() {
14476        return mHasSystemUidErrors;
14477    }
14478
14479    static String arrayToString(int[] array) {
14480        StringBuffer buf = new StringBuffer(128);
14481        buf.append('[');
14482        if (array != null) {
14483            for (int i=0; i<array.length; i++) {
14484                if (i > 0) buf.append(", ");
14485                buf.append(array[i]);
14486            }
14487        }
14488        buf.append(']');
14489        return buf.toString();
14490    }
14491
14492    static class DumpState {
14493        public static final int DUMP_LIBS = 1 << 0;
14494        public static final int DUMP_FEATURES = 1 << 1;
14495        public static final int DUMP_RESOLVERS = 1 << 2;
14496        public static final int DUMP_PERMISSIONS = 1 << 3;
14497        public static final int DUMP_PACKAGES = 1 << 4;
14498        public static final int DUMP_SHARED_USERS = 1 << 5;
14499        public static final int DUMP_MESSAGES = 1 << 6;
14500        public static final int DUMP_PROVIDERS = 1 << 7;
14501        public static final int DUMP_VERIFIERS = 1 << 8;
14502        public static final int DUMP_PREFERRED = 1 << 9;
14503        public static final int DUMP_PREFERRED_XML = 1 << 10;
14504        public static final int DUMP_KEYSETS = 1 << 11;
14505        public static final int DUMP_VERSION = 1 << 12;
14506        public static final int DUMP_INSTALLS = 1 << 13;
14507        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14508        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14509
14510        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14511
14512        private int mTypes;
14513
14514        private int mOptions;
14515
14516        private boolean mTitlePrinted;
14517
14518        private SharedUserSetting mSharedUser;
14519
14520        public boolean isDumping(int type) {
14521            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14522                return true;
14523            }
14524
14525            return (mTypes & type) != 0;
14526        }
14527
14528        public void setDump(int type) {
14529            mTypes |= type;
14530        }
14531
14532        public boolean isOptionEnabled(int option) {
14533            return (mOptions & option) != 0;
14534        }
14535
14536        public void setOptionEnabled(int option) {
14537            mOptions |= option;
14538        }
14539
14540        public boolean onTitlePrinted() {
14541            final boolean printed = mTitlePrinted;
14542            mTitlePrinted = true;
14543            return printed;
14544        }
14545
14546        public boolean getTitlePrinted() {
14547            return mTitlePrinted;
14548        }
14549
14550        public void setTitlePrinted(boolean enabled) {
14551            mTitlePrinted = enabled;
14552        }
14553
14554        public SharedUserSetting getSharedUser() {
14555            return mSharedUser;
14556        }
14557
14558        public void setSharedUser(SharedUserSetting user) {
14559            mSharedUser = user;
14560        }
14561    }
14562
14563    @Override
14564    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14565        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14566                != PackageManager.PERMISSION_GRANTED) {
14567            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14568                    + Binder.getCallingPid()
14569                    + ", uid=" + Binder.getCallingUid()
14570                    + " without permission "
14571                    + android.Manifest.permission.DUMP);
14572            return;
14573        }
14574
14575        DumpState dumpState = new DumpState();
14576        boolean fullPreferred = false;
14577        boolean checkin = false;
14578
14579        String packageName = null;
14580        ArraySet<String> permissionNames = null;
14581
14582        int opti = 0;
14583        while (opti < args.length) {
14584            String opt = args[opti];
14585            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14586                break;
14587            }
14588            opti++;
14589
14590            if ("-a".equals(opt)) {
14591                // Right now we only know how to print all.
14592            } else if ("-h".equals(opt)) {
14593                pw.println("Package manager dump options:");
14594                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14595                pw.println("    --checkin: dump for a checkin");
14596                pw.println("    -f: print details of intent filters");
14597                pw.println("    -h: print this help");
14598                pw.println("  cmd may be one of:");
14599                pw.println("    l[ibraries]: list known shared libraries");
14600                pw.println("    f[ibraries]: list device features");
14601                pw.println("    k[eysets]: print known keysets");
14602                pw.println("    r[esolvers]: dump intent resolvers");
14603                pw.println("    perm[issions]: dump permissions");
14604                pw.println("    permission [name ...]: dump declaration and use of given permission");
14605                pw.println("    pref[erred]: print preferred package settings");
14606                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14607                pw.println("    prov[iders]: dump content providers");
14608                pw.println("    p[ackages]: dump installed packages");
14609                pw.println("    s[hared-users]: dump shared user IDs");
14610                pw.println("    m[essages]: print collected runtime messages");
14611                pw.println("    v[erifiers]: print package verifier info");
14612                pw.println("    version: print database version info");
14613                pw.println("    write: write current settings now");
14614                pw.println("    <package.name>: info about given package");
14615                pw.println("    installs: details about install sessions");
14616                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14617                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14618                return;
14619            } else if ("--checkin".equals(opt)) {
14620                checkin = true;
14621            } else if ("-f".equals(opt)) {
14622                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14623            } else {
14624                pw.println("Unknown argument: " + opt + "; use -h for help");
14625            }
14626        }
14627
14628        // Is the caller requesting to dump a particular piece of data?
14629        if (opti < args.length) {
14630            String cmd = args[opti];
14631            opti++;
14632            // Is this a package name?
14633            if ("android".equals(cmd) || cmd.contains(".")) {
14634                packageName = cmd;
14635                // When dumping a single package, we always dump all of its
14636                // filter information since the amount of data will be reasonable.
14637                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14638            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14639                dumpState.setDump(DumpState.DUMP_LIBS);
14640            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14641                dumpState.setDump(DumpState.DUMP_FEATURES);
14642            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14643                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14644            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14645                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14646            } else if ("permission".equals(cmd)) {
14647                if (opti >= args.length) {
14648                    pw.println("Error: permission requires permission name");
14649                    return;
14650                }
14651                permissionNames = new ArraySet<>();
14652                while (opti < args.length) {
14653                    permissionNames.add(args[opti]);
14654                    opti++;
14655                }
14656                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14657                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14658            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14659                dumpState.setDump(DumpState.DUMP_PREFERRED);
14660            } else if ("preferred-xml".equals(cmd)) {
14661                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14662                if (opti < args.length && "--full".equals(args[opti])) {
14663                    fullPreferred = true;
14664                    opti++;
14665                }
14666            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14667                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14668            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14669                dumpState.setDump(DumpState.DUMP_PACKAGES);
14670            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14671                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14672            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14673                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14674            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14675                dumpState.setDump(DumpState.DUMP_MESSAGES);
14676            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14677                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14678            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14679                    || "intent-filter-verifiers".equals(cmd)) {
14680                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14681            } else if ("version".equals(cmd)) {
14682                dumpState.setDump(DumpState.DUMP_VERSION);
14683            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14684                dumpState.setDump(DumpState.DUMP_KEYSETS);
14685            } else if ("installs".equals(cmd)) {
14686                dumpState.setDump(DumpState.DUMP_INSTALLS);
14687            } else if ("write".equals(cmd)) {
14688                synchronized (mPackages) {
14689                    mSettings.writeLPr();
14690                    pw.println("Settings written.");
14691                    return;
14692                }
14693            }
14694        }
14695
14696        if (checkin) {
14697            pw.println("vers,1");
14698        }
14699
14700        // reader
14701        synchronized (mPackages) {
14702            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14703                if (!checkin) {
14704                    if (dumpState.onTitlePrinted())
14705                        pw.println();
14706                    pw.println("Database versions:");
14707                    pw.print("  SDK Version:");
14708                    pw.print(" internal=");
14709                    pw.print(mSettings.mInternalSdkPlatform);
14710                    pw.print(" external=");
14711                    pw.println(mSettings.mExternalSdkPlatform);
14712                    pw.print("  DB Version:");
14713                    pw.print(" internal=");
14714                    pw.print(mSettings.mInternalDatabaseVersion);
14715                    pw.print(" external=");
14716                    pw.println(mSettings.mExternalDatabaseVersion);
14717                }
14718            }
14719
14720            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14721                if (!checkin) {
14722                    if (dumpState.onTitlePrinted())
14723                        pw.println();
14724                    pw.println("Verifiers:");
14725                    pw.print("  Required: ");
14726                    pw.print(mRequiredVerifierPackage);
14727                    pw.print(" (uid=");
14728                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14729                    pw.println(")");
14730                } else if (mRequiredVerifierPackage != null) {
14731                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14732                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14733                }
14734            }
14735
14736            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14737                    packageName == null) {
14738                if (mIntentFilterVerifierComponent != null) {
14739                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14740                    if (!checkin) {
14741                        if (dumpState.onTitlePrinted())
14742                            pw.println();
14743                        pw.println("Intent Filter Verifier:");
14744                        pw.print("  Using: ");
14745                        pw.print(verifierPackageName);
14746                        pw.print(" (uid=");
14747                        pw.print(getPackageUid(verifierPackageName, 0));
14748                        pw.println(")");
14749                    } else if (verifierPackageName != null) {
14750                        pw.print("ifv,"); pw.print(verifierPackageName);
14751                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14752                    }
14753                } else {
14754                    pw.println();
14755                    pw.println("No Intent Filter Verifier available!");
14756                }
14757            }
14758
14759            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14760                boolean printedHeader = false;
14761                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14762                while (it.hasNext()) {
14763                    String name = it.next();
14764                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14765                    if (!checkin) {
14766                        if (!printedHeader) {
14767                            if (dumpState.onTitlePrinted())
14768                                pw.println();
14769                            pw.println("Libraries:");
14770                            printedHeader = true;
14771                        }
14772                        pw.print("  ");
14773                    } else {
14774                        pw.print("lib,");
14775                    }
14776                    pw.print(name);
14777                    if (!checkin) {
14778                        pw.print(" -> ");
14779                    }
14780                    if (ent.path != null) {
14781                        if (!checkin) {
14782                            pw.print("(jar) ");
14783                            pw.print(ent.path);
14784                        } else {
14785                            pw.print(",jar,");
14786                            pw.print(ent.path);
14787                        }
14788                    } else {
14789                        if (!checkin) {
14790                            pw.print("(apk) ");
14791                            pw.print(ent.apk);
14792                        } else {
14793                            pw.print(",apk,");
14794                            pw.print(ent.apk);
14795                        }
14796                    }
14797                    pw.println();
14798                }
14799            }
14800
14801            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14802                if (dumpState.onTitlePrinted())
14803                    pw.println();
14804                if (!checkin) {
14805                    pw.println("Features:");
14806                }
14807                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14808                while (it.hasNext()) {
14809                    String name = it.next();
14810                    if (!checkin) {
14811                        pw.print("  ");
14812                    } else {
14813                        pw.print("feat,");
14814                    }
14815                    pw.println(name);
14816                }
14817            }
14818
14819            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14820                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14821                        : "Activity Resolver Table:", "  ", packageName,
14822                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14823                    dumpState.setTitlePrinted(true);
14824                }
14825                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14826                        : "Receiver Resolver Table:", "  ", packageName,
14827                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14828                    dumpState.setTitlePrinted(true);
14829                }
14830                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14831                        : "Service Resolver Table:", "  ", packageName,
14832                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14833                    dumpState.setTitlePrinted(true);
14834                }
14835                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14836                        : "Provider Resolver Table:", "  ", packageName,
14837                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14838                    dumpState.setTitlePrinted(true);
14839                }
14840            }
14841
14842            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14843                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14844                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14845                    int user = mSettings.mPreferredActivities.keyAt(i);
14846                    if (pir.dump(pw,
14847                            dumpState.getTitlePrinted()
14848                                ? "\nPreferred Activities User " + user + ":"
14849                                : "Preferred Activities User " + user + ":", "  ",
14850                            packageName, true, false)) {
14851                        dumpState.setTitlePrinted(true);
14852                    }
14853                }
14854            }
14855
14856            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14857                pw.flush();
14858                FileOutputStream fout = new FileOutputStream(fd);
14859                BufferedOutputStream str = new BufferedOutputStream(fout);
14860                XmlSerializer serializer = new FastXmlSerializer();
14861                try {
14862                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14863                    serializer.startDocument(null, true);
14864                    serializer.setFeature(
14865                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14866                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14867                    serializer.endDocument();
14868                    serializer.flush();
14869                } catch (IllegalArgumentException e) {
14870                    pw.println("Failed writing: " + e);
14871                } catch (IllegalStateException e) {
14872                    pw.println("Failed writing: " + e);
14873                } catch (IOException e) {
14874                    pw.println("Failed writing: " + e);
14875                }
14876            }
14877
14878            if (!checkin
14879                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14880                    && packageName == null) {
14881                pw.println();
14882                int count = mSettings.mPackages.size();
14883                if (count == 0) {
14884                    pw.println("No applications!");
14885                    pw.println();
14886                } else {
14887                    final String prefix = "  ";
14888                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14889                    if (allPackageSettings.size() == 0) {
14890                        pw.println("No domain preferred apps!");
14891                        pw.println();
14892                    } else {
14893                        pw.println("App verification status:");
14894                        pw.println();
14895                        count = 0;
14896                        for (PackageSetting ps : allPackageSettings) {
14897                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14898                            if (ivi == null || ivi.getPackageName() == null) continue;
14899                            pw.println(prefix + "Package: " + ivi.getPackageName());
14900                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14901                            pw.println(prefix + "Status:  " + ivi.getStatusString());
14902                            pw.println();
14903                            count++;
14904                        }
14905                        if (count == 0) {
14906                            pw.println(prefix + "No app verification established.");
14907                            pw.println();
14908                        }
14909                        for (int userId : sUserManager.getUserIds()) {
14910                            pw.println("App linkages for user " + userId + ":");
14911                            pw.println();
14912                            count = 0;
14913                            for (PackageSetting ps : allPackageSettings) {
14914                                final long status = ps.getDomainVerificationStatusForUser(userId);
14915                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14916                                    continue;
14917                                }
14918                                pw.println(prefix + "Package: " + ps.name);
14919                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
14920                                String statusStr = IntentFilterVerificationInfo.
14921                                        getStatusStringFromValue(status);
14922                                pw.println(prefix + "Status:  " + statusStr);
14923                                pw.println();
14924                                count++;
14925                            }
14926                            if (count == 0) {
14927                                pw.println(prefix + "No configured app linkages.");
14928                                pw.println();
14929                            }
14930                        }
14931                    }
14932                }
14933            }
14934
14935            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14936                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14937                if (packageName == null && permissionNames == null) {
14938                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14939                        if (iperm == 0) {
14940                            if (dumpState.onTitlePrinted())
14941                                pw.println();
14942                            pw.println("AppOp Permissions:");
14943                        }
14944                        pw.print("  AppOp Permission ");
14945                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14946                        pw.println(":");
14947                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14948                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14949                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14950                        }
14951                    }
14952                }
14953            }
14954
14955            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14956                boolean printedSomething = false;
14957                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14958                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14959                        continue;
14960                    }
14961                    if (!printedSomething) {
14962                        if (dumpState.onTitlePrinted())
14963                            pw.println();
14964                        pw.println("Registered ContentProviders:");
14965                        printedSomething = true;
14966                    }
14967                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14968                    pw.print("    "); pw.println(p.toString());
14969                }
14970                printedSomething = false;
14971                for (Map.Entry<String, PackageParser.Provider> entry :
14972                        mProvidersByAuthority.entrySet()) {
14973                    PackageParser.Provider p = entry.getValue();
14974                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14975                        continue;
14976                    }
14977                    if (!printedSomething) {
14978                        if (dumpState.onTitlePrinted())
14979                            pw.println();
14980                        pw.println("ContentProvider Authorities:");
14981                        printedSomething = true;
14982                    }
14983                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14984                    pw.print("    "); pw.println(p.toString());
14985                    if (p.info != null && p.info.applicationInfo != null) {
14986                        final String appInfo = p.info.applicationInfo.toString();
14987                        pw.print("      applicationInfo="); pw.println(appInfo);
14988                    }
14989                }
14990            }
14991
14992            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14993                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14994            }
14995
14996            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14997                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
14998            }
14999
15000            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15001                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15002            }
15003
15004            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15005                // XXX should handle packageName != null by dumping only install data that
15006                // the given package is involved with.
15007                if (dumpState.onTitlePrinted()) pw.println();
15008                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15009            }
15010
15011            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15012                if (dumpState.onTitlePrinted()) pw.println();
15013                mSettings.dumpReadMessagesLPr(pw, dumpState);
15014
15015                pw.println();
15016                pw.println("Package warning messages:");
15017                BufferedReader in = null;
15018                String line = null;
15019                try {
15020                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15021                    while ((line = in.readLine()) != null) {
15022                        if (line.contains("ignored: updated version")) continue;
15023                        pw.println(line);
15024                    }
15025                } catch (IOException ignored) {
15026                } finally {
15027                    IoUtils.closeQuietly(in);
15028                }
15029            }
15030
15031            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15032                BufferedReader in = null;
15033                String line = null;
15034                try {
15035                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15036                    while ((line = in.readLine()) != null) {
15037                        if (line.contains("ignored: updated version")) continue;
15038                        pw.print("msg,");
15039                        pw.println(line);
15040                    }
15041                } catch (IOException ignored) {
15042                } finally {
15043                    IoUtils.closeQuietly(in);
15044                }
15045            }
15046        }
15047    }
15048
15049    private String dumpDomainString(String packageName) {
15050        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15051        List<IntentFilter> filters = getAllIntentFilters(packageName);
15052
15053        ArraySet<String> result = new ArraySet<>();
15054        if (iviList.size() > 0) {
15055            for (IntentFilterVerificationInfo ivi : iviList) {
15056                for (String host : ivi.getDomains()) {
15057                    result.add(host);
15058                }
15059            }
15060        }
15061        if (filters != null && filters.size() > 0) {
15062            for (IntentFilter filter : filters) {
15063                if (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15064                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)) {
15065                    result.addAll(filter.getHostsList());
15066                }
15067            }
15068        }
15069
15070        StringBuilder sb = new StringBuilder(result.size() * 16);
15071        for (String domain : result) {
15072            if (sb.length() > 0) sb.append(" ");
15073            sb.append(domain);
15074        }
15075        return sb.toString();
15076    }
15077
15078    // ------- apps on sdcard specific code -------
15079    static final boolean DEBUG_SD_INSTALL = false;
15080
15081    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15082
15083    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15084
15085    private boolean mMediaMounted = false;
15086
15087    static String getEncryptKey() {
15088        try {
15089            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15090                    SD_ENCRYPTION_KEYSTORE_NAME);
15091            if (sdEncKey == null) {
15092                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15093                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15094                if (sdEncKey == null) {
15095                    Slog.e(TAG, "Failed to create encryption keys");
15096                    return null;
15097                }
15098            }
15099            return sdEncKey;
15100        } catch (NoSuchAlgorithmException nsae) {
15101            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15102            return null;
15103        } catch (IOException ioe) {
15104            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15105            return null;
15106        }
15107    }
15108
15109    /*
15110     * Update media status on PackageManager.
15111     */
15112    @Override
15113    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15114        int callingUid = Binder.getCallingUid();
15115        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15116            throw new SecurityException("Media status can only be updated by the system");
15117        }
15118        // reader; this apparently protects mMediaMounted, but should probably
15119        // be a different lock in that case.
15120        synchronized (mPackages) {
15121            Log.i(TAG, "Updating external media status from "
15122                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15123                    + (mediaStatus ? "mounted" : "unmounted"));
15124            if (DEBUG_SD_INSTALL)
15125                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15126                        + ", mMediaMounted=" + mMediaMounted);
15127            if (mediaStatus == mMediaMounted) {
15128                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15129                        : 0, -1);
15130                mHandler.sendMessage(msg);
15131                return;
15132            }
15133            mMediaMounted = mediaStatus;
15134        }
15135        // Queue up an async operation since the package installation may take a
15136        // little while.
15137        mHandler.post(new Runnable() {
15138            public void run() {
15139                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15140            }
15141        });
15142    }
15143
15144    /**
15145     * Called by MountService when the initial ASECs to scan are available.
15146     * Should block until all the ASEC containers are finished being scanned.
15147     */
15148    public void scanAvailableAsecs() {
15149        updateExternalMediaStatusInner(true, false, false);
15150        if (mShouldRestoreconData) {
15151            SELinuxMMAC.setRestoreconDone();
15152            mShouldRestoreconData = false;
15153        }
15154    }
15155
15156    /*
15157     * Collect information of applications on external media, map them against
15158     * existing containers and update information based on current mount status.
15159     * Please note that we always have to report status if reportStatus has been
15160     * set to true especially when unloading packages.
15161     */
15162    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15163            boolean externalStorage) {
15164        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15165        int[] uidArr = EmptyArray.INT;
15166
15167        final String[] list = PackageHelper.getSecureContainerList();
15168        if (ArrayUtils.isEmpty(list)) {
15169            Log.i(TAG, "No secure containers found");
15170        } else {
15171            // Process list of secure containers and categorize them
15172            // as active or stale based on their package internal state.
15173
15174            // reader
15175            synchronized (mPackages) {
15176                for (String cid : list) {
15177                    // Leave stages untouched for now; installer service owns them
15178                    if (PackageInstallerService.isStageName(cid)) continue;
15179
15180                    if (DEBUG_SD_INSTALL)
15181                        Log.i(TAG, "Processing container " + cid);
15182                    String pkgName = getAsecPackageName(cid);
15183                    if (pkgName == null) {
15184                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15185                        continue;
15186                    }
15187                    if (DEBUG_SD_INSTALL)
15188                        Log.i(TAG, "Looking for pkg : " + pkgName);
15189
15190                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15191                    if (ps == null) {
15192                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15193                        continue;
15194                    }
15195
15196                    /*
15197                     * Skip packages that are not external if we're unmounting
15198                     * external storage.
15199                     */
15200                    if (externalStorage && !isMounted && !isExternal(ps)) {
15201                        continue;
15202                    }
15203
15204                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15205                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15206                    // The package status is changed only if the code path
15207                    // matches between settings and the container id.
15208                    if (ps.codePathString != null
15209                            && ps.codePathString.startsWith(args.getCodePath())) {
15210                        if (DEBUG_SD_INSTALL) {
15211                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15212                                    + " at code path: " + ps.codePathString);
15213                        }
15214
15215                        // We do have a valid package installed on sdcard
15216                        processCids.put(args, ps.codePathString);
15217                        final int uid = ps.appId;
15218                        if (uid != -1) {
15219                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15220                        }
15221                    } else {
15222                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15223                                + ps.codePathString);
15224                    }
15225                }
15226            }
15227
15228            Arrays.sort(uidArr);
15229        }
15230
15231        // Process packages with valid entries.
15232        if (isMounted) {
15233            if (DEBUG_SD_INSTALL)
15234                Log.i(TAG, "Loading packages");
15235            loadMediaPackages(processCids, uidArr);
15236            startCleaningPackages();
15237            mInstallerService.onSecureContainersAvailable();
15238        } else {
15239            if (DEBUG_SD_INSTALL)
15240                Log.i(TAG, "Unloading packages");
15241            unloadMediaPackages(processCids, uidArr, reportStatus);
15242        }
15243    }
15244
15245    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15246            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15247        final int size = infos.size();
15248        final String[] packageNames = new String[size];
15249        final int[] packageUids = new int[size];
15250        for (int i = 0; i < size; i++) {
15251            final ApplicationInfo info = infos.get(i);
15252            packageNames[i] = info.packageName;
15253            packageUids[i] = info.uid;
15254        }
15255        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15256                finishedReceiver);
15257    }
15258
15259    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15260            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15261        sendResourcesChangedBroadcast(mediaStatus, replacing,
15262                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15263    }
15264
15265    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15266            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15267        int size = pkgList.length;
15268        if (size > 0) {
15269            // Send broadcasts here
15270            Bundle extras = new Bundle();
15271            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15272            if (uidArr != null) {
15273                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15274            }
15275            if (replacing) {
15276                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15277            }
15278            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15279                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15280            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15281        }
15282    }
15283
15284   /*
15285     * Look at potentially valid container ids from processCids If package
15286     * information doesn't match the one on record or package scanning fails,
15287     * the cid is added to list of removeCids. We currently don't delete stale
15288     * containers.
15289     */
15290    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15291        ArrayList<String> pkgList = new ArrayList<String>();
15292        Set<AsecInstallArgs> keys = processCids.keySet();
15293
15294        for (AsecInstallArgs args : keys) {
15295            String codePath = processCids.get(args);
15296            if (DEBUG_SD_INSTALL)
15297                Log.i(TAG, "Loading container : " + args.cid);
15298            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15299            try {
15300                // Make sure there are no container errors first.
15301                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15302                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15303                            + " when installing from sdcard");
15304                    continue;
15305                }
15306                // Check code path here.
15307                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15308                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15309                            + " does not match one in settings " + codePath);
15310                    continue;
15311                }
15312                // Parse package
15313                int parseFlags = mDefParseFlags;
15314                if (args.isExternalAsec()) {
15315                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15316                }
15317                if (args.isFwdLocked()) {
15318                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15319                }
15320
15321                synchronized (mInstallLock) {
15322                    PackageParser.Package pkg = null;
15323                    try {
15324                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15325                    } catch (PackageManagerException e) {
15326                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15327                    }
15328                    // Scan the package
15329                    if (pkg != null) {
15330                        /*
15331                         * TODO why is the lock being held? doPostInstall is
15332                         * called in other places without the lock. This needs
15333                         * to be straightened out.
15334                         */
15335                        // writer
15336                        synchronized (mPackages) {
15337                            retCode = PackageManager.INSTALL_SUCCEEDED;
15338                            pkgList.add(pkg.packageName);
15339                            // Post process args
15340                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15341                                    pkg.applicationInfo.uid);
15342                        }
15343                    } else {
15344                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15345                    }
15346                }
15347
15348            } finally {
15349                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15350                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15351                }
15352            }
15353        }
15354        // writer
15355        synchronized (mPackages) {
15356            // If the platform SDK has changed since the last time we booted,
15357            // we need to re-grant app permission to catch any new ones that
15358            // appear. This is really a hack, and means that apps can in some
15359            // cases get permissions that the user didn't initially explicitly
15360            // allow... it would be nice to have some better way to handle
15361            // this situation.
15362            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15363            if (regrantPermissions)
15364                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15365                        + mSdkVersion + "; regranting permissions for external storage");
15366            mSettings.mExternalSdkPlatform = mSdkVersion;
15367
15368            // Make sure group IDs have been assigned, and any permission
15369            // changes in other apps are accounted for
15370            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15371                    | (regrantPermissions
15372                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15373                            : 0));
15374
15375            mSettings.updateExternalDatabaseVersion();
15376
15377            // can downgrade to reader
15378            // Persist settings
15379            mSettings.writeLPr();
15380        }
15381        // Send a broadcast to let everyone know we are done processing
15382        if (pkgList.size() > 0) {
15383            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15384        }
15385    }
15386
15387   /*
15388     * Utility method to unload a list of specified containers
15389     */
15390    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15391        // Just unmount all valid containers.
15392        for (AsecInstallArgs arg : cidArgs) {
15393            synchronized (mInstallLock) {
15394                arg.doPostDeleteLI(false);
15395           }
15396       }
15397   }
15398
15399    /*
15400     * Unload packages mounted on external media. This involves deleting package
15401     * data from internal structures, sending broadcasts about diabled packages,
15402     * gc'ing to free up references, unmounting all secure containers
15403     * corresponding to packages on external media, and posting a
15404     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15405     * that we always have to post this message if status has been requested no
15406     * matter what.
15407     */
15408    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15409            final boolean reportStatus) {
15410        if (DEBUG_SD_INSTALL)
15411            Log.i(TAG, "unloading media packages");
15412        ArrayList<String> pkgList = new ArrayList<String>();
15413        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15414        final Set<AsecInstallArgs> keys = processCids.keySet();
15415        for (AsecInstallArgs args : keys) {
15416            String pkgName = args.getPackageName();
15417            if (DEBUG_SD_INSTALL)
15418                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15419            // Delete package internally
15420            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15421            synchronized (mInstallLock) {
15422                boolean res = deletePackageLI(pkgName, null, false, null, null,
15423                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15424                if (res) {
15425                    pkgList.add(pkgName);
15426                } else {
15427                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15428                    failedList.add(args);
15429                }
15430            }
15431        }
15432
15433        // reader
15434        synchronized (mPackages) {
15435            // We didn't update the settings after removing each package;
15436            // write them now for all packages.
15437            mSettings.writeLPr();
15438        }
15439
15440        // We have to absolutely send UPDATED_MEDIA_STATUS only
15441        // after confirming that all the receivers processed the ordered
15442        // broadcast when packages get disabled, force a gc to clean things up.
15443        // and unload all the containers.
15444        if (pkgList.size() > 0) {
15445            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15446                    new IIntentReceiver.Stub() {
15447                public void performReceive(Intent intent, int resultCode, String data,
15448                        Bundle extras, boolean ordered, boolean sticky,
15449                        int sendingUser) throws RemoteException {
15450                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15451                            reportStatus ? 1 : 0, 1, keys);
15452                    mHandler.sendMessage(msg);
15453                }
15454            });
15455        } else {
15456            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15457                    keys);
15458            mHandler.sendMessage(msg);
15459        }
15460    }
15461
15462    private void loadPrivatePackages(VolumeInfo vol) {
15463        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15464        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15465        synchronized (mInstallLock) {
15466        synchronized (mPackages) {
15467            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15468            for (PackageSetting ps : packages) {
15469                final PackageParser.Package pkg;
15470                try {
15471                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15472                    loaded.add(pkg.applicationInfo);
15473                } catch (PackageManagerException e) {
15474                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15475                }
15476            }
15477
15478            // TODO: regrant any permissions that changed based since original install
15479
15480            mSettings.writeLPr();
15481        }
15482        }
15483
15484        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15485        sendResourcesChangedBroadcast(true, false, loaded, null);
15486    }
15487
15488    private void unloadPrivatePackages(VolumeInfo vol) {
15489        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15490        synchronized (mInstallLock) {
15491        synchronized (mPackages) {
15492            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15493            for (PackageSetting ps : packages) {
15494                if (ps.pkg == null) continue;
15495
15496                final ApplicationInfo info = ps.pkg.applicationInfo;
15497                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15498                if (deletePackageLI(ps.name, null, false, null, null,
15499                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15500                    unloaded.add(info);
15501                } else {
15502                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15503                }
15504            }
15505
15506            mSettings.writeLPr();
15507        }
15508        }
15509
15510        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15511        sendResourcesChangedBroadcast(false, false, unloaded, null);
15512    }
15513
15514    /**
15515     * Examine all users present on given mounted volume, and destroy data
15516     * belonging to users that are no longer valid, or whose user ID has been
15517     * recycled.
15518     */
15519    private void reconcileUsers(String volumeUuid) {
15520        final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
15521        if (ArrayUtils.isEmpty(files)) {
15522            Slog.d(TAG, "No users found on " + volumeUuid);
15523            return;
15524        }
15525
15526        for (File file : files) {
15527            if (!file.isDirectory()) continue;
15528
15529            final int userId;
15530            final UserInfo info;
15531            try {
15532                userId = Integer.parseInt(file.getName());
15533                info = sUserManager.getUserInfo(userId);
15534            } catch (NumberFormatException e) {
15535                Slog.w(TAG, "Invalid user directory " + file);
15536                continue;
15537            }
15538
15539            boolean destroyUser = false;
15540            if (info == null) {
15541                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15542                        + " because no matching user was found");
15543                destroyUser = true;
15544            } else {
15545                try {
15546                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15547                } catch (IOException e) {
15548                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15549                            + " because we failed to enforce serial number: " + e);
15550                    destroyUser = true;
15551                }
15552            }
15553
15554            if (destroyUser) {
15555                synchronized (mInstallLock) {
15556                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15557                }
15558            }
15559        }
15560
15561        final UserManager um = mContext.getSystemService(UserManager.class);
15562        for (UserInfo user : um.getUsers()) {
15563            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15564            if (userDir.exists()) continue;
15565
15566            try {
15567                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15568                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15569            } catch (IOException e) {
15570                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15571            }
15572        }
15573    }
15574
15575    /**
15576     * Examine all apps present on given mounted volume, and destroy apps that
15577     * aren't expected, either due to uninstallation or reinstallation on
15578     * another volume.
15579     */
15580    private void reconcileApps(String volumeUuid) {
15581        final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
15582        if (ArrayUtils.isEmpty(files)) {
15583            Slog.d(TAG, "No apps found on " + volumeUuid);
15584            return;
15585        }
15586
15587        for (File file : files) {
15588            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15589                    && !PackageInstallerService.isStageName(file.getName());
15590            if (!isPackage) {
15591                // Ignore entries which are not packages
15592                continue;
15593            }
15594
15595            boolean destroyApp = false;
15596            String packageName = null;
15597            try {
15598                final PackageLite pkg = PackageParser.parsePackageLite(file,
15599                        PackageParser.PARSE_MUST_BE_APK);
15600                packageName = pkg.packageName;
15601
15602                synchronized (mPackages) {
15603                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15604                    if (ps == null) {
15605                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15606                                + volumeUuid + " because we found no install record");
15607                        destroyApp = true;
15608                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15609                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15610                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15611                        destroyApp = true;
15612                    }
15613                }
15614
15615            } catch (PackageParserException e) {
15616                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15617                destroyApp = true;
15618            }
15619
15620            if (destroyApp) {
15621                synchronized (mInstallLock) {
15622                    if (packageName != null) {
15623                        removeDataDirsLI(volumeUuid, packageName);
15624                    }
15625                    if (file.isDirectory()) {
15626                        mInstaller.rmPackageDir(file.getAbsolutePath());
15627                    } else {
15628                        file.delete();
15629                    }
15630                }
15631            }
15632        }
15633    }
15634
15635    private void unfreezePackage(String packageName) {
15636        synchronized (mPackages) {
15637            final PackageSetting ps = mSettings.mPackages.get(packageName);
15638            if (ps != null) {
15639                ps.frozen = false;
15640            }
15641        }
15642    }
15643
15644    @Override
15645    public int movePackage(final String packageName, final String volumeUuid) {
15646        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15647
15648        final int moveId = mNextMoveId.getAndIncrement();
15649        try {
15650            movePackageInternal(packageName, volumeUuid, moveId);
15651        } catch (PackageManagerException e) {
15652            Slog.w(TAG, "Failed to move " + packageName, e);
15653            mMoveCallbacks.notifyStatusChanged(moveId,
15654                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15655        }
15656        return moveId;
15657    }
15658
15659    private void movePackageInternal(final String packageName, final String volumeUuid,
15660            final int moveId) throws PackageManagerException {
15661        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15662        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15663        final PackageManager pm = mContext.getPackageManager();
15664
15665        final boolean currentAsec;
15666        final String currentVolumeUuid;
15667        final File codeFile;
15668        final String installerPackageName;
15669        final String packageAbiOverride;
15670        final int appId;
15671        final String seinfo;
15672        final String label;
15673
15674        // reader
15675        synchronized (mPackages) {
15676            final PackageParser.Package pkg = mPackages.get(packageName);
15677            final PackageSetting ps = mSettings.mPackages.get(packageName);
15678            if (pkg == null || ps == null) {
15679                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15680            }
15681
15682            if (pkg.applicationInfo.isSystemApp()) {
15683                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15684                        "Cannot move system application");
15685            }
15686
15687            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15688                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15689                        "Package already moved to " + volumeUuid);
15690            }
15691
15692            final File probe = new File(pkg.codePath);
15693            final File probeOat = new File(probe, "oat");
15694            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15695                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15696                        "Move only supported for modern cluster style installs");
15697            }
15698
15699            if (ps.frozen) {
15700                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15701                        "Failed to move already frozen package");
15702            }
15703            ps.frozen = true;
15704
15705            currentAsec = pkg.applicationInfo.isForwardLocked()
15706                    || pkg.applicationInfo.isExternalAsec();
15707            currentVolumeUuid = ps.volumeUuid;
15708            codeFile = new File(pkg.codePath);
15709            installerPackageName = ps.installerPackageName;
15710            packageAbiOverride = ps.cpuAbiOverrideString;
15711            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15712            seinfo = pkg.applicationInfo.seinfo;
15713            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15714        }
15715
15716        // Now that we're guarded by frozen state, kill app during move
15717        killApplication(packageName, appId, "move pkg");
15718
15719        final Bundle extras = new Bundle();
15720        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15721        extras.putString(Intent.EXTRA_TITLE, label);
15722        mMoveCallbacks.notifyCreated(moveId, extras);
15723
15724        int installFlags;
15725        final boolean moveCompleteApp;
15726        final File measurePath;
15727
15728        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15729            installFlags = INSTALL_INTERNAL;
15730            moveCompleteApp = !currentAsec;
15731            measurePath = Environment.getDataAppDirectory(volumeUuid);
15732        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15733            installFlags = INSTALL_EXTERNAL;
15734            moveCompleteApp = false;
15735            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15736        } else {
15737            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15738            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15739                    || !volume.isMountedWritable()) {
15740                unfreezePackage(packageName);
15741                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15742                        "Move location not mounted private volume");
15743            }
15744
15745            Preconditions.checkState(!currentAsec);
15746
15747            installFlags = INSTALL_INTERNAL;
15748            moveCompleteApp = true;
15749            measurePath = Environment.getDataAppDirectory(volumeUuid);
15750        }
15751
15752        final PackageStats stats = new PackageStats(null, -1);
15753        synchronized (mInstaller) {
15754            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15755                unfreezePackage(packageName);
15756                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15757                        "Failed to measure package size");
15758            }
15759        }
15760
15761        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15762                + stats.dataSize);
15763
15764        final long startFreeBytes = measurePath.getFreeSpace();
15765        final long sizeBytes;
15766        if (moveCompleteApp) {
15767            sizeBytes = stats.codeSize + stats.dataSize;
15768        } else {
15769            sizeBytes = stats.codeSize;
15770        }
15771
15772        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15773            unfreezePackage(packageName);
15774            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15775                    "Not enough free space to move");
15776        }
15777
15778        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15779
15780        final CountDownLatch installedLatch = new CountDownLatch(1);
15781        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15782            @Override
15783            public void onUserActionRequired(Intent intent) throws RemoteException {
15784                throw new IllegalStateException();
15785            }
15786
15787            @Override
15788            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15789                    Bundle extras) throws RemoteException {
15790                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15791                        + PackageManager.installStatusToString(returnCode, msg));
15792
15793                installedLatch.countDown();
15794
15795                // Regardless of success or failure of the move operation,
15796                // always unfreeze the package
15797                unfreezePackage(packageName);
15798
15799                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15800                switch (status) {
15801                    case PackageInstaller.STATUS_SUCCESS:
15802                        mMoveCallbacks.notifyStatusChanged(moveId,
15803                                PackageManager.MOVE_SUCCEEDED);
15804                        break;
15805                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15806                        mMoveCallbacks.notifyStatusChanged(moveId,
15807                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15808                        break;
15809                    default:
15810                        mMoveCallbacks.notifyStatusChanged(moveId,
15811                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15812                        break;
15813                }
15814            }
15815        };
15816
15817        final MoveInfo move;
15818        if (moveCompleteApp) {
15819            // Kick off a thread to report progress estimates
15820            new Thread() {
15821                @Override
15822                public void run() {
15823                    while (true) {
15824                        try {
15825                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15826                                break;
15827                            }
15828                        } catch (InterruptedException ignored) {
15829                        }
15830
15831                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15832                        final int progress = 10 + (int) MathUtils.constrain(
15833                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15834                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15835                    }
15836                }
15837            }.start();
15838
15839            final String dataAppName = codeFile.getName();
15840            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15841                    dataAppName, appId, seinfo);
15842        } else {
15843            move = null;
15844        }
15845
15846        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15847
15848        final Message msg = mHandler.obtainMessage(INIT_COPY);
15849        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15850        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15851                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15852        mHandler.sendMessage(msg);
15853    }
15854
15855    @Override
15856    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15857        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15858
15859        final int realMoveId = mNextMoveId.getAndIncrement();
15860        final Bundle extras = new Bundle();
15861        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15862        mMoveCallbacks.notifyCreated(realMoveId, extras);
15863
15864        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15865            @Override
15866            public void onCreated(int moveId, Bundle extras) {
15867                // Ignored
15868            }
15869
15870            @Override
15871            public void onStatusChanged(int moveId, int status, long estMillis) {
15872                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15873            }
15874        };
15875
15876        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15877        storage.setPrimaryStorageUuid(volumeUuid, callback);
15878        return realMoveId;
15879    }
15880
15881    @Override
15882    public int getMoveStatus(int moveId) {
15883        mContext.enforceCallingOrSelfPermission(
15884                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15885        return mMoveCallbacks.mLastStatus.get(moveId);
15886    }
15887
15888    @Override
15889    public void registerMoveCallback(IPackageMoveObserver callback) {
15890        mContext.enforceCallingOrSelfPermission(
15891                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15892        mMoveCallbacks.register(callback);
15893    }
15894
15895    @Override
15896    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15897        mContext.enforceCallingOrSelfPermission(
15898                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15899        mMoveCallbacks.unregister(callback);
15900    }
15901
15902    @Override
15903    public boolean setInstallLocation(int loc) {
15904        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15905                null);
15906        if (getInstallLocation() == loc) {
15907            return true;
15908        }
15909        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15910                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15911            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15912                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15913            return true;
15914        }
15915        return false;
15916   }
15917
15918    @Override
15919    public int getInstallLocation() {
15920        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15921                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15922                PackageHelper.APP_INSTALL_AUTO);
15923    }
15924
15925    /** Called by UserManagerService */
15926    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15927        mDirtyUsers.remove(userHandle);
15928        mSettings.removeUserLPw(userHandle);
15929        mPendingBroadcasts.remove(userHandle);
15930        if (mInstaller != null) {
15931            // Technically, we shouldn't be doing this with the package lock
15932            // held.  However, this is very rare, and there is already so much
15933            // other disk I/O going on, that we'll let it slide for now.
15934            final StorageManager storage = mContext.getSystemService(StorageManager.class);
15935            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
15936                final String volumeUuid = vol.getFsUuid();
15937                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15938                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15939            }
15940        }
15941        mUserNeedsBadging.delete(userHandle);
15942        removeUnusedPackagesLILPw(userManager, userHandle);
15943    }
15944
15945    /**
15946     * We're removing userHandle and would like to remove any downloaded packages
15947     * that are no longer in use by any other user.
15948     * @param userHandle the user being removed
15949     */
15950    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15951        final boolean DEBUG_CLEAN_APKS = false;
15952        int [] users = userManager.getUserIdsLPr();
15953        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15954        while (psit.hasNext()) {
15955            PackageSetting ps = psit.next();
15956            if (ps.pkg == null) {
15957                continue;
15958            }
15959            final String packageName = ps.pkg.packageName;
15960            // Skip over if system app
15961            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15962                continue;
15963            }
15964            if (DEBUG_CLEAN_APKS) {
15965                Slog.i(TAG, "Checking package " + packageName);
15966            }
15967            boolean keep = false;
15968            for (int i = 0; i < users.length; i++) {
15969                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15970                    keep = true;
15971                    if (DEBUG_CLEAN_APKS) {
15972                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15973                                + users[i]);
15974                    }
15975                    break;
15976                }
15977            }
15978            if (!keep) {
15979                if (DEBUG_CLEAN_APKS) {
15980                    Slog.i(TAG, "  Removing package " + packageName);
15981                }
15982                mHandler.post(new Runnable() {
15983                    public void run() {
15984                        deletePackageX(packageName, userHandle, 0);
15985                    } //end run
15986                });
15987            }
15988        }
15989    }
15990
15991    /** Called by UserManagerService */
15992    void createNewUserLILPw(int userHandle) {
15993        if (mInstaller != null) {
15994            mInstaller.createUserConfig(userHandle);
15995            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
15996            applyFactoryDefaultBrowserLPw(userHandle);
15997            primeDomainVerificationsLPw(userHandle);
15998        }
15999    }
16000
16001    void newUserCreated(final int userHandle) {
16002        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16003    }
16004
16005    @Override
16006    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16007        mContext.enforceCallingOrSelfPermission(
16008                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16009                "Only package verification agents can read the verifier device identity");
16010
16011        synchronized (mPackages) {
16012            return mSettings.getVerifierDeviceIdentityLPw();
16013        }
16014    }
16015
16016    @Override
16017    public void setPermissionEnforced(String permission, boolean enforced) {
16018        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
16019        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16020            synchronized (mPackages) {
16021                if (mSettings.mReadExternalStorageEnforced == null
16022                        || mSettings.mReadExternalStorageEnforced != enforced) {
16023                    mSettings.mReadExternalStorageEnforced = enforced;
16024                    mSettings.writeLPr();
16025                }
16026            }
16027            // kill any non-foreground processes so we restart them and
16028            // grant/revoke the GID.
16029            final IActivityManager am = ActivityManagerNative.getDefault();
16030            if (am != null) {
16031                final long token = Binder.clearCallingIdentity();
16032                try {
16033                    am.killProcessesBelowForeground("setPermissionEnforcement");
16034                } catch (RemoteException e) {
16035                } finally {
16036                    Binder.restoreCallingIdentity(token);
16037                }
16038            }
16039        } else {
16040            throw new IllegalArgumentException("No selective enforcement for " + permission);
16041        }
16042    }
16043
16044    @Override
16045    @Deprecated
16046    public boolean isPermissionEnforced(String permission) {
16047        return true;
16048    }
16049
16050    @Override
16051    public boolean isStorageLow() {
16052        final long token = Binder.clearCallingIdentity();
16053        try {
16054            final DeviceStorageMonitorInternal
16055                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16056            if (dsm != null) {
16057                return dsm.isMemoryLow();
16058            } else {
16059                return false;
16060            }
16061        } finally {
16062            Binder.restoreCallingIdentity(token);
16063        }
16064    }
16065
16066    @Override
16067    public IPackageInstaller getPackageInstaller() {
16068        return mInstallerService;
16069    }
16070
16071    private boolean userNeedsBadging(int userId) {
16072        int index = mUserNeedsBadging.indexOfKey(userId);
16073        if (index < 0) {
16074            final UserInfo userInfo;
16075            final long token = Binder.clearCallingIdentity();
16076            try {
16077                userInfo = sUserManager.getUserInfo(userId);
16078            } finally {
16079                Binder.restoreCallingIdentity(token);
16080            }
16081            final boolean b;
16082            if (userInfo != null && userInfo.isManagedProfile()) {
16083                b = true;
16084            } else {
16085                b = false;
16086            }
16087            mUserNeedsBadging.put(userId, b);
16088            return b;
16089        }
16090        return mUserNeedsBadging.valueAt(index);
16091    }
16092
16093    @Override
16094    public KeySet getKeySetByAlias(String packageName, String alias) {
16095        if (packageName == null || alias == null) {
16096            return null;
16097        }
16098        synchronized(mPackages) {
16099            final PackageParser.Package pkg = mPackages.get(packageName);
16100            if (pkg == null) {
16101                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16102                throw new IllegalArgumentException("Unknown package: " + packageName);
16103            }
16104            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16105            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16106        }
16107    }
16108
16109    @Override
16110    public KeySet getSigningKeySet(String packageName) {
16111        if (packageName == null) {
16112            return null;
16113        }
16114        synchronized(mPackages) {
16115            final PackageParser.Package pkg = mPackages.get(packageName);
16116            if (pkg == null) {
16117                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16118                throw new IllegalArgumentException("Unknown package: " + packageName);
16119            }
16120            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16121                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16122                throw new SecurityException("May not access signing KeySet of other apps.");
16123            }
16124            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16125            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16126        }
16127    }
16128
16129    @Override
16130    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16131        if (packageName == null || ks == null) {
16132            return false;
16133        }
16134        synchronized(mPackages) {
16135            final PackageParser.Package pkg = mPackages.get(packageName);
16136            if (pkg == null) {
16137                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16138                throw new IllegalArgumentException("Unknown package: " + packageName);
16139            }
16140            IBinder ksh = ks.getToken();
16141            if (ksh instanceof KeySetHandle) {
16142                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16143                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16144            }
16145            return false;
16146        }
16147    }
16148
16149    @Override
16150    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16151        if (packageName == null || ks == null) {
16152            return false;
16153        }
16154        synchronized(mPackages) {
16155            final PackageParser.Package pkg = mPackages.get(packageName);
16156            if (pkg == null) {
16157                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16158                throw new IllegalArgumentException("Unknown package: " + packageName);
16159            }
16160            IBinder ksh = ks.getToken();
16161            if (ksh instanceof KeySetHandle) {
16162                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16163                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16164            }
16165            return false;
16166        }
16167    }
16168
16169    public void getUsageStatsIfNoPackageUsageInfo() {
16170        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16171            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16172            if (usm == null) {
16173                throw new IllegalStateException("UsageStatsManager must be initialized");
16174            }
16175            long now = System.currentTimeMillis();
16176            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16177            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16178                String packageName = entry.getKey();
16179                PackageParser.Package pkg = mPackages.get(packageName);
16180                if (pkg == null) {
16181                    continue;
16182                }
16183                UsageStats usage = entry.getValue();
16184                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16185                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16186            }
16187        }
16188    }
16189
16190    /**
16191     * Check and throw if the given before/after packages would be considered a
16192     * downgrade.
16193     */
16194    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16195            throws PackageManagerException {
16196        if (after.versionCode < before.mVersionCode) {
16197            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16198                    "Update version code " + after.versionCode + " is older than current "
16199                    + before.mVersionCode);
16200        } else if (after.versionCode == before.mVersionCode) {
16201            if (after.baseRevisionCode < before.baseRevisionCode) {
16202                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16203                        "Update base revision code " + after.baseRevisionCode
16204                        + " is older than current " + before.baseRevisionCode);
16205            }
16206
16207            if (!ArrayUtils.isEmpty(after.splitNames)) {
16208                for (int i = 0; i < after.splitNames.length; i++) {
16209                    final String splitName = after.splitNames[i];
16210                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16211                    if (j != -1) {
16212                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16213                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16214                                    "Update split " + splitName + " revision code "
16215                                    + after.splitRevisionCodes[i] + " is older than current "
16216                                    + before.splitRevisionCodes[j]);
16217                        }
16218                    }
16219                }
16220            }
16221        }
16222    }
16223
16224    private static class MoveCallbacks extends Handler {
16225        private static final int MSG_CREATED = 1;
16226        private static final int MSG_STATUS_CHANGED = 2;
16227
16228        private final RemoteCallbackList<IPackageMoveObserver>
16229                mCallbacks = new RemoteCallbackList<>();
16230
16231        private final SparseIntArray mLastStatus = new SparseIntArray();
16232
16233        public MoveCallbacks(Looper looper) {
16234            super(looper);
16235        }
16236
16237        public void register(IPackageMoveObserver callback) {
16238            mCallbacks.register(callback);
16239        }
16240
16241        public void unregister(IPackageMoveObserver callback) {
16242            mCallbacks.unregister(callback);
16243        }
16244
16245        @Override
16246        public void handleMessage(Message msg) {
16247            final SomeArgs args = (SomeArgs) msg.obj;
16248            final int n = mCallbacks.beginBroadcast();
16249            for (int i = 0; i < n; i++) {
16250                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16251                try {
16252                    invokeCallback(callback, msg.what, args);
16253                } catch (RemoteException ignored) {
16254                }
16255            }
16256            mCallbacks.finishBroadcast();
16257            args.recycle();
16258        }
16259
16260        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16261                throws RemoteException {
16262            switch (what) {
16263                case MSG_CREATED: {
16264                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16265                    break;
16266                }
16267                case MSG_STATUS_CHANGED: {
16268                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16269                    break;
16270                }
16271            }
16272        }
16273
16274        private void notifyCreated(int moveId, Bundle extras) {
16275            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16276
16277            final SomeArgs args = SomeArgs.obtain();
16278            args.argi1 = moveId;
16279            args.arg2 = extras;
16280            obtainMessage(MSG_CREATED, args).sendToTarget();
16281        }
16282
16283        private void notifyStatusChanged(int moveId, int status) {
16284            notifyStatusChanged(moveId, status, -1);
16285        }
16286
16287        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16288            Slog.v(TAG, "Move " + moveId + " status " + status);
16289
16290            final SomeArgs args = SomeArgs.obtain();
16291            args.argi1 = moveId;
16292            args.argi2 = status;
16293            args.arg3 = estMillis;
16294            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16295
16296            synchronized (mLastStatus) {
16297                mLastStatus.put(moveId, status);
16298            }
16299        }
16300    }
16301
16302    private final class OnPermissionChangeListeners extends Handler {
16303        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16304
16305        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16306                new RemoteCallbackList<>();
16307
16308        public OnPermissionChangeListeners(Looper looper) {
16309            super(looper);
16310        }
16311
16312        @Override
16313        public void handleMessage(Message msg) {
16314            switch (msg.what) {
16315                case MSG_ON_PERMISSIONS_CHANGED: {
16316                    final int uid = msg.arg1;
16317                    handleOnPermissionsChanged(uid);
16318                } break;
16319            }
16320        }
16321
16322        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16323            mPermissionListeners.register(listener);
16324
16325        }
16326
16327        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16328            mPermissionListeners.unregister(listener);
16329        }
16330
16331        public void onPermissionsChanged(int uid) {
16332            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16333                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16334            }
16335        }
16336
16337        private void handleOnPermissionsChanged(int uid) {
16338            final int count = mPermissionListeners.beginBroadcast();
16339            try {
16340                for (int i = 0; i < count; i++) {
16341                    IOnPermissionsChangeListener callback = mPermissionListeners
16342                            .getBroadcastItem(i);
16343                    try {
16344                        callback.onPermissionsChanged(uid);
16345                    } catch (RemoteException e) {
16346                        Log.e(TAG, "Permission listener is dead", e);
16347                    }
16348                }
16349            } finally {
16350                mPermissionListeners.finishBroadcast();
16351            }
16352        }
16353    }
16354
16355    private class PackageManagerInternalImpl extends PackageManagerInternal {
16356        @Override
16357        public void setLocationPackagesProvider(PackagesProvider provider) {
16358            synchronized (mPackages) {
16359                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16360            }
16361        }
16362
16363        @Override
16364        public void setImePackagesProvider(PackagesProvider provider) {
16365            synchronized (mPackages) {
16366                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16367            }
16368        }
16369
16370        @Override
16371        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16372            synchronized (mPackages) {
16373                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16374            }
16375        }
16376
16377        @Override
16378        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16379            synchronized (mPackages) {
16380                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16381            }
16382        }
16383
16384        @Override
16385        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16386            synchronized (mPackages) {
16387                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16388            }
16389        }
16390
16391        @Override
16392        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16393            synchronized (mPackages) {
16394                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider);
16395            }
16396        }
16397
16398        @Override
16399        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16400            synchronized (mPackages) {
16401                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16402                        packageName, userId);
16403            }
16404        }
16405
16406        @Override
16407        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16408            synchronized (mPackages) {
16409                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16410                        packageName, userId);
16411            }
16412        }
16413    }
16414
16415    @Override
16416    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16417        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16418        synchronized (mPackages) {
16419            final long identity = Binder.clearCallingIdentity();
16420            try {
16421                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16422                        packageNames, userId);
16423            } finally {
16424                Binder.restoreCallingIdentity(identity);
16425            }
16426        }
16427    }
16428
16429    private static void enforceSystemOrPhoneCaller(String tag) {
16430        int callingUid = Binder.getCallingUid();
16431        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16432            throw new SecurityException(
16433                    "Cannot call " + tag + " from UID " + callingUid);
16434        }
16435    }
16436}
16437