PackageManagerService.java revision 28e7313992ba6efd94ddc16b45278863f84d7fcb
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.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
33import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
53import static android.content.pm.PackageManager.INSTALL_INTERNAL;
54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
59import static android.content.pm.PackageManager.MATCH_ALL;
60import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
61import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
62import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
63import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
64import static android.content.pm.PackageManager.PERMISSION_DENIED;
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.Debug;
147import android.os.Binder;
148import android.os.Build;
149import android.os.Bundle;
150import android.os.Environment;
151import android.os.Environment.UserEnvironment;
152import android.os.FileUtils;
153import android.os.Handler;
154import android.os.IBinder;
155import android.os.Looper;
156import android.os.Message;
157import android.os.Parcel;
158import android.os.ParcelFileDescriptor;
159import android.os.Process;
160import android.os.RemoteCallbackList;
161import android.os.RemoteException;
162import android.os.SELinux;
163import android.os.ServiceManager;
164import android.os.SystemClock;
165import android.os.SystemProperties;
166import android.os.UserHandle;
167import android.os.UserManager;
168import android.os.storage.IMountService;
169import android.os.storage.MountServiceInternal;
170import android.os.storage.StorageEventListener;
171import android.os.storage.StorageManager;
172import android.os.storage.VolumeInfo;
173import android.os.storage.VolumeRecord;
174import android.security.KeyStore;
175import android.security.SystemKeyStore;
176import android.system.ErrnoException;
177import android.system.Os;
178import android.system.StructStat;
179import android.text.TextUtils;
180import android.text.format.DateUtils;
181import android.util.ArrayMap;
182import android.util.ArraySet;
183import android.util.AtomicFile;
184import android.util.DisplayMetrics;
185import android.util.EventLog;
186import android.util.ExceptionUtils;
187import android.util.Log;
188import android.util.LogPrinter;
189import android.util.MathUtils;
190import android.util.PrintStreamPrinter;
191import android.util.Slog;
192import android.util.SparseArray;
193import android.util.SparseBooleanArray;
194import android.util.SparseIntArray;
195import android.util.Xml;
196import android.view.Display;
197
198import dalvik.system.DexFile;
199import dalvik.system.VMRuntime;
200
201import libcore.io.IoUtils;
202import libcore.util.EmptyArray;
203
204import com.android.internal.R;
205import com.android.internal.annotations.GuardedBy;
206import com.android.internal.app.IMediaContainerService;
207import com.android.internal.app.ResolverActivity;
208import com.android.internal.content.NativeLibraryHelper;
209import com.android.internal.content.PackageHelper;
210import com.android.internal.os.IParcelFileDescriptorFactory;
211import com.android.internal.os.SomeArgs;
212import com.android.internal.os.Zygote;
213import com.android.internal.util.ArrayUtils;
214import com.android.internal.util.FastPrintWriter;
215import com.android.internal.util.FastXmlSerializer;
216import com.android.internal.util.IndentingPrintWriter;
217import com.android.internal.util.Preconditions;
218import com.android.server.EventLogTags;
219import com.android.server.FgThread;
220import com.android.server.IntentResolver;
221import com.android.server.LocalServices;
222import com.android.server.ServiceThread;
223import com.android.server.SystemConfig;
224import com.android.server.Watchdog;
225import com.android.server.pm.PermissionsState.PermissionState;
226import com.android.server.pm.Settings.DatabaseVersion;
227import com.android.server.storage.DeviceStorageMonitorInternal;
228
229import org.xmlpull.v1.XmlPullParser;
230import org.xmlpull.v1.XmlPullParserException;
231import org.xmlpull.v1.XmlSerializer;
232
233import java.io.BufferedInputStream;
234import java.io.BufferedOutputStream;
235import java.io.BufferedReader;
236import java.io.ByteArrayInputStream;
237import java.io.ByteArrayOutputStream;
238import java.io.File;
239import java.io.FileDescriptor;
240import java.io.FileNotFoundException;
241import java.io.FileOutputStream;
242import java.io.FileReader;
243import java.io.FilenameFilter;
244import java.io.IOException;
245import java.io.InputStream;
246import java.io.PrintWriter;
247import java.nio.charset.StandardCharsets;
248import java.security.NoSuchAlgorithmException;
249import java.security.PublicKey;
250import java.security.cert.CertificateEncodingException;
251import java.security.cert.CertificateException;
252import java.text.SimpleDateFormat;
253import java.util.ArrayList;
254import java.util.Arrays;
255import java.util.Collection;
256import java.util.Collections;
257import java.util.Comparator;
258import java.util.Date;
259import java.util.Iterator;
260import java.util.List;
261import java.util.Map;
262import java.util.Objects;
263import java.util.Set;
264import java.util.concurrent.CountDownLatch;
265import java.util.concurrent.TimeUnit;
266import java.util.concurrent.atomic.AtomicBoolean;
267import java.util.concurrent.atomic.AtomicInteger;
268import java.util.concurrent.atomic.AtomicLong;
269
270/**
271 * Keep track of all those .apks everywhere.
272 *
273 * This is very central to the platform's security; please run the unit
274 * tests whenever making modifications here:
275 *
276runtest -c android.content.pm.PackageManagerTests frameworks-core
277 *
278 * {@hide}
279 */
280public class PackageManagerService extends IPackageManager.Stub {
281    static final String TAG = "PackageManager";
282    static final boolean DEBUG_SETTINGS = false;
283    static final boolean DEBUG_PREFERRED = false;
284    static final boolean DEBUG_UPGRADE = false;
285    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
286    private static final boolean DEBUG_BACKUP = false;
287    private static final boolean DEBUG_INSTALL = false;
288    private static final boolean DEBUG_REMOVE = false;
289    private static final boolean DEBUG_BROADCASTS = false;
290    private static final boolean DEBUG_SHOW_INFO = false;
291    private static final boolean DEBUG_PACKAGE_INFO = false;
292    private static final boolean DEBUG_INTENT_MATCHING = false;
293    private static final boolean DEBUG_PACKAGE_SCANNING = false;
294    private static final boolean DEBUG_VERIFY = false;
295    private static final boolean DEBUG_DEXOPT = false;
296    private static final boolean DEBUG_ABI_SELECTION = false;
297
298    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
299
300    private static final int RADIO_UID = Process.PHONE_UID;
301    private static final int LOG_UID = Process.LOG_UID;
302    private static final int NFC_UID = Process.NFC_UID;
303    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
304    private static final int SHELL_UID = Process.SHELL_UID;
305
306    // Cap the size of permission trees that 3rd party apps can define
307    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
308
309    // Suffix used during package installation when copying/moving
310    // package apks to install directory.
311    private static final String INSTALL_PACKAGE_SUFFIX = "-";
312
313    static final int SCAN_NO_DEX = 1<<1;
314    static final int SCAN_FORCE_DEX = 1<<2;
315    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
316    static final int SCAN_NEW_INSTALL = 1<<4;
317    static final int SCAN_NO_PATHS = 1<<5;
318    static final int SCAN_UPDATE_TIME = 1<<6;
319    static final int SCAN_DEFER_DEX = 1<<7;
320    static final int SCAN_BOOTING = 1<<8;
321    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
322    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
323    static final int SCAN_REQUIRE_KNOWN = 1<<12;
324    static final int SCAN_MOVE = 1<<13;
325    static final int SCAN_INITIAL = 1<<14;
326
327    static final int REMOVE_CHATTY = 1<<16;
328
329    private static final int[] EMPTY_INT_ARRAY = new int[0];
330
331    /**
332     * Timeout (in milliseconds) after which the watchdog should declare that
333     * our handler thread is wedged.  The usual default for such things is one
334     * minute but we sometimes do very lengthy I/O operations on this thread,
335     * such as installing multi-gigabyte applications, so ours needs to be longer.
336     */
337    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
338
339    /**
340     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
341     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
342     * settings entry if available, otherwise we use the hardcoded default.  If it's been
343     * more than this long since the last fstrim, we force one during the boot sequence.
344     *
345     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
346     * one gets run at the next available charging+idle time.  This final mandatory
347     * no-fstrim check kicks in only of the other scheduling criteria is never met.
348     */
349    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
350
351    /**
352     * Whether verification is enabled by default.
353     */
354    private static final boolean DEFAULT_VERIFY_ENABLE = true;
355
356    /**
357     * The default maximum time to wait for the verification agent to return in
358     * milliseconds.
359     */
360    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
361
362    /**
363     * The default response for package verification timeout.
364     *
365     * This can be either PackageManager.VERIFICATION_ALLOW or
366     * PackageManager.VERIFICATION_REJECT.
367     */
368    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
369
370    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
371
372    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
373            DEFAULT_CONTAINER_PACKAGE,
374            "com.android.defcontainer.DefaultContainerService");
375
376    private static final String KILL_APP_REASON_GIDS_CHANGED =
377            "permission grant or revoke changed gids";
378
379    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
380            "permissions revoked";
381
382    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
383
384    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
385
386    /** Permission grant: not grant the permission. */
387    private static final int GRANT_DENIED = 1;
388
389    /** Permission grant: grant the permission as an install permission. */
390    private static final int GRANT_INSTALL = 2;
391
392    /** Permission grant: grant the permission as an install permission for a legacy app. */
393    private static final int GRANT_INSTALL_LEGACY = 3;
394
395    /** Permission grant: grant the permission as a runtime one. */
396    private static final int GRANT_RUNTIME = 4;
397
398    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
399    private static final int GRANT_UPGRADE = 5;
400
401    /** Canonical intent used to identify what counts as a "web browser" app */
402    private static final Intent sBrowserIntent;
403    static {
404        sBrowserIntent = new Intent();
405        sBrowserIntent.setAction(Intent.ACTION_VIEW);
406        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
407        sBrowserIntent.setData(Uri.parse("http:"));
408    }
409
410    final ServiceThread mHandlerThread;
411
412    final PackageHandler mHandler;
413
414    /**
415     * Messages for {@link #mHandler} that need to wait for system ready before
416     * being dispatched.
417     */
418    private ArrayList<Message> mPostSystemReadyMessages;
419
420    final int mSdkVersion = Build.VERSION.SDK_INT;
421
422    final Context mContext;
423    final boolean mFactoryTest;
424    final boolean mOnlyCore;
425    final boolean mLazyDexOpt;
426    final long mDexOptLRUThresholdInMills;
427    final DisplayMetrics mMetrics;
428    final int mDefParseFlags;
429    final String[] mSeparateProcesses;
430    final boolean mIsUpgrade;
431
432    // This is where all application persistent data goes.
433    final File mAppDataDir;
434
435    // This is where all application persistent data goes for secondary users.
436    final File mUserAppDataDir;
437
438    /** The location for ASEC container files on internal storage. */
439    final String mAsecInternalPath;
440
441    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
442    // LOCK HELD.  Can be called with mInstallLock held.
443    @GuardedBy("mInstallLock")
444    final Installer mInstaller;
445
446    /** Directory where installed third-party apps stored */
447    final File mAppInstallDir;
448
449    /**
450     * Directory to which applications installed internally have their
451     * 32 bit native libraries copied.
452     */
453    private File mAppLib32InstallDir;
454
455    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
456    // apps.
457    final File mDrmAppPrivateInstallDir;
458
459    // ----------------------------------------------------------------
460
461    // Lock for state used when installing and doing other long running
462    // operations.  Methods that must be called with this lock held have
463    // the suffix "LI".
464    final Object mInstallLock = new Object();
465
466    // ----------------------------------------------------------------
467
468    // Keys are String (package name), values are Package.  This also serves
469    // as the lock for the global state.  Methods that must be called with
470    // this lock held have the prefix "LP".
471    @GuardedBy("mPackages")
472    final ArrayMap<String, PackageParser.Package> mPackages =
473            new ArrayMap<String, PackageParser.Package>();
474
475    // Tracks available target package names -> overlay package paths.
476    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
477        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
478
479    /**
480     * Tracks new system packages [receiving in an OTA] that we expect to
481     * find updated user-installed versions. Keys are package name, values
482     * are package location.
483     */
484    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
485
486    final Settings mSettings;
487    boolean mRestoredSettings;
488
489    // System configuration read by SystemConfig.
490    final int[] mGlobalGids;
491    final SparseArray<ArraySet<String>> mSystemPermissions;
492    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
493
494    // If mac_permissions.xml was found for seinfo labeling.
495    boolean mFoundPolicyFile;
496
497    // If a recursive restorecon of /data/data/<pkg> is needed.
498    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
499
500    public static final class SharedLibraryEntry {
501        public final String path;
502        public final String apk;
503
504        SharedLibraryEntry(String _path, String _apk) {
505            path = _path;
506            apk = _apk;
507        }
508    }
509
510    // Currently known shared libraries.
511    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
512            new ArrayMap<String, SharedLibraryEntry>();
513
514    // All available activities, for your resolving pleasure.
515    final ActivityIntentResolver mActivities =
516            new ActivityIntentResolver();
517
518    // All available receivers, for your resolving pleasure.
519    final ActivityIntentResolver mReceivers =
520            new ActivityIntentResolver();
521
522    // All available services, for your resolving pleasure.
523    final ServiceIntentResolver mServices = new ServiceIntentResolver();
524
525    // All available providers, for your resolving pleasure.
526    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
527
528    // Mapping from provider base names (first directory in content URI codePath)
529    // to the provider information.
530    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
531            new ArrayMap<String, PackageParser.Provider>();
532
533    // Mapping from instrumentation class names to info about them.
534    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
535            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
536
537    // Mapping from permission names to info about them.
538    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
539            new ArrayMap<String, PackageParser.PermissionGroup>();
540
541    // Packages whose data we have transfered into another package, thus
542    // should no longer exist.
543    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
544
545    // Broadcast actions that are only available to the system.
546    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
547
548    /** List of packages waiting for verification. */
549    final SparseArray<PackageVerificationState> mPendingVerification
550            = new SparseArray<PackageVerificationState>();
551
552    /** Set of packages associated with each app op permission. */
553    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
554
555    final PackageInstallerService mInstallerService;
556
557    private final PackageDexOptimizer mPackageDexOptimizer;
558
559    private AtomicInteger mNextMoveId = new AtomicInteger();
560    private final MoveCallbacks mMoveCallbacks;
561
562    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
563
564    // Cache of users who need badging.
565    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
566
567    /** Token for keys in mPendingVerification. */
568    private int mPendingVerificationToken = 0;
569
570    volatile boolean mSystemReady;
571    volatile boolean mSafeMode;
572    volatile boolean mHasSystemUidErrors;
573
574    ApplicationInfo mAndroidApplication;
575    final ActivityInfo mResolveActivity = new ActivityInfo();
576    final ResolveInfo mResolveInfo = new ResolveInfo();
577    ComponentName mResolveComponentName;
578    PackageParser.Package mPlatformPackage;
579    ComponentName mCustomResolverComponentName;
580
581    boolean mResolverReplaced = false;
582
583    private final ComponentName mIntentFilterVerifierComponent;
584    private int mIntentFilterVerificationToken = 0;
585
586    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
587            = new SparseArray<IntentFilterVerificationState>();
588
589    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
590            new DefaultPermissionGrantPolicy(this);
591
592    private static class IFVerificationParams {
593        PackageParser.Package pkg;
594        boolean replacing;
595        int userId;
596        int verifierUid;
597
598        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
599                int _userId, int _verifierUid) {
600            pkg = _pkg;
601            replacing = _replacing;
602            userId = _userId;
603            replacing = _replacing;
604            verifierUid = _verifierUid;
605        }
606    }
607
608    private interface IntentFilterVerifier<T extends IntentFilter> {
609        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
610                                               T filter, String packageName);
611        void startVerifications(int userId);
612        void receiveVerificationResponse(int verificationId);
613    }
614
615    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
616        private Context mContext;
617        private ComponentName mIntentFilterVerifierComponent;
618        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
619
620        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
621            mContext = context;
622            mIntentFilterVerifierComponent = verifierComponent;
623        }
624
625        private String getDefaultScheme() {
626            return IntentFilter.SCHEME_HTTPS;
627        }
628
629        @Override
630        public void startVerifications(int userId) {
631            // Launch verifications requests
632            int count = mCurrentIntentFilterVerifications.size();
633            for (int n=0; n<count; n++) {
634                int verificationId = mCurrentIntentFilterVerifications.get(n);
635                final IntentFilterVerificationState ivs =
636                        mIntentFilterVerificationStates.get(verificationId);
637
638                String packageName = ivs.getPackageName();
639
640                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
641                final int filterCount = filters.size();
642                ArraySet<String> domainsSet = new ArraySet<>();
643                for (int m=0; m<filterCount; m++) {
644                    PackageParser.ActivityIntentInfo filter = filters.get(m);
645                    domainsSet.addAll(filter.getHostsList());
646                }
647                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
648                synchronized (mPackages) {
649                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
650                            packageName, domainsList) != null) {
651                        scheduleWriteSettingsLocked();
652                    }
653                }
654                sendVerificationRequest(userId, verificationId, ivs);
655            }
656            mCurrentIntentFilterVerifications.clear();
657        }
658
659        private void sendVerificationRequest(int userId, int verificationId,
660                IntentFilterVerificationState ivs) {
661
662            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
663            verificationIntent.putExtra(
664                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
665                    verificationId);
666            verificationIntent.putExtra(
667                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
668                    getDefaultScheme());
669            verificationIntent.putExtra(
670                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
671                    ivs.getHostsString());
672            verificationIntent.putExtra(
673                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
674                    ivs.getPackageName());
675            verificationIntent.setComponent(mIntentFilterVerifierComponent);
676            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
677
678            UserHandle user = new UserHandle(userId);
679            mContext.sendBroadcastAsUser(verificationIntent, user);
680            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
681                    "Sending IntentFilter verification broadcast");
682        }
683
684        public void receiveVerificationResponse(int verificationId) {
685            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
686
687            final boolean verified = ivs.isVerified();
688
689            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
690            final int count = filters.size();
691            if (DEBUG_DOMAIN_VERIFICATION) {
692                Slog.i(TAG, "Received verification response " + verificationId
693                        + " for " + count + " filters, verified=" + verified);
694            }
695            for (int n=0; n<count; n++) {
696                PackageParser.ActivityIntentInfo filter = filters.get(n);
697                filter.setVerified(verified);
698
699                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
700                        + " verified with result:" + verified + " and hosts:"
701                        + ivs.getHostsString());
702            }
703
704            mIntentFilterVerificationStates.remove(verificationId);
705
706            final String packageName = ivs.getPackageName();
707            IntentFilterVerificationInfo ivi = null;
708
709            synchronized (mPackages) {
710                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
711            }
712            if (ivi == null) {
713                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
714                        + verificationId + " packageName:" + packageName);
715                return;
716            }
717            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
718                    "Updating IntentFilterVerificationInfo for package " + packageName
719                            +" verificationId:" + verificationId);
720
721            synchronized (mPackages) {
722                if (verified) {
723                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
724                } else {
725                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
726                }
727                scheduleWriteSettingsLocked();
728
729                final int userId = ivs.getUserId();
730                if (userId != UserHandle.USER_ALL) {
731                    final int userStatus =
732                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
733
734                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
735                    boolean needUpdate = false;
736
737                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
738                    // already been set by the User thru the Disambiguation dialog
739                    switch (userStatus) {
740                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
741                            if (verified) {
742                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
743                            } else {
744                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
745                            }
746                            needUpdate = true;
747                            break;
748
749                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
750                            if (verified) {
751                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
752                                needUpdate = true;
753                            }
754                            break;
755
756                        default:
757                            // Nothing to do
758                    }
759
760                    if (needUpdate) {
761                        mSettings.updateIntentFilterVerificationStatusLPw(
762                                packageName, updatedStatus, userId);
763                        scheduleWritePackageRestrictionsLocked(userId);
764                    }
765                }
766            }
767        }
768
769        @Override
770        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
771                    ActivityIntentInfo filter, String packageName) {
772            if (!hasValidDomains(filter)) {
773                return false;
774            }
775            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
776            if (ivs == null) {
777                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
778                        packageName);
779            }
780            if (DEBUG_DOMAIN_VERIFICATION) {
781                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
782            }
783            ivs.addFilter(filter);
784            return true;
785        }
786
787        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
788                int userId, int verificationId, String packageName) {
789            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
790                    verifierUid, userId, packageName);
791            ivs.setPendingState();
792            synchronized (mPackages) {
793                mIntentFilterVerificationStates.append(verificationId, ivs);
794                mCurrentIntentFilterVerifications.add(verificationId);
795            }
796            return ivs;
797        }
798    }
799
800    private static boolean hasValidDomains(ActivityIntentInfo filter) {
801        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
802                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
803                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
804    }
805
806    private IntentFilterVerifier mIntentFilterVerifier;
807
808    // Set of pending broadcasts for aggregating enable/disable of components.
809    static class PendingPackageBroadcasts {
810        // for each user id, a map of <package name -> components within that package>
811        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
812
813        public PendingPackageBroadcasts() {
814            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
815        }
816
817        public ArrayList<String> get(int userId, String packageName) {
818            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
819            return packages.get(packageName);
820        }
821
822        public void put(int userId, String packageName, ArrayList<String> components) {
823            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
824            packages.put(packageName, components);
825        }
826
827        public void remove(int userId, String packageName) {
828            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
829            if (packages != null) {
830                packages.remove(packageName);
831            }
832        }
833
834        public void remove(int userId) {
835            mUidMap.remove(userId);
836        }
837
838        public int userIdCount() {
839            return mUidMap.size();
840        }
841
842        public int userIdAt(int n) {
843            return mUidMap.keyAt(n);
844        }
845
846        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
847            return mUidMap.get(userId);
848        }
849
850        public int size() {
851            // total number of pending broadcast entries across all userIds
852            int num = 0;
853            for (int i = 0; i< mUidMap.size(); i++) {
854                num += mUidMap.valueAt(i).size();
855            }
856            return num;
857        }
858
859        public void clear() {
860            mUidMap.clear();
861        }
862
863        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
864            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
865            if (map == null) {
866                map = new ArrayMap<String, ArrayList<String>>();
867                mUidMap.put(userId, map);
868            }
869            return map;
870        }
871    }
872    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
873
874    // Service Connection to remote media container service to copy
875    // package uri's from external media onto secure containers
876    // or internal storage.
877    private IMediaContainerService mContainerService = null;
878
879    static final int SEND_PENDING_BROADCAST = 1;
880    static final int MCS_BOUND = 3;
881    static final int END_COPY = 4;
882    static final int INIT_COPY = 5;
883    static final int MCS_UNBIND = 6;
884    static final int START_CLEANING_PACKAGE = 7;
885    static final int FIND_INSTALL_LOC = 8;
886    static final int POST_INSTALL = 9;
887    static final int MCS_RECONNECT = 10;
888    static final int MCS_GIVE_UP = 11;
889    static final int UPDATED_MEDIA_STATUS = 12;
890    static final int WRITE_SETTINGS = 13;
891    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
892    static final int PACKAGE_VERIFIED = 15;
893    static final int CHECK_PENDING_VERIFICATION = 16;
894    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
895    static final int INTENT_FILTER_VERIFIED = 18;
896
897    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
898
899    // Delay time in millisecs
900    static final int BROADCAST_DELAY = 10 * 1000;
901
902    static UserManagerService sUserManager;
903
904    // Stores a list of users whose package restrictions file needs to be updated
905    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
906
907    final private DefaultContainerConnection mDefContainerConn =
908            new DefaultContainerConnection();
909    class DefaultContainerConnection implements ServiceConnection {
910        public void onServiceConnected(ComponentName name, IBinder service) {
911            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
912            IMediaContainerService imcs =
913                IMediaContainerService.Stub.asInterface(service);
914            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
915        }
916
917        public void onServiceDisconnected(ComponentName name) {
918            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
919        }
920    }
921
922    // Recordkeeping of restore-after-install operations that are currently in flight
923    // between the Package Manager and the Backup Manager
924    class PostInstallData {
925        public InstallArgs args;
926        public PackageInstalledInfo res;
927
928        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
929            args = _a;
930            res = _r;
931        }
932    }
933
934    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
935    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
936
937    // XML tags for backup/restore of various bits of state
938    private static final String TAG_PREFERRED_BACKUP = "pa";
939    private static final String TAG_DEFAULT_APPS = "da";
940    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
941
942    final String mRequiredVerifierPackage;
943    final String mRequiredInstallerPackage;
944
945    private final PackageUsage mPackageUsage = new PackageUsage();
946
947    private class PackageUsage {
948        private static final int WRITE_INTERVAL
949            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
950
951        private final Object mFileLock = new Object();
952        private final AtomicLong mLastWritten = new AtomicLong(0);
953        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
954
955        private boolean mIsHistoricalPackageUsageAvailable = true;
956
957        boolean isHistoricalPackageUsageAvailable() {
958            return mIsHistoricalPackageUsageAvailable;
959        }
960
961        void write(boolean force) {
962            if (force) {
963                writeInternal();
964                return;
965            }
966            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
967                && !DEBUG_DEXOPT) {
968                return;
969            }
970            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
971                new Thread("PackageUsage_DiskWriter") {
972                    @Override
973                    public void run() {
974                        try {
975                            writeInternal();
976                        } finally {
977                            mBackgroundWriteRunning.set(false);
978                        }
979                    }
980                }.start();
981            }
982        }
983
984        private void writeInternal() {
985            synchronized (mPackages) {
986                synchronized (mFileLock) {
987                    AtomicFile file = getFile();
988                    FileOutputStream f = null;
989                    try {
990                        f = file.startWrite();
991                        BufferedOutputStream out = new BufferedOutputStream(f);
992                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
993                        StringBuilder sb = new StringBuilder();
994                        for (PackageParser.Package pkg : mPackages.values()) {
995                            if (pkg.mLastPackageUsageTimeInMills == 0) {
996                                continue;
997                            }
998                            sb.setLength(0);
999                            sb.append(pkg.packageName);
1000                            sb.append(' ');
1001                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1002                            sb.append('\n');
1003                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1004                        }
1005                        out.flush();
1006                        file.finishWrite(f);
1007                    } catch (IOException e) {
1008                        if (f != null) {
1009                            file.failWrite(f);
1010                        }
1011                        Log.e(TAG, "Failed to write package usage times", e);
1012                    }
1013                }
1014            }
1015            mLastWritten.set(SystemClock.elapsedRealtime());
1016        }
1017
1018        void readLP() {
1019            synchronized (mFileLock) {
1020                AtomicFile file = getFile();
1021                BufferedInputStream in = null;
1022                try {
1023                    in = new BufferedInputStream(file.openRead());
1024                    StringBuffer sb = new StringBuffer();
1025                    while (true) {
1026                        String packageName = readToken(in, sb, ' ');
1027                        if (packageName == null) {
1028                            break;
1029                        }
1030                        String timeInMillisString = readToken(in, sb, '\n');
1031                        if (timeInMillisString == null) {
1032                            throw new IOException("Failed to find last usage time for package "
1033                                                  + packageName);
1034                        }
1035                        PackageParser.Package pkg = mPackages.get(packageName);
1036                        if (pkg == null) {
1037                            continue;
1038                        }
1039                        long timeInMillis;
1040                        try {
1041                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1042                        } catch (NumberFormatException e) {
1043                            throw new IOException("Failed to parse " + timeInMillisString
1044                                                  + " as a long.", e);
1045                        }
1046                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1047                    }
1048                } catch (FileNotFoundException expected) {
1049                    mIsHistoricalPackageUsageAvailable = false;
1050                } catch (IOException e) {
1051                    Log.w(TAG, "Failed to read package usage times", e);
1052                } finally {
1053                    IoUtils.closeQuietly(in);
1054                }
1055            }
1056            mLastWritten.set(SystemClock.elapsedRealtime());
1057        }
1058
1059        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1060                throws IOException {
1061            sb.setLength(0);
1062            while (true) {
1063                int ch = in.read();
1064                if (ch == -1) {
1065                    if (sb.length() == 0) {
1066                        return null;
1067                    }
1068                    throw new IOException("Unexpected EOF");
1069                }
1070                if (ch == endOfToken) {
1071                    return sb.toString();
1072                }
1073                sb.append((char)ch);
1074            }
1075        }
1076
1077        private AtomicFile getFile() {
1078            File dataDir = Environment.getDataDirectory();
1079            File systemDir = new File(dataDir, "system");
1080            File fname = new File(systemDir, "package-usage.list");
1081            return new AtomicFile(fname);
1082        }
1083    }
1084
1085    class PackageHandler extends Handler {
1086        private boolean mBound = false;
1087        final ArrayList<HandlerParams> mPendingInstalls =
1088            new ArrayList<HandlerParams>();
1089
1090        private boolean connectToService() {
1091            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1092                    " DefaultContainerService");
1093            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1094            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1095            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1096                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1097                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1098                mBound = true;
1099                return true;
1100            }
1101            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1102            return false;
1103        }
1104
1105        private void disconnectService() {
1106            mContainerService = null;
1107            mBound = false;
1108            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1109            mContext.unbindService(mDefContainerConn);
1110            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1111        }
1112
1113        PackageHandler(Looper looper) {
1114            super(looper);
1115        }
1116
1117        public void handleMessage(Message msg) {
1118            try {
1119                doHandleMessage(msg);
1120            } finally {
1121                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1122            }
1123        }
1124
1125        void doHandleMessage(Message msg) {
1126            switch (msg.what) {
1127                case INIT_COPY: {
1128                    HandlerParams params = (HandlerParams) msg.obj;
1129                    int idx = mPendingInstalls.size();
1130                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1131                    // If a bind was already initiated we dont really
1132                    // need to do anything. The pending install
1133                    // will be processed later on.
1134                    if (!mBound) {
1135                        // If this is the only one pending we might
1136                        // have to bind to the service again.
1137                        if (!connectToService()) {
1138                            Slog.e(TAG, "Failed to bind to media container service");
1139                            params.serviceError();
1140                            return;
1141                        } else {
1142                            // Once we bind to the service, the first
1143                            // pending request will be processed.
1144                            mPendingInstalls.add(idx, params);
1145                        }
1146                    } else {
1147                        mPendingInstalls.add(idx, params);
1148                        // Already bound to the service. Just make
1149                        // sure we trigger off processing the first request.
1150                        if (idx == 0) {
1151                            mHandler.sendEmptyMessage(MCS_BOUND);
1152                        }
1153                    }
1154                    break;
1155                }
1156                case MCS_BOUND: {
1157                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1158                    if (msg.obj != null) {
1159                        mContainerService = (IMediaContainerService) msg.obj;
1160                    }
1161                    if (mContainerService == null) {
1162                        if (!mBound) {
1163                            // Something seriously wrong since we are not bound and we are not
1164                            // waiting for connection. Bail out.
1165                            Slog.e(TAG, "Cannot bind to media container service");
1166                            for (HandlerParams params : mPendingInstalls) {
1167                                // Indicate service bind error
1168                                params.serviceError();
1169                            }
1170                            mPendingInstalls.clear();
1171                        } else {
1172                            Slog.w(TAG, "Waiting to connect to media container service");
1173                        }
1174                    } else if (mPendingInstalls.size() > 0) {
1175                        HandlerParams params = mPendingInstalls.get(0);
1176                        if (params != null) {
1177                            if (params.startCopy()) {
1178                                // We are done...  look for more work or to
1179                                // go idle.
1180                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1181                                        "Checking for more work or unbind...");
1182                                // Delete pending install
1183                                if (mPendingInstalls.size() > 0) {
1184                                    mPendingInstalls.remove(0);
1185                                }
1186                                if (mPendingInstalls.size() == 0) {
1187                                    if (mBound) {
1188                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1189                                                "Posting delayed MCS_UNBIND");
1190                                        removeMessages(MCS_UNBIND);
1191                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1192                                        // Unbind after a little delay, to avoid
1193                                        // continual thrashing.
1194                                        sendMessageDelayed(ubmsg, 10000);
1195                                    }
1196                                } else {
1197                                    // There are more pending requests in queue.
1198                                    // Just post MCS_BOUND message to trigger processing
1199                                    // of next pending install.
1200                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1201                                            "Posting MCS_BOUND for next work");
1202                                    mHandler.sendEmptyMessage(MCS_BOUND);
1203                                }
1204                            }
1205                        }
1206                    } else {
1207                        // Should never happen ideally.
1208                        Slog.w(TAG, "Empty queue");
1209                    }
1210                    break;
1211                }
1212                case MCS_RECONNECT: {
1213                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1214                    if (mPendingInstalls.size() > 0) {
1215                        if (mBound) {
1216                            disconnectService();
1217                        }
1218                        if (!connectToService()) {
1219                            Slog.e(TAG, "Failed to bind to media container service");
1220                            for (HandlerParams params : mPendingInstalls) {
1221                                // Indicate service bind error
1222                                params.serviceError();
1223                            }
1224                            mPendingInstalls.clear();
1225                        }
1226                    }
1227                    break;
1228                }
1229                case MCS_UNBIND: {
1230                    // If there is no actual work left, then time to unbind.
1231                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1232
1233                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1234                        if (mBound) {
1235                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1236
1237                            disconnectService();
1238                        }
1239                    } else if (mPendingInstalls.size() > 0) {
1240                        // There are more pending requests in queue.
1241                        // Just post MCS_BOUND message to trigger processing
1242                        // of next pending install.
1243                        mHandler.sendEmptyMessage(MCS_BOUND);
1244                    }
1245
1246                    break;
1247                }
1248                case MCS_GIVE_UP: {
1249                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1250                    mPendingInstalls.remove(0);
1251                    break;
1252                }
1253                case SEND_PENDING_BROADCAST: {
1254                    String packages[];
1255                    ArrayList<String> components[];
1256                    int size = 0;
1257                    int uids[];
1258                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1259                    synchronized (mPackages) {
1260                        if (mPendingBroadcasts == null) {
1261                            return;
1262                        }
1263                        size = mPendingBroadcasts.size();
1264                        if (size <= 0) {
1265                            // Nothing to be done. Just return
1266                            return;
1267                        }
1268                        packages = new String[size];
1269                        components = new ArrayList[size];
1270                        uids = new int[size];
1271                        int i = 0;  // filling out the above arrays
1272
1273                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1274                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1275                            Iterator<Map.Entry<String, ArrayList<String>>> it
1276                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1277                                            .entrySet().iterator();
1278                            while (it.hasNext() && i < size) {
1279                                Map.Entry<String, ArrayList<String>> ent = it.next();
1280                                packages[i] = ent.getKey();
1281                                components[i] = ent.getValue();
1282                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1283                                uids[i] = (ps != null)
1284                                        ? UserHandle.getUid(packageUserId, ps.appId)
1285                                        : -1;
1286                                i++;
1287                            }
1288                        }
1289                        size = i;
1290                        mPendingBroadcasts.clear();
1291                    }
1292                    // Send broadcasts
1293                    for (int i = 0; i < size; i++) {
1294                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1295                    }
1296                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1297                    break;
1298                }
1299                case START_CLEANING_PACKAGE: {
1300                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1301                    final String packageName = (String)msg.obj;
1302                    final int userId = msg.arg1;
1303                    final boolean andCode = msg.arg2 != 0;
1304                    synchronized (mPackages) {
1305                        if (userId == UserHandle.USER_ALL) {
1306                            int[] users = sUserManager.getUserIds();
1307                            for (int user : users) {
1308                                mSettings.addPackageToCleanLPw(
1309                                        new PackageCleanItem(user, packageName, andCode));
1310                            }
1311                        } else {
1312                            mSettings.addPackageToCleanLPw(
1313                                    new PackageCleanItem(userId, packageName, andCode));
1314                        }
1315                    }
1316                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1317                    startCleaningPackages();
1318                } break;
1319                case POST_INSTALL: {
1320                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1321                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1322                    mRunningInstalls.delete(msg.arg1);
1323                    boolean deleteOld = false;
1324
1325                    if (data != null) {
1326                        InstallArgs args = data.args;
1327                        PackageInstalledInfo res = data.res;
1328
1329                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1330                            final String packageName = res.pkg.applicationInfo.packageName;
1331                            res.removedInfo.sendBroadcast(false, true, false);
1332                            Bundle extras = new Bundle(1);
1333                            extras.putInt(Intent.EXTRA_UID, res.uid);
1334
1335                            // Now that we successfully installed the package, grant runtime
1336                            // permissions if requested before broadcasting the install.
1337                            if ((args.installFlags
1338                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1339                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1340                                        args.installGrantPermissions);
1341                            }
1342
1343                            // Determine the set of users who are adding this
1344                            // package for the first time vs. those who are seeing
1345                            // an update.
1346                            int[] firstUsers;
1347                            int[] updateUsers = new int[0];
1348                            if (res.origUsers == null || res.origUsers.length == 0) {
1349                                firstUsers = res.newUsers;
1350                            } else {
1351                                firstUsers = new int[0];
1352                                for (int i=0; i<res.newUsers.length; i++) {
1353                                    int user = res.newUsers[i];
1354                                    boolean isNew = true;
1355                                    for (int j=0; j<res.origUsers.length; j++) {
1356                                        if (res.origUsers[j] == user) {
1357                                            isNew = false;
1358                                            break;
1359                                        }
1360                                    }
1361                                    if (isNew) {
1362                                        int[] newFirst = new int[firstUsers.length+1];
1363                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1364                                                firstUsers.length);
1365                                        newFirst[firstUsers.length] = user;
1366                                        firstUsers = newFirst;
1367                                    } else {
1368                                        int[] newUpdate = new int[updateUsers.length+1];
1369                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1370                                                updateUsers.length);
1371                                        newUpdate[updateUsers.length] = user;
1372                                        updateUsers = newUpdate;
1373                                    }
1374                                }
1375                            }
1376                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1377                                    packageName, extras, null, null, firstUsers);
1378                            final boolean update = res.removedInfo.removedPackage != null;
1379                            if (update) {
1380                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1381                            }
1382                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1383                                    packageName, extras, null, null, updateUsers);
1384                            if (update) {
1385                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1386                                        packageName, extras, null, null, updateUsers);
1387                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1388                                        null, null, packageName, null, updateUsers);
1389
1390                                // treat asec-hosted packages like removable media on upgrade
1391                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1392                                    if (DEBUG_INSTALL) {
1393                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1394                                                + " is ASEC-hosted -> AVAILABLE");
1395                                    }
1396                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1397                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1398                                    pkgList.add(packageName);
1399                                    sendResourcesChangedBroadcast(true, true,
1400                                            pkgList,uidArray, null);
1401                                }
1402                            }
1403                            if (res.removedInfo.args != null) {
1404                                // Remove the replaced package's older resources safely now
1405                                deleteOld = true;
1406                            }
1407
1408                            // If this app is a browser and it's newly-installed for some
1409                            // users, clear any default-browser state in those users
1410                            if (firstUsers.length > 0) {
1411                                // the app's nature doesn't depend on the user, so we can just
1412                                // check its browser nature in any user and generalize.
1413                                if (packageIsBrowser(packageName, firstUsers[0])) {
1414                                    synchronized (mPackages) {
1415                                        for (int userId : firstUsers) {
1416                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1417                                        }
1418                                    }
1419                                }
1420                            }
1421                            // Log current value of "unknown sources" setting
1422                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1423                                getUnknownSourcesSettings());
1424                        }
1425                        // Force a gc to clear up things
1426                        Runtime.getRuntime().gc();
1427                        // We delete after a gc for applications  on sdcard.
1428                        if (deleteOld) {
1429                            synchronized (mInstallLock) {
1430                                res.removedInfo.args.doPostDeleteLI(true);
1431                            }
1432                        }
1433                        if (args.observer != null) {
1434                            try {
1435                                Bundle extras = extrasForInstallResult(res);
1436                                args.observer.onPackageInstalled(res.name, res.returnCode,
1437                                        res.returnMsg, extras);
1438                            } catch (RemoteException e) {
1439                                Slog.i(TAG, "Observer no longer exists.");
1440                            }
1441                        }
1442                    } else {
1443                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1444                    }
1445                } break;
1446                case UPDATED_MEDIA_STATUS: {
1447                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1448                    boolean reportStatus = msg.arg1 == 1;
1449                    boolean doGc = msg.arg2 == 1;
1450                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1451                    if (doGc) {
1452                        // Force a gc to clear up stale containers.
1453                        Runtime.getRuntime().gc();
1454                    }
1455                    if (msg.obj != null) {
1456                        @SuppressWarnings("unchecked")
1457                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1458                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1459                        // Unload containers
1460                        unloadAllContainers(args);
1461                    }
1462                    if (reportStatus) {
1463                        try {
1464                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1465                            PackageHelper.getMountService().finishMediaUpdate();
1466                        } catch (RemoteException e) {
1467                            Log.e(TAG, "MountService not running?");
1468                        }
1469                    }
1470                } break;
1471                case WRITE_SETTINGS: {
1472                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1473                    synchronized (mPackages) {
1474                        removeMessages(WRITE_SETTINGS);
1475                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1476                        mSettings.writeLPr();
1477                        mDirtyUsers.clear();
1478                    }
1479                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1480                } break;
1481                case WRITE_PACKAGE_RESTRICTIONS: {
1482                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1483                    synchronized (mPackages) {
1484                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1485                        for (int userId : mDirtyUsers) {
1486                            mSettings.writePackageRestrictionsLPr(userId);
1487                        }
1488                        mDirtyUsers.clear();
1489                    }
1490                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1491                } break;
1492                case CHECK_PENDING_VERIFICATION: {
1493                    final int verificationId = msg.arg1;
1494                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1495
1496                    if ((state != null) && !state.timeoutExtended()) {
1497                        final InstallArgs args = state.getInstallArgs();
1498                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1499
1500                        Slog.i(TAG, "Verification timed out for " + originUri);
1501                        mPendingVerification.remove(verificationId);
1502
1503                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1504
1505                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1506                            Slog.i(TAG, "Continuing with installation of " + originUri);
1507                            state.setVerifierResponse(Binder.getCallingUid(),
1508                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1509                            broadcastPackageVerified(verificationId, originUri,
1510                                    PackageManager.VERIFICATION_ALLOW,
1511                                    state.getInstallArgs().getUser());
1512                            try {
1513                                ret = args.copyApk(mContainerService, true);
1514                            } catch (RemoteException e) {
1515                                Slog.e(TAG, "Could not contact the ContainerService");
1516                            }
1517                        } else {
1518                            broadcastPackageVerified(verificationId, originUri,
1519                                    PackageManager.VERIFICATION_REJECT,
1520                                    state.getInstallArgs().getUser());
1521                        }
1522
1523                        processPendingInstall(args, ret);
1524                        mHandler.sendEmptyMessage(MCS_UNBIND);
1525                    }
1526                    break;
1527                }
1528                case PACKAGE_VERIFIED: {
1529                    final int verificationId = msg.arg1;
1530
1531                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1532                    if (state == null) {
1533                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1534                        break;
1535                    }
1536
1537                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1538
1539                    state.setVerifierResponse(response.callerUid, response.code);
1540
1541                    if (state.isVerificationComplete()) {
1542                        mPendingVerification.remove(verificationId);
1543
1544                        final InstallArgs args = state.getInstallArgs();
1545                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1546
1547                        int ret;
1548                        if (state.isInstallAllowed()) {
1549                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1550                            broadcastPackageVerified(verificationId, originUri,
1551                                    response.code, state.getInstallArgs().getUser());
1552                            try {
1553                                ret = args.copyApk(mContainerService, true);
1554                            } catch (RemoteException e) {
1555                                Slog.e(TAG, "Could not contact the ContainerService");
1556                            }
1557                        } else {
1558                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1559                        }
1560
1561                        processPendingInstall(args, ret);
1562
1563                        mHandler.sendEmptyMessage(MCS_UNBIND);
1564                    }
1565
1566                    break;
1567                }
1568                case START_INTENT_FILTER_VERIFICATIONS: {
1569                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1570                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1571                            params.replacing, params.pkg);
1572                    break;
1573                }
1574                case INTENT_FILTER_VERIFIED: {
1575                    final int verificationId = msg.arg1;
1576
1577                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1578                            verificationId);
1579                    if (state == null) {
1580                        Slog.w(TAG, "Invalid IntentFilter verification token "
1581                                + verificationId + " received");
1582                        break;
1583                    }
1584
1585                    final int userId = state.getUserId();
1586
1587                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1588                            "Processing IntentFilter verification with token:"
1589                            + verificationId + " and userId:" + userId);
1590
1591                    final IntentFilterVerificationResponse response =
1592                            (IntentFilterVerificationResponse) msg.obj;
1593
1594                    state.setVerifierResponse(response.callerUid, response.code);
1595
1596                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1597                            "IntentFilter verification with token:" + verificationId
1598                            + " and userId:" + userId
1599                            + " is settings verifier response with response code:"
1600                            + response.code);
1601
1602                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1603                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1604                                + response.getFailedDomainsString());
1605                    }
1606
1607                    if (state.isVerificationComplete()) {
1608                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1609                    } else {
1610                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1611                                "IntentFilter verification with token:" + verificationId
1612                                + " was not said to be complete");
1613                    }
1614
1615                    break;
1616                }
1617            }
1618        }
1619    }
1620
1621    private StorageEventListener mStorageListener = new StorageEventListener() {
1622        @Override
1623        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1624            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1625                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1626                    final String volumeUuid = vol.getFsUuid();
1627
1628                    // Clean up any users or apps that were removed or recreated
1629                    // while this volume was missing
1630                    reconcileUsers(volumeUuid);
1631                    reconcileApps(volumeUuid);
1632
1633                    // Clean up any install sessions that expired or were
1634                    // cancelled while this volume was missing
1635                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1636
1637                    loadPrivatePackages(vol);
1638
1639                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1640                    unloadPrivatePackages(vol);
1641                }
1642            }
1643
1644            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1645                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1646                    updateExternalMediaStatus(true, false);
1647                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1648                    updateExternalMediaStatus(false, false);
1649                }
1650            }
1651        }
1652
1653        @Override
1654        public void onVolumeForgotten(String fsUuid) {
1655            // Remove any apps installed on the forgotten volume
1656            synchronized (mPackages) {
1657                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1658                for (PackageSetting ps : packages) {
1659                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1660                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1661                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1662                }
1663
1664                mSettings.writeLPr();
1665            }
1666        }
1667    };
1668
1669    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1670            String[] grantedPermissions) {
1671        if (userId >= UserHandle.USER_OWNER) {
1672            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1673        } else if (userId == UserHandle.USER_ALL) {
1674            final int[] userIds;
1675            synchronized (mPackages) {
1676                userIds = UserManagerService.getInstance().getUserIds();
1677            }
1678            for (int someUserId : userIds) {
1679                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1680            }
1681        }
1682
1683        // We could have touched GID membership, so flush out packages.list
1684        synchronized (mPackages) {
1685            mSettings.writePackageListLPr();
1686        }
1687    }
1688
1689    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1690            String[] grantedPermissions) {
1691        SettingBase sb = (SettingBase) pkg.mExtras;
1692        if (sb == null) {
1693            return;
1694        }
1695
1696        PermissionsState permissionsState = sb.getPermissionsState();
1697
1698        for (String permission : pkg.requestedPermissions) {
1699            BasePermission bp = mSettings.mPermissions.get(permission);
1700            if (bp != null && bp.isRuntime() && (grantedPermissions == null
1701                    || ArrayUtils.contains(grantedPermissions, permission))) {
1702                permissionsState.grantRuntimePermission(bp, userId);
1703            }
1704        }
1705    }
1706
1707    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1708        Bundle extras = null;
1709        switch (res.returnCode) {
1710            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1711                extras = new Bundle();
1712                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1713                        res.origPermission);
1714                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1715                        res.origPackage);
1716                break;
1717            }
1718            case PackageManager.INSTALL_SUCCEEDED: {
1719                extras = new Bundle();
1720                extras.putBoolean(Intent.EXTRA_REPLACING,
1721                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1722                break;
1723            }
1724        }
1725        return extras;
1726    }
1727
1728    void scheduleWriteSettingsLocked() {
1729        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1730            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1731        }
1732    }
1733
1734    void scheduleWritePackageRestrictionsLocked(int userId) {
1735        if (!sUserManager.exists(userId)) return;
1736        mDirtyUsers.add(userId);
1737        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1738            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1739        }
1740    }
1741
1742    public static PackageManagerService main(Context context, Installer installer,
1743            boolean factoryTest, boolean onlyCore) {
1744        PackageManagerService m = new PackageManagerService(context, installer,
1745                factoryTest, onlyCore);
1746        ServiceManager.addService("package", m);
1747        return m;
1748    }
1749
1750    static String[] splitString(String str, char sep) {
1751        int count = 1;
1752        int i = 0;
1753        while ((i=str.indexOf(sep, i)) >= 0) {
1754            count++;
1755            i++;
1756        }
1757
1758        String[] res = new String[count];
1759        i=0;
1760        count = 0;
1761        int lastI=0;
1762        while ((i=str.indexOf(sep, i)) >= 0) {
1763            res[count] = str.substring(lastI, i);
1764            count++;
1765            i++;
1766            lastI = i;
1767        }
1768        res[count] = str.substring(lastI, str.length());
1769        return res;
1770    }
1771
1772    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1773        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1774                Context.DISPLAY_SERVICE);
1775        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1776    }
1777
1778    public PackageManagerService(Context context, Installer installer,
1779            boolean factoryTest, boolean onlyCore) {
1780        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1781                SystemClock.uptimeMillis());
1782
1783        if (mSdkVersion <= 0) {
1784            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1785        }
1786
1787        mContext = context;
1788        mFactoryTest = factoryTest;
1789        mOnlyCore = onlyCore;
1790        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1791        mMetrics = new DisplayMetrics();
1792        mSettings = new Settings(mPackages);
1793        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1794                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1795        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1796                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1797        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1798                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1799        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1800                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1801        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1802                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1803        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1804                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1805
1806        // TODO: add a property to control this?
1807        long dexOptLRUThresholdInMinutes;
1808        if (mLazyDexOpt) {
1809            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1810        } else {
1811            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1812        }
1813        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1814
1815        String separateProcesses = SystemProperties.get("debug.separate_processes");
1816        if (separateProcesses != null && separateProcesses.length() > 0) {
1817            if ("*".equals(separateProcesses)) {
1818                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1819                mSeparateProcesses = null;
1820                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1821            } else {
1822                mDefParseFlags = 0;
1823                mSeparateProcesses = separateProcesses.split(",");
1824                Slog.w(TAG, "Running with debug.separate_processes: "
1825                        + separateProcesses);
1826            }
1827        } else {
1828            mDefParseFlags = 0;
1829            mSeparateProcesses = null;
1830        }
1831
1832        mInstaller = installer;
1833        mPackageDexOptimizer = new PackageDexOptimizer(this);
1834        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1835
1836        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1837                FgThread.get().getLooper());
1838
1839        getDefaultDisplayMetrics(context, mMetrics);
1840
1841        SystemConfig systemConfig = SystemConfig.getInstance();
1842        mGlobalGids = systemConfig.getGlobalGids();
1843        mSystemPermissions = systemConfig.getSystemPermissions();
1844        mAvailableFeatures = systemConfig.getAvailableFeatures();
1845
1846        synchronized (mInstallLock) {
1847        // writer
1848        synchronized (mPackages) {
1849            mHandlerThread = new ServiceThread(TAG,
1850                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1851            mHandlerThread.start();
1852            mHandler = new PackageHandler(mHandlerThread.getLooper());
1853            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1854
1855            File dataDir = Environment.getDataDirectory();
1856            mAppDataDir = new File(dataDir, "data");
1857            mAppInstallDir = new File(dataDir, "app");
1858            mAppLib32InstallDir = new File(dataDir, "app-lib");
1859            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1860            mUserAppDataDir = new File(dataDir, "user");
1861            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1862
1863            sUserManager = new UserManagerService(context, this,
1864                    mInstallLock, mPackages);
1865
1866            // Propagate permission configuration in to package manager.
1867            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1868                    = systemConfig.getPermissions();
1869            for (int i=0; i<permConfig.size(); i++) {
1870                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1871                BasePermission bp = mSettings.mPermissions.get(perm.name);
1872                if (bp == null) {
1873                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1874                    mSettings.mPermissions.put(perm.name, bp);
1875                }
1876                if (perm.gids != null) {
1877                    bp.setGids(perm.gids, perm.perUser);
1878                }
1879            }
1880
1881            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1882            for (int i=0; i<libConfig.size(); i++) {
1883                mSharedLibraries.put(libConfig.keyAt(i),
1884                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1885            }
1886
1887            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1888
1889            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1890                    mSdkVersion, mOnlyCore);
1891
1892            String customResolverActivity = Resources.getSystem().getString(
1893                    R.string.config_customResolverActivity);
1894            if (TextUtils.isEmpty(customResolverActivity)) {
1895                customResolverActivity = null;
1896            } else {
1897                mCustomResolverComponentName = ComponentName.unflattenFromString(
1898                        customResolverActivity);
1899            }
1900
1901            long startTime = SystemClock.uptimeMillis();
1902
1903            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1904                    startTime);
1905
1906            // Set flag to monitor and not change apk file paths when
1907            // scanning install directories.
1908            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1909
1910            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1911
1912            /**
1913             * Add everything in the in the boot class path to the
1914             * list of process files because dexopt will have been run
1915             * if necessary during zygote startup.
1916             */
1917            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1918            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1919
1920            if (bootClassPath != null) {
1921                String[] bootClassPathElements = splitString(bootClassPath, ':');
1922                for (String element : bootClassPathElements) {
1923                    alreadyDexOpted.add(element);
1924                }
1925            } else {
1926                Slog.w(TAG, "No BOOTCLASSPATH found!");
1927            }
1928
1929            if (systemServerClassPath != null) {
1930                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1931                for (String element : systemServerClassPathElements) {
1932                    alreadyDexOpted.add(element);
1933                }
1934            } else {
1935                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1936            }
1937
1938            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1939            final String[] dexCodeInstructionSets =
1940                    getDexCodeInstructionSets(
1941                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1942
1943            /**
1944             * Ensure all external libraries have had dexopt run on them.
1945             */
1946            if (mSharedLibraries.size() > 0) {
1947                // NOTE: For now, we're compiling these system "shared libraries"
1948                // (and framework jars) into all available architectures. It's possible
1949                // to compile them only when we come across an app that uses them (there's
1950                // already logic for that in scanPackageLI) but that adds some complexity.
1951                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1952                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1953                        final String lib = libEntry.path;
1954                        if (lib == null) {
1955                            continue;
1956                        }
1957
1958                        try {
1959                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1960                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1961                                alreadyDexOpted.add(lib);
1962                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1963                            }
1964                        } catch (FileNotFoundException e) {
1965                            Slog.w(TAG, "Library not found: " + lib);
1966                        } catch (IOException e) {
1967                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1968                                    + e.getMessage());
1969                        }
1970                    }
1971                }
1972            }
1973
1974            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1975
1976            // Gross hack for now: we know this file doesn't contain any
1977            // code, so don't dexopt it to avoid the resulting log spew.
1978            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1979
1980            // Gross hack for now: we know this file is only part of
1981            // the boot class path for art, so don't dexopt it to
1982            // avoid the resulting log spew.
1983            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1984
1985            /**
1986             * There are a number of commands implemented in Java, which
1987             * we currently need to do the dexopt on so that they can be
1988             * run from a non-root shell.
1989             */
1990            String[] frameworkFiles = frameworkDir.list();
1991            if (frameworkFiles != null) {
1992                // TODO: We could compile these only for the most preferred ABI. We should
1993                // first double check that the dex files for these commands are not referenced
1994                // by other system apps.
1995                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1996                    for (int i=0; i<frameworkFiles.length; i++) {
1997                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1998                        String path = libPath.getPath();
1999                        // Skip the file if we already did it.
2000                        if (alreadyDexOpted.contains(path)) {
2001                            continue;
2002                        }
2003                        // Skip the file if it is not a type we want to dexopt.
2004                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2005                            continue;
2006                        }
2007                        try {
2008                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2009                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2010                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2011                            }
2012                        } catch (FileNotFoundException e) {
2013                            Slog.w(TAG, "Jar not found: " + path);
2014                        } catch (IOException e) {
2015                            Slog.w(TAG, "Exception reading jar: " + path, e);
2016                        }
2017                    }
2018                }
2019            }
2020
2021            // Collect vendor overlay packages.
2022            // (Do this before scanning any apps.)
2023            // For security and version matching reason, only consider
2024            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2025            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2026            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2027                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2028
2029            // Find base frameworks (resource packages without code).
2030            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2031                    | PackageParser.PARSE_IS_SYSTEM_DIR
2032                    | PackageParser.PARSE_IS_PRIVILEGED,
2033                    scanFlags | SCAN_NO_DEX, 0);
2034
2035            // Collected privileged system packages.
2036            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2037            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2038                    | PackageParser.PARSE_IS_SYSTEM_DIR
2039                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2040
2041            // Collect ordinary system packages.
2042            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2043            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2044                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2045
2046            // Collect all vendor packages.
2047            File vendorAppDir = new File("/vendor/app");
2048            try {
2049                vendorAppDir = vendorAppDir.getCanonicalFile();
2050            } catch (IOException e) {
2051                // failed to look up canonical path, continue with original one
2052            }
2053            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2054                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2055
2056            // Collect all OEM packages.
2057            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2058            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2059                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2060
2061            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2062            mInstaller.moveFiles();
2063
2064            // Prune any system packages that no longer exist.
2065            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2066            if (!mOnlyCore) {
2067                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2068                while (psit.hasNext()) {
2069                    PackageSetting ps = psit.next();
2070
2071                    /*
2072                     * If this is not a system app, it can't be a
2073                     * disable system app.
2074                     */
2075                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2076                        continue;
2077                    }
2078
2079                    /*
2080                     * If the package is scanned, it's not erased.
2081                     */
2082                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2083                    if (scannedPkg != null) {
2084                        /*
2085                         * If the system app is both scanned and in the
2086                         * disabled packages list, then it must have been
2087                         * added via OTA. Remove it from the currently
2088                         * scanned package so the previously user-installed
2089                         * application can be scanned.
2090                         */
2091                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2092                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2093                                    + ps.name + "; removing system app.  Last known codePath="
2094                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2095                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2096                                    + scannedPkg.mVersionCode);
2097                            removePackageLI(ps, true);
2098                            mExpectingBetter.put(ps.name, ps.codePath);
2099                        }
2100
2101                        continue;
2102                    }
2103
2104                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2105                        psit.remove();
2106                        logCriticalInfo(Log.WARN, "System package " + ps.name
2107                                + " no longer exists; wiping its data");
2108                        removeDataDirsLI(null, ps.name);
2109                    } else {
2110                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2111                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2112                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2113                        }
2114                    }
2115                }
2116            }
2117
2118            //look for any incomplete package installations
2119            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2120            //clean up list
2121            for(int i = 0; i < deletePkgsList.size(); i++) {
2122                //clean up here
2123                cleanupInstallFailedPackage(deletePkgsList.get(i));
2124            }
2125            //delete tmp files
2126            deleteTempPackageFiles();
2127
2128            // Remove any shared userIDs that have no associated packages
2129            mSettings.pruneSharedUsersLPw();
2130
2131            if (!mOnlyCore) {
2132                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2133                        SystemClock.uptimeMillis());
2134                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2135
2136                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2137                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2138
2139                /**
2140                 * Remove disable package settings for any updated system
2141                 * apps that were removed via an OTA. If they're not a
2142                 * previously-updated app, remove them completely.
2143                 * Otherwise, just revoke their system-level permissions.
2144                 */
2145                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2146                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2147                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2148
2149                    String msg;
2150                    if (deletedPkg == null) {
2151                        msg = "Updated system package " + deletedAppName
2152                                + " no longer exists; wiping its data";
2153                        removeDataDirsLI(null, deletedAppName);
2154                    } else {
2155                        msg = "Updated system app + " + deletedAppName
2156                                + " no longer present; removing system privileges for "
2157                                + deletedAppName;
2158
2159                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2160
2161                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2162                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2163                    }
2164                    logCriticalInfo(Log.WARN, msg);
2165                }
2166
2167                /**
2168                 * Make sure all system apps that we expected to appear on
2169                 * the userdata partition actually showed up. If they never
2170                 * appeared, crawl back and revive the system version.
2171                 */
2172                for (int i = 0; i < mExpectingBetter.size(); i++) {
2173                    final String packageName = mExpectingBetter.keyAt(i);
2174                    if (!mPackages.containsKey(packageName)) {
2175                        final File scanFile = mExpectingBetter.valueAt(i);
2176
2177                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2178                                + " but never showed up; reverting to system");
2179
2180                        final int reparseFlags;
2181                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2182                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2183                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2184                                    | PackageParser.PARSE_IS_PRIVILEGED;
2185                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2186                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2187                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2188                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2189                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2190                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2191                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2192                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2193                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2194                        } else {
2195                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2196                            continue;
2197                        }
2198
2199                        mSettings.enableSystemPackageLPw(packageName);
2200
2201                        try {
2202                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2203                        } catch (PackageManagerException e) {
2204                            Slog.e(TAG, "Failed to parse original system package: "
2205                                    + e.getMessage());
2206                        }
2207                    }
2208                }
2209            }
2210            mExpectingBetter.clear();
2211
2212            // Now that we know all of the shared libraries, update all clients to have
2213            // the correct library paths.
2214            updateAllSharedLibrariesLPw();
2215
2216            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2217                // NOTE: We ignore potential failures here during a system scan (like
2218                // the rest of the commands above) because there's precious little we
2219                // can do about it. A settings error is reported, though.
2220                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2221                        false /* force dexopt */, false /* defer dexopt */);
2222            }
2223
2224            // Now that we know all the packages we are keeping,
2225            // read and update their last usage times.
2226            mPackageUsage.readLP();
2227
2228            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2229                    SystemClock.uptimeMillis());
2230            Slog.i(TAG, "Time to scan packages: "
2231                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2232                    + " seconds");
2233
2234            // If the platform SDK has changed since the last time we booted,
2235            // we need to re-grant app permission to catch any new ones that
2236            // appear.  This is really a hack, and means that apps can in some
2237            // cases get permissions that the user didn't initially explicitly
2238            // allow...  it would be nice to have some better way to handle
2239            // this situation.
2240            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2241                    != mSdkVersion;
2242            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2243                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2244                    + "; regranting permissions for internal storage");
2245            mSettings.mInternalSdkPlatform = mSdkVersion;
2246
2247            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2248                    | (regrantPermissions
2249                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2250                            : 0));
2251
2252            // If this is the first boot, and it is a normal boot, then
2253            // we need to initialize the default preferred apps.
2254            if (!mRestoredSettings && !onlyCore) {
2255                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2256                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2257                primeDomainVerificationsLPw(UserHandle.USER_OWNER);
2258            }
2259
2260            // If this is first boot after an OTA, and a normal boot, then
2261            // we need to clear code cache directories.
2262            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2263            if (mIsUpgrade && !onlyCore) {
2264                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2265                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2266                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2267                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2268                }
2269                mSettings.mFingerprint = Build.FINGERPRINT;
2270            }
2271
2272            checkDefaultBrowser();
2273
2274            // All the changes are done during package scanning.
2275            mSettings.updateInternalDatabaseVersion();
2276
2277            // can downgrade to reader
2278            mSettings.writeLPr();
2279
2280            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2281                    SystemClock.uptimeMillis());
2282
2283            mRequiredVerifierPackage = getRequiredVerifierLPr();
2284            mRequiredInstallerPackage = getRequiredInstallerLPr();
2285
2286            mInstallerService = new PackageInstallerService(context, this);
2287
2288            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2289            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2290                    mIntentFilterVerifierComponent);
2291
2292        } // synchronized (mPackages)
2293        } // synchronized (mInstallLock)
2294
2295        // Now after opening every single application zip, make sure they
2296        // are all flushed.  Not really needed, but keeps things nice and
2297        // tidy.
2298        Runtime.getRuntime().gc();
2299
2300        // Expose private service for system components to use.
2301        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2302    }
2303
2304    @Override
2305    public boolean isFirstBoot() {
2306        return !mRestoredSettings;
2307    }
2308
2309    @Override
2310    public boolean isOnlyCoreApps() {
2311        return mOnlyCore;
2312    }
2313
2314    @Override
2315    public boolean isUpgrade() {
2316        return mIsUpgrade;
2317    }
2318
2319    private String getRequiredVerifierLPr() {
2320        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2321        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2322                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2323
2324        String requiredVerifier = null;
2325
2326        final int N = receivers.size();
2327        for (int i = 0; i < N; i++) {
2328            final ResolveInfo info = receivers.get(i);
2329
2330            if (info.activityInfo == null) {
2331                continue;
2332            }
2333
2334            final String packageName = info.activityInfo.packageName;
2335
2336            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2337                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2338                continue;
2339            }
2340
2341            if (requiredVerifier != null) {
2342                throw new RuntimeException("There can be only one required verifier");
2343            }
2344
2345            requiredVerifier = packageName;
2346        }
2347
2348        return requiredVerifier;
2349    }
2350
2351    private String getRequiredInstallerLPr() {
2352        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2353        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2354        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2355
2356        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2357                PACKAGE_MIME_TYPE, 0, 0);
2358
2359        String requiredInstaller = null;
2360
2361        final int N = installers.size();
2362        for (int i = 0; i < N; i++) {
2363            final ResolveInfo info = installers.get(i);
2364            final String packageName = info.activityInfo.packageName;
2365
2366            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2367                continue;
2368            }
2369
2370            if (requiredInstaller != null) {
2371                throw new RuntimeException("There must be one required installer");
2372            }
2373
2374            requiredInstaller = packageName;
2375        }
2376
2377        if (requiredInstaller == null) {
2378            throw new RuntimeException("There must be one required installer");
2379        }
2380
2381        return requiredInstaller;
2382    }
2383
2384    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2385        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2386        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2387                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2388
2389        ComponentName verifierComponentName = null;
2390
2391        int priority = -1000;
2392        final int N = receivers.size();
2393        for (int i = 0; i < N; i++) {
2394            final ResolveInfo info = receivers.get(i);
2395
2396            if (info.activityInfo == null) {
2397                continue;
2398            }
2399
2400            final String packageName = info.activityInfo.packageName;
2401
2402            final PackageSetting ps = mSettings.mPackages.get(packageName);
2403            if (ps == null) {
2404                continue;
2405            }
2406
2407            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2408                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2409                continue;
2410            }
2411
2412            // Select the IntentFilterVerifier with the highest priority
2413            if (priority < info.priority) {
2414                priority = info.priority;
2415                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2416                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2417                        + verifierComponentName + " with priority: " + info.priority);
2418            }
2419        }
2420
2421        return verifierComponentName;
2422    }
2423
2424    private void primeDomainVerificationsLPw(int userId) {
2425        if (DEBUG_DOMAIN_VERIFICATION) {
2426            Slog.d(TAG, "Priming domain verifications in user " + userId);
2427        }
2428
2429        SystemConfig systemConfig = SystemConfig.getInstance();
2430        ArraySet<String> packages = systemConfig.getLinkedApps();
2431        ArraySet<String> domains = new ArraySet<String>();
2432
2433        for (String packageName : packages) {
2434            PackageParser.Package pkg = mPackages.get(packageName);
2435            if (pkg != null) {
2436                if (!pkg.isSystemApp()) {
2437                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2438                    continue;
2439                }
2440
2441                domains.clear();
2442                for (PackageParser.Activity a : pkg.activities) {
2443                    for (ActivityIntentInfo filter : a.intents) {
2444                        if (hasValidDomains(filter)) {
2445                            domains.addAll(filter.getHostsList());
2446                        }
2447                    }
2448                }
2449
2450                if (domains.size() > 0) {
2451                    if (DEBUG_DOMAIN_VERIFICATION) {
2452                        Slog.v(TAG, "      + " + packageName);
2453                    }
2454                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2455                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2456                    // and then 'always' in the per-user state actually used for intent resolution.
2457                    final IntentFilterVerificationInfo ivi;
2458                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2459                            new ArrayList<String>(domains));
2460                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2461                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2462                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2463                } else {
2464                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2465                            + "' does not handle web links");
2466                }
2467            } else {
2468                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2469            }
2470        }
2471
2472        scheduleWritePackageRestrictionsLocked(userId);
2473        scheduleWriteSettingsLocked();
2474    }
2475
2476    private void applyFactoryDefaultBrowserLPw(int userId) {
2477        // The default browser app's package name is stored in a string resource,
2478        // with a product-specific overlay used for vendor customization.
2479        String browserPkg = mContext.getResources().getString(
2480                com.android.internal.R.string.default_browser);
2481        if (!TextUtils.isEmpty(browserPkg)) {
2482            // non-empty string => required to be a known package
2483            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2484            if (ps == null) {
2485                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2486                browserPkg = null;
2487            } else {
2488                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2489            }
2490        }
2491
2492        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2493        // default.  If there's more than one, just leave everything alone.
2494        if (browserPkg == null) {
2495            calculateDefaultBrowserLPw(userId);
2496        }
2497    }
2498
2499    private void calculateDefaultBrowserLPw(int userId) {
2500        List<String> allBrowsers = resolveAllBrowserApps(userId);
2501        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2502        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2503    }
2504
2505    private List<String> resolveAllBrowserApps(int userId) {
2506        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2507        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2508                PackageManager.MATCH_ALL, userId);
2509
2510        final int count = list.size();
2511        List<String> result = new ArrayList<String>(count);
2512        for (int i=0; i<count; i++) {
2513            ResolveInfo info = list.get(i);
2514            if (info.activityInfo == null
2515                    || !info.handleAllWebDataURI
2516                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2517                    || result.contains(info.activityInfo.packageName)) {
2518                continue;
2519            }
2520            result.add(info.activityInfo.packageName);
2521        }
2522
2523        return result;
2524    }
2525
2526    private boolean packageIsBrowser(String packageName, int userId) {
2527        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2528                PackageManager.MATCH_ALL, userId);
2529        final int N = list.size();
2530        for (int i = 0; i < N; i++) {
2531            ResolveInfo info = list.get(i);
2532            if (packageName.equals(info.activityInfo.packageName)) {
2533                return true;
2534            }
2535        }
2536        return false;
2537    }
2538
2539    private void checkDefaultBrowser() {
2540        final int myUserId = UserHandle.myUserId();
2541        final String packageName = getDefaultBrowserPackageName(myUserId);
2542        if (packageName != null) {
2543            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2544            if (info == null) {
2545                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2546                synchronized (mPackages) {
2547                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2548                }
2549            }
2550        }
2551    }
2552
2553    @Override
2554    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2555            throws RemoteException {
2556        try {
2557            return super.onTransact(code, data, reply, flags);
2558        } catch (RuntimeException e) {
2559            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2560                Slog.wtf(TAG, "Package Manager Crash", e);
2561            }
2562            throw e;
2563        }
2564    }
2565
2566    void cleanupInstallFailedPackage(PackageSetting ps) {
2567        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2568
2569        removeDataDirsLI(ps.volumeUuid, ps.name);
2570        if (ps.codePath != null) {
2571            if (ps.codePath.isDirectory()) {
2572                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2573            } else {
2574                ps.codePath.delete();
2575            }
2576        }
2577        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2578            if (ps.resourcePath.isDirectory()) {
2579                FileUtils.deleteContents(ps.resourcePath);
2580            }
2581            ps.resourcePath.delete();
2582        }
2583        mSettings.removePackageLPw(ps.name);
2584    }
2585
2586    static int[] appendInts(int[] cur, int[] add) {
2587        if (add == null) return cur;
2588        if (cur == null) return add;
2589        final int N = add.length;
2590        for (int i=0; i<N; i++) {
2591            cur = appendInt(cur, add[i]);
2592        }
2593        return cur;
2594    }
2595
2596    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2597        if (!sUserManager.exists(userId)) return null;
2598        final PackageSetting ps = (PackageSetting) p.mExtras;
2599        if (ps == null) {
2600            return null;
2601        }
2602
2603        final PermissionsState permissionsState = ps.getPermissionsState();
2604
2605        final int[] gids = permissionsState.computeGids(userId);
2606        final Set<String> permissions = permissionsState.getPermissions(userId);
2607        final PackageUserState state = ps.readUserState(userId);
2608
2609        return PackageParser.generatePackageInfo(p, gids, flags,
2610                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2611    }
2612
2613    @Override
2614    public boolean isPackageFrozen(String packageName) {
2615        synchronized (mPackages) {
2616            final PackageSetting ps = mSettings.mPackages.get(packageName);
2617            if (ps != null) {
2618                return ps.frozen;
2619            }
2620        }
2621        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2622        return true;
2623    }
2624
2625    @Override
2626    public boolean isPackageAvailable(String packageName, int userId) {
2627        if (!sUserManager.exists(userId)) return false;
2628        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2629        synchronized (mPackages) {
2630            PackageParser.Package p = mPackages.get(packageName);
2631            if (p != null) {
2632                final PackageSetting ps = (PackageSetting) p.mExtras;
2633                if (ps != null) {
2634                    final PackageUserState state = ps.readUserState(userId);
2635                    if (state != null) {
2636                        return PackageParser.isAvailable(state);
2637                    }
2638                }
2639            }
2640        }
2641        return false;
2642    }
2643
2644    @Override
2645    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2646        if (!sUserManager.exists(userId)) return null;
2647        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2648        // reader
2649        synchronized (mPackages) {
2650            PackageParser.Package p = mPackages.get(packageName);
2651            if (DEBUG_PACKAGE_INFO)
2652                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2653            if (p != null) {
2654                return generatePackageInfo(p, flags, userId);
2655            }
2656            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2657                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2658            }
2659        }
2660        return null;
2661    }
2662
2663    @Override
2664    public String[] currentToCanonicalPackageNames(String[] names) {
2665        String[] out = new String[names.length];
2666        // reader
2667        synchronized (mPackages) {
2668            for (int i=names.length-1; i>=0; i--) {
2669                PackageSetting ps = mSettings.mPackages.get(names[i]);
2670                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2671            }
2672        }
2673        return out;
2674    }
2675
2676    @Override
2677    public String[] canonicalToCurrentPackageNames(String[] names) {
2678        String[] out = new String[names.length];
2679        // reader
2680        synchronized (mPackages) {
2681            for (int i=names.length-1; i>=0; i--) {
2682                String cur = mSettings.mRenamedPackages.get(names[i]);
2683                out[i] = cur != null ? cur : names[i];
2684            }
2685        }
2686        return out;
2687    }
2688
2689    @Override
2690    public int getPackageUid(String packageName, int userId) {
2691        if (!sUserManager.exists(userId)) return -1;
2692        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2693
2694        // reader
2695        synchronized (mPackages) {
2696            PackageParser.Package p = mPackages.get(packageName);
2697            if(p != null) {
2698                return UserHandle.getUid(userId, p.applicationInfo.uid);
2699            }
2700            PackageSetting ps = mSettings.mPackages.get(packageName);
2701            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2702                return -1;
2703            }
2704            p = ps.pkg;
2705            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2706        }
2707    }
2708
2709    @Override
2710    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2711        if (!sUserManager.exists(userId)) {
2712            return null;
2713        }
2714
2715        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2716                "getPackageGids");
2717
2718        // reader
2719        synchronized (mPackages) {
2720            PackageParser.Package p = mPackages.get(packageName);
2721            if (DEBUG_PACKAGE_INFO) {
2722                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2723            }
2724            if (p != null) {
2725                PackageSetting ps = (PackageSetting) p.mExtras;
2726                return ps.getPermissionsState().computeGids(userId);
2727            }
2728        }
2729
2730        return null;
2731    }
2732
2733    static PermissionInfo generatePermissionInfo(
2734            BasePermission bp, int flags) {
2735        if (bp.perm != null) {
2736            return PackageParser.generatePermissionInfo(bp.perm, flags);
2737        }
2738        PermissionInfo pi = new PermissionInfo();
2739        pi.name = bp.name;
2740        pi.packageName = bp.sourcePackage;
2741        pi.nonLocalizedLabel = bp.name;
2742        pi.protectionLevel = bp.protectionLevel;
2743        return pi;
2744    }
2745
2746    @Override
2747    public PermissionInfo getPermissionInfo(String name, int flags) {
2748        // reader
2749        synchronized (mPackages) {
2750            final BasePermission p = mSettings.mPermissions.get(name);
2751            if (p != null) {
2752                return generatePermissionInfo(p, flags);
2753            }
2754            return null;
2755        }
2756    }
2757
2758    @Override
2759    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2760        // reader
2761        synchronized (mPackages) {
2762            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2763            for (BasePermission p : mSettings.mPermissions.values()) {
2764                if (group == null) {
2765                    if (p.perm == null || p.perm.info.group == null) {
2766                        out.add(generatePermissionInfo(p, flags));
2767                    }
2768                } else {
2769                    if (p.perm != null && group.equals(p.perm.info.group)) {
2770                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2771                    }
2772                }
2773            }
2774
2775            if (out.size() > 0) {
2776                return out;
2777            }
2778            return mPermissionGroups.containsKey(group) ? out : null;
2779        }
2780    }
2781
2782    @Override
2783    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2784        // reader
2785        synchronized (mPackages) {
2786            return PackageParser.generatePermissionGroupInfo(
2787                    mPermissionGroups.get(name), flags);
2788        }
2789    }
2790
2791    @Override
2792    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2793        // reader
2794        synchronized (mPackages) {
2795            final int N = mPermissionGroups.size();
2796            ArrayList<PermissionGroupInfo> out
2797                    = new ArrayList<PermissionGroupInfo>(N);
2798            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2799                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2800            }
2801            return out;
2802        }
2803    }
2804
2805    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2806            int userId) {
2807        if (!sUserManager.exists(userId)) return null;
2808        PackageSetting ps = mSettings.mPackages.get(packageName);
2809        if (ps != null) {
2810            if (ps.pkg == null) {
2811                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2812                        flags, userId);
2813                if (pInfo != null) {
2814                    return pInfo.applicationInfo;
2815                }
2816                return null;
2817            }
2818            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2819                    ps.readUserState(userId), userId);
2820        }
2821        return null;
2822    }
2823
2824    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2825            int userId) {
2826        if (!sUserManager.exists(userId)) return null;
2827        PackageSetting ps = mSettings.mPackages.get(packageName);
2828        if (ps != null) {
2829            PackageParser.Package pkg = ps.pkg;
2830            if (pkg == null) {
2831                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2832                    return null;
2833                }
2834                // Only data remains, so we aren't worried about code paths
2835                pkg = new PackageParser.Package(packageName);
2836                pkg.applicationInfo.packageName = packageName;
2837                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2838                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2839                pkg.applicationInfo.dataDir = Environment
2840                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2841                        .getAbsolutePath();
2842                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2843                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2844            }
2845            return generatePackageInfo(pkg, flags, userId);
2846        }
2847        return null;
2848    }
2849
2850    @Override
2851    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2852        if (!sUserManager.exists(userId)) return null;
2853        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2854        // writer
2855        synchronized (mPackages) {
2856            PackageParser.Package p = mPackages.get(packageName);
2857            if (DEBUG_PACKAGE_INFO) Log.v(
2858                    TAG, "getApplicationInfo " + packageName
2859                    + ": " + p);
2860            if (p != null) {
2861                PackageSetting ps = mSettings.mPackages.get(packageName);
2862                if (ps == null) return null;
2863                // Note: isEnabledLP() does not apply here - always return info
2864                return PackageParser.generateApplicationInfo(
2865                        p, flags, ps.readUserState(userId), userId);
2866            }
2867            if ("android".equals(packageName)||"system".equals(packageName)) {
2868                return mAndroidApplication;
2869            }
2870            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2871                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2872            }
2873        }
2874        return null;
2875    }
2876
2877    @Override
2878    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2879            final IPackageDataObserver observer) {
2880        mContext.enforceCallingOrSelfPermission(
2881                android.Manifest.permission.CLEAR_APP_CACHE, null);
2882        // Queue up an async operation since clearing cache may take a little while.
2883        mHandler.post(new Runnable() {
2884            public void run() {
2885                mHandler.removeCallbacks(this);
2886                int retCode = -1;
2887                synchronized (mInstallLock) {
2888                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2889                    if (retCode < 0) {
2890                        Slog.w(TAG, "Couldn't clear application caches");
2891                    }
2892                }
2893                if (observer != null) {
2894                    try {
2895                        observer.onRemoveCompleted(null, (retCode >= 0));
2896                    } catch (RemoteException e) {
2897                        Slog.w(TAG, "RemoveException when invoking call back");
2898                    }
2899                }
2900            }
2901        });
2902    }
2903
2904    @Override
2905    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2906            final IntentSender pi) {
2907        mContext.enforceCallingOrSelfPermission(
2908                android.Manifest.permission.CLEAR_APP_CACHE, null);
2909        // Queue up an async operation since clearing cache may take a little while.
2910        mHandler.post(new Runnable() {
2911            public void run() {
2912                mHandler.removeCallbacks(this);
2913                int retCode = -1;
2914                synchronized (mInstallLock) {
2915                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2916                    if (retCode < 0) {
2917                        Slog.w(TAG, "Couldn't clear application caches");
2918                    }
2919                }
2920                if(pi != null) {
2921                    try {
2922                        // Callback via pending intent
2923                        int code = (retCode >= 0) ? 1 : 0;
2924                        pi.sendIntent(null, code, null,
2925                                null, null);
2926                    } catch (SendIntentException e1) {
2927                        Slog.i(TAG, "Failed to send pending intent");
2928                    }
2929                }
2930            }
2931        });
2932    }
2933
2934    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2935        synchronized (mInstallLock) {
2936            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2937                throw new IOException("Failed to free enough space");
2938            }
2939        }
2940    }
2941
2942    @Override
2943    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2944        if (!sUserManager.exists(userId)) return null;
2945        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2946        synchronized (mPackages) {
2947            PackageParser.Activity a = mActivities.mActivities.get(component);
2948
2949            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2950            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2951                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2952                if (ps == null) return null;
2953                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2954                        userId);
2955            }
2956            if (mResolveComponentName.equals(component)) {
2957                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2958                        new PackageUserState(), userId);
2959            }
2960        }
2961        return null;
2962    }
2963
2964    @Override
2965    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2966            String resolvedType) {
2967        synchronized (mPackages) {
2968            PackageParser.Activity a = mActivities.mActivities.get(component);
2969            if (a == null) {
2970                return false;
2971            }
2972            for (int i=0; i<a.intents.size(); i++) {
2973                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2974                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2975                    return true;
2976                }
2977            }
2978            return false;
2979        }
2980    }
2981
2982    @Override
2983    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2984        if (!sUserManager.exists(userId)) return null;
2985        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2986        synchronized (mPackages) {
2987            PackageParser.Activity a = mReceivers.mActivities.get(component);
2988            if (DEBUG_PACKAGE_INFO) Log.v(
2989                TAG, "getReceiverInfo " + component + ": " + a);
2990            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2991                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2992                if (ps == null) return null;
2993                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2994                        userId);
2995            }
2996        }
2997        return null;
2998    }
2999
3000    @Override
3001    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3002        if (!sUserManager.exists(userId)) return null;
3003        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3004        synchronized (mPackages) {
3005            PackageParser.Service s = mServices.mServices.get(component);
3006            if (DEBUG_PACKAGE_INFO) Log.v(
3007                TAG, "getServiceInfo " + component + ": " + s);
3008            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3009                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3010                if (ps == null) return null;
3011                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3012                        userId);
3013            }
3014        }
3015        return null;
3016    }
3017
3018    @Override
3019    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3020        if (!sUserManager.exists(userId)) return null;
3021        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3022        synchronized (mPackages) {
3023            PackageParser.Provider p = mProviders.mProviders.get(component);
3024            if (DEBUG_PACKAGE_INFO) Log.v(
3025                TAG, "getProviderInfo " + component + ": " + p);
3026            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3027                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3028                if (ps == null) return null;
3029                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3030                        userId);
3031            }
3032        }
3033        return null;
3034    }
3035
3036    @Override
3037    public String[] getSystemSharedLibraryNames() {
3038        Set<String> libSet;
3039        synchronized (mPackages) {
3040            libSet = mSharedLibraries.keySet();
3041            int size = libSet.size();
3042            if (size > 0) {
3043                String[] libs = new String[size];
3044                libSet.toArray(libs);
3045                return libs;
3046            }
3047        }
3048        return null;
3049    }
3050
3051    /**
3052     * @hide
3053     */
3054    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3055        synchronized (mPackages) {
3056            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3057            if (lib != null && lib.apk != null) {
3058                return mPackages.get(lib.apk);
3059            }
3060        }
3061        return null;
3062    }
3063
3064    @Override
3065    public FeatureInfo[] getSystemAvailableFeatures() {
3066        Collection<FeatureInfo> featSet;
3067        synchronized (mPackages) {
3068            featSet = mAvailableFeatures.values();
3069            int size = featSet.size();
3070            if (size > 0) {
3071                FeatureInfo[] features = new FeatureInfo[size+1];
3072                featSet.toArray(features);
3073                FeatureInfo fi = new FeatureInfo();
3074                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3075                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3076                features[size] = fi;
3077                return features;
3078            }
3079        }
3080        return null;
3081    }
3082
3083    @Override
3084    public boolean hasSystemFeature(String name) {
3085        synchronized (mPackages) {
3086            return mAvailableFeatures.containsKey(name);
3087        }
3088    }
3089
3090    private void checkValidCaller(int uid, int userId) {
3091        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3092            return;
3093
3094        throw new SecurityException("Caller uid=" + uid
3095                + " is not privileged to communicate with user=" + userId);
3096    }
3097
3098    @Override
3099    public int checkPermission(String permName, String pkgName, int userId) {
3100        if (!sUserManager.exists(userId)) {
3101            return PackageManager.PERMISSION_DENIED;
3102        }
3103
3104        synchronized (mPackages) {
3105            final PackageParser.Package p = mPackages.get(pkgName);
3106            if (p != null && p.mExtras != null) {
3107                final PackageSetting ps = (PackageSetting) p.mExtras;
3108                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3109                    return PackageManager.PERMISSION_GRANTED;
3110                }
3111            }
3112        }
3113
3114        return PackageManager.PERMISSION_DENIED;
3115    }
3116
3117    @Override
3118    public int checkUidPermission(String permName, int uid) {
3119        final int userId = UserHandle.getUserId(uid);
3120
3121        if (!sUserManager.exists(userId)) {
3122            return PackageManager.PERMISSION_DENIED;
3123        }
3124
3125        synchronized (mPackages) {
3126            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3127            if (obj != null) {
3128                final SettingBase ps = (SettingBase) obj;
3129                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3130                    return PackageManager.PERMISSION_GRANTED;
3131                }
3132            } else {
3133                ArraySet<String> perms = mSystemPermissions.get(uid);
3134                if (perms != null && perms.contains(permName)) {
3135                    return PackageManager.PERMISSION_GRANTED;
3136                }
3137            }
3138        }
3139
3140        return PackageManager.PERMISSION_DENIED;
3141    }
3142
3143    @Override
3144    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3145        if (UserHandle.getCallingUserId() != userId) {
3146            mContext.enforceCallingPermission(
3147                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3148                    "isPermissionRevokedByPolicy for user " + userId);
3149        }
3150
3151        if (checkPermission(permission, packageName, userId)
3152                == PackageManager.PERMISSION_GRANTED) {
3153            return false;
3154        }
3155
3156        final long identity = Binder.clearCallingIdentity();
3157        try {
3158            final int flags = getPermissionFlags(permission, packageName, userId);
3159            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3160        } finally {
3161            Binder.restoreCallingIdentity(identity);
3162        }
3163    }
3164
3165    /**
3166     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3167     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3168     * @param checkShell TODO(yamasani):
3169     * @param message the message to log on security exception
3170     */
3171    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3172            boolean checkShell, String message) {
3173        if (userId < 0) {
3174            throw new IllegalArgumentException("Invalid userId " + userId);
3175        }
3176        if (checkShell) {
3177            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3178        }
3179        if (userId == UserHandle.getUserId(callingUid)) return;
3180        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3181            if (requireFullPermission) {
3182                mContext.enforceCallingOrSelfPermission(
3183                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3184            } else {
3185                try {
3186                    mContext.enforceCallingOrSelfPermission(
3187                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3188                } catch (SecurityException se) {
3189                    mContext.enforceCallingOrSelfPermission(
3190                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3191                }
3192            }
3193        }
3194    }
3195
3196    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3197        if (callingUid == Process.SHELL_UID) {
3198            if (userHandle >= 0
3199                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3200                throw new SecurityException("Shell does not have permission to access user "
3201                        + userHandle);
3202            } else if (userHandle < 0) {
3203                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3204                        + Debug.getCallers(3));
3205            }
3206        }
3207    }
3208
3209    private BasePermission findPermissionTreeLP(String permName) {
3210        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3211            if (permName.startsWith(bp.name) &&
3212                    permName.length() > bp.name.length() &&
3213                    permName.charAt(bp.name.length()) == '.') {
3214                return bp;
3215            }
3216        }
3217        return null;
3218    }
3219
3220    private BasePermission checkPermissionTreeLP(String permName) {
3221        if (permName != null) {
3222            BasePermission bp = findPermissionTreeLP(permName);
3223            if (bp != null) {
3224                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3225                    return bp;
3226                }
3227                throw new SecurityException("Calling uid "
3228                        + Binder.getCallingUid()
3229                        + " is not allowed to add to permission tree "
3230                        + bp.name + " owned by uid " + bp.uid);
3231            }
3232        }
3233        throw new SecurityException("No permission tree found for " + permName);
3234    }
3235
3236    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3237        if (s1 == null) {
3238            return s2 == null;
3239        }
3240        if (s2 == null) {
3241            return false;
3242        }
3243        if (s1.getClass() != s2.getClass()) {
3244            return false;
3245        }
3246        return s1.equals(s2);
3247    }
3248
3249    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3250        if (pi1.icon != pi2.icon) return false;
3251        if (pi1.logo != pi2.logo) return false;
3252        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3253        if (!compareStrings(pi1.name, pi2.name)) return false;
3254        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3255        // We'll take care of setting this one.
3256        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3257        // These are not currently stored in settings.
3258        //if (!compareStrings(pi1.group, pi2.group)) return false;
3259        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3260        //if (pi1.labelRes != pi2.labelRes) return false;
3261        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3262        return true;
3263    }
3264
3265    int permissionInfoFootprint(PermissionInfo info) {
3266        int size = info.name.length();
3267        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3268        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3269        return size;
3270    }
3271
3272    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3273        int size = 0;
3274        for (BasePermission perm : mSettings.mPermissions.values()) {
3275            if (perm.uid == tree.uid) {
3276                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3277            }
3278        }
3279        return size;
3280    }
3281
3282    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3283        // We calculate the max size of permissions defined by this uid and throw
3284        // if that plus the size of 'info' would exceed our stated maximum.
3285        if (tree.uid != Process.SYSTEM_UID) {
3286            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3287            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3288                throw new SecurityException("Permission tree size cap exceeded");
3289            }
3290        }
3291    }
3292
3293    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3294        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3295            throw new SecurityException("Label must be specified in permission");
3296        }
3297        BasePermission tree = checkPermissionTreeLP(info.name);
3298        BasePermission bp = mSettings.mPermissions.get(info.name);
3299        boolean added = bp == null;
3300        boolean changed = true;
3301        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3302        if (added) {
3303            enforcePermissionCapLocked(info, tree);
3304            bp = new BasePermission(info.name, tree.sourcePackage,
3305                    BasePermission.TYPE_DYNAMIC);
3306        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3307            throw new SecurityException(
3308                    "Not allowed to modify non-dynamic permission "
3309                    + info.name);
3310        } else {
3311            if (bp.protectionLevel == fixedLevel
3312                    && bp.perm.owner.equals(tree.perm.owner)
3313                    && bp.uid == tree.uid
3314                    && comparePermissionInfos(bp.perm.info, info)) {
3315                changed = false;
3316            }
3317        }
3318        bp.protectionLevel = fixedLevel;
3319        info = new PermissionInfo(info);
3320        info.protectionLevel = fixedLevel;
3321        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3322        bp.perm.info.packageName = tree.perm.info.packageName;
3323        bp.uid = tree.uid;
3324        if (added) {
3325            mSettings.mPermissions.put(info.name, bp);
3326        }
3327        if (changed) {
3328            if (!async) {
3329                mSettings.writeLPr();
3330            } else {
3331                scheduleWriteSettingsLocked();
3332            }
3333        }
3334        return added;
3335    }
3336
3337    @Override
3338    public boolean addPermission(PermissionInfo info) {
3339        synchronized (mPackages) {
3340            return addPermissionLocked(info, false);
3341        }
3342    }
3343
3344    @Override
3345    public boolean addPermissionAsync(PermissionInfo info) {
3346        synchronized (mPackages) {
3347            return addPermissionLocked(info, true);
3348        }
3349    }
3350
3351    @Override
3352    public void removePermission(String name) {
3353        synchronized (mPackages) {
3354            checkPermissionTreeLP(name);
3355            BasePermission bp = mSettings.mPermissions.get(name);
3356            if (bp != null) {
3357                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3358                    throw new SecurityException(
3359                            "Not allowed to modify non-dynamic permission "
3360                            + name);
3361                }
3362                mSettings.mPermissions.remove(name);
3363                mSettings.writeLPr();
3364            }
3365        }
3366    }
3367
3368    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3369            BasePermission bp) {
3370        int index = pkg.requestedPermissions.indexOf(bp.name);
3371        if (index == -1) {
3372            throw new SecurityException("Package " + pkg.packageName
3373                    + " has not requested permission " + bp.name);
3374        }
3375        if (!bp.isRuntime()) {
3376            throw new SecurityException("Permission " + bp.name
3377                    + " is not a changeable permission type");
3378        }
3379    }
3380
3381    @Override
3382    public void grantRuntimePermission(String packageName, String name, final int userId) {
3383        if (!sUserManager.exists(userId)) {
3384            Log.e(TAG, "No such user:" + userId);
3385            return;
3386        }
3387
3388        mContext.enforceCallingOrSelfPermission(
3389                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3390                "grantRuntimePermission");
3391
3392        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3393                "grantRuntimePermission");
3394
3395        final int uid;
3396        final SettingBase sb;
3397
3398        synchronized (mPackages) {
3399            final PackageParser.Package pkg = mPackages.get(packageName);
3400            if (pkg == null) {
3401                throw new IllegalArgumentException("Unknown package: " + packageName);
3402            }
3403
3404            final BasePermission bp = mSettings.mPermissions.get(name);
3405            if (bp == null) {
3406                throw new IllegalArgumentException("Unknown permission: " + name);
3407            }
3408
3409            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3410
3411            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3412            sb = (SettingBase) pkg.mExtras;
3413            if (sb == null) {
3414                throw new IllegalArgumentException("Unknown package: " + packageName);
3415            }
3416
3417            final PermissionsState permissionsState = sb.getPermissionsState();
3418
3419            final int flags = permissionsState.getPermissionFlags(name, userId);
3420            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3421                throw new SecurityException("Cannot grant system fixed permission: "
3422                        + name + " for package: " + packageName);
3423            }
3424
3425            final int result = permissionsState.grantRuntimePermission(bp, userId);
3426            switch (result) {
3427                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3428                    return;
3429                }
3430
3431                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3432                    mHandler.post(new Runnable() {
3433                        @Override
3434                        public void run() {
3435                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3436                        }
3437                    });
3438                } break;
3439            }
3440
3441            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3442
3443            // Not critical if that is lost - app has to request again.
3444            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3445        }
3446
3447        // Only need to do this if user is initialized. Otherwise it's a new user
3448        // and there are no processes running as the user yet and there's no need
3449        // to make an expensive call to remount processes for the changed permissions.
3450        if (READ_EXTERNAL_STORAGE.equals(name)
3451                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3452            final long token = Binder.clearCallingIdentity();
3453            try {
3454                if (sUserManager.isInitialized(userId)) {
3455                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3456                            MountServiceInternal.class);
3457                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3458                }
3459            } finally {
3460                Binder.restoreCallingIdentity(token);
3461            }
3462        }
3463    }
3464
3465    @Override
3466    public void revokeRuntimePermission(String packageName, String name, int userId) {
3467        if (!sUserManager.exists(userId)) {
3468            Log.e(TAG, "No such user:" + userId);
3469            return;
3470        }
3471
3472        mContext.enforceCallingOrSelfPermission(
3473                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3474                "revokeRuntimePermission");
3475
3476        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3477                "revokeRuntimePermission");
3478
3479        final SettingBase sb;
3480
3481        synchronized (mPackages) {
3482            final PackageParser.Package pkg = mPackages.get(packageName);
3483            if (pkg == null) {
3484                throw new IllegalArgumentException("Unknown package: " + packageName);
3485            }
3486
3487            final BasePermission bp = mSettings.mPermissions.get(name);
3488            if (bp == null) {
3489                throw new IllegalArgumentException("Unknown permission: " + name);
3490            }
3491
3492            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3493
3494            sb = (SettingBase) pkg.mExtras;
3495            if (sb == null) {
3496                throw new IllegalArgumentException("Unknown package: " + packageName);
3497            }
3498
3499            final PermissionsState permissionsState = sb.getPermissionsState();
3500
3501            final int flags = permissionsState.getPermissionFlags(name, userId);
3502            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3503                throw new SecurityException("Cannot revoke system fixed permission: "
3504                        + name + " for package: " + packageName);
3505            }
3506
3507            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3508                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3509                return;
3510            }
3511
3512            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3513
3514            // Critical, after this call app should never have the permission.
3515            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3516        }
3517
3518        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3519    }
3520
3521    @Override
3522    public void resetRuntimePermissions() {
3523        mContext.enforceCallingOrSelfPermission(
3524                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3525                "revokeRuntimePermission");
3526
3527        int callingUid = Binder.getCallingUid();
3528        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3529            mContext.enforceCallingOrSelfPermission(
3530                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3531                    "resetRuntimePermissions");
3532        }
3533
3534        synchronized (mPackages) {
3535            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3536            for (int userId : UserManagerService.getInstance().getUserIds()) {
3537                final int packageCount = mPackages.size();
3538                for (int i = 0; i < packageCount; i++) {
3539                    PackageParser.Package pkg = mPackages.valueAt(i);
3540                    if (!(pkg.mExtras instanceof PackageSetting)) {
3541                        continue;
3542                    }
3543                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3544                    resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
3545                }
3546            }
3547        }
3548    }
3549
3550    @Override
3551    public int getPermissionFlags(String name, String packageName, int userId) {
3552        if (!sUserManager.exists(userId)) {
3553            return 0;
3554        }
3555
3556        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3557
3558        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3559                "getPermissionFlags");
3560
3561        synchronized (mPackages) {
3562            final PackageParser.Package pkg = mPackages.get(packageName);
3563            if (pkg == null) {
3564                throw new IllegalArgumentException("Unknown package: " + packageName);
3565            }
3566
3567            final BasePermission bp = mSettings.mPermissions.get(name);
3568            if (bp == null) {
3569                throw new IllegalArgumentException("Unknown permission: " + name);
3570            }
3571
3572            SettingBase sb = (SettingBase) pkg.mExtras;
3573            if (sb == null) {
3574                throw new IllegalArgumentException("Unknown package: " + packageName);
3575            }
3576
3577            PermissionsState permissionsState = sb.getPermissionsState();
3578            return permissionsState.getPermissionFlags(name, userId);
3579        }
3580    }
3581
3582    @Override
3583    public void updatePermissionFlags(String name, String packageName, int flagMask,
3584            int flagValues, int userId) {
3585        if (!sUserManager.exists(userId)) {
3586            return;
3587        }
3588
3589        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3590
3591        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3592                "updatePermissionFlags");
3593
3594        // Only the system can change system fixed flags.
3595        if (getCallingUid() != Process.SYSTEM_UID) {
3596            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3597            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3598        }
3599
3600        synchronized (mPackages) {
3601            final PackageParser.Package pkg = mPackages.get(packageName);
3602            if (pkg == null) {
3603                throw new IllegalArgumentException("Unknown package: " + packageName);
3604            }
3605
3606            final BasePermission bp = mSettings.mPermissions.get(name);
3607            if (bp == null) {
3608                throw new IllegalArgumentException("Unknown permission: " + name);
3609            }
3610
3611            SettingBase sb = (SettingBase) pkg.mExtras;
3612            if (sb == null) {
3613                throw new IllegalArgumentException("Unknown package: " + packageName);
3614            }
3615
3616            PermissionsState permissionsState = sb.getPermissionsState();
3617
3618            // Only the package manager can change flags for system component permissions.
3619            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3620            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3621                return;
3622            }
3623
3624            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3625
3626            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3627                // Install and runtime permissions are stored in different places,
3628                // so figure out what permission changed and persist the change.
3629                if (permissionsState.getInstallPermissionState(name) != null) {
3630                    scheduleWriteSettingsLocked();
3631                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3632                        || hadState) {
3633                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3634                }
3635            }
3636        }
3637    }
3638
3639    /**
3640     * Update the permission flags for all packages and runtime permissions of a user in order
3641     * to allow device or profile owner to remove POLICY_FIXED.
3642     */
3643    @Override
3644    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3645        if (!sUserManager.exists(userId)) {
3646            return;
3647        }
3648
3649        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3650
3651        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3652                "updatePermissionFlagsForAllApps");
3653
3654        // Only the system can change system fixed flags.
3655        if (getCallingUid() != Process.SYSTEM_UID) {
3656            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3657            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3658        }
3659
3660        synchronized (mPackages) {
3661            boolean changed = false;
3662            final int packageCount = mPackages.size();
3663            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3664                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3665                SettingBase sb = (SettingBase) pkg.mExtras;
3666                if (sb == null) {
3667                    continue;
3668                }
3669                PermissionsState permissionsState = sb.getPermissionsState();
3670                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3671                        userId, flagMask, flagValues);
3672            }
3673            if (changed) {
3674                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3675            }
3676        }
3677    }
3678
3679    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3680        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3681                != PackageManager.PERMISSION_GRANTED
3682            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3683                != PackageManager.PERMISSION_GRANTED) {
3684            throw new SecurityException(message + " requires "
3685                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3686                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3687        }
3688    }
3689
3690    @Override
3691    public boolean shouldShowRequestPermissionRationale(String permissionName,
3692            String packageName, int userId) {
3693        if (UserHandle.getCallingUserId() != userId) {
3694            mContext.enforceCallingPermission(
3695                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3696                    "canShowRequestPermissionRationale for user " + userId);
3697        }
3698
3699        final int uid = getPackageUid(packageName, userId);
3700        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3701            return false;
3702        }
3703
3704        if (checkPermission(permissionName, packageName, userId)
3705                == PackageManager.PERMISSION_GRANTED) {
3706            return false;
3707        }
3708
3709        final int flags;
3710
3711        final long identity = Binder.clearCallingIdentity();
3712        try {
3713            flags = getPermissionFlags(permissionName,
3714                    packageName, userId);
3715        } finally {
3716            Binder.restoreCallingIdentity(identity);
3717        }
3718
3719        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3720                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3721                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3722
3723        if ((flags & fixedFlags) != 0) {
3724            return false;
3725        }
3726
3727        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3728    }
3729
3730    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3731        BasePermission bp = mSettings.mPermissions.get(permission);
3732        if (bp == null) {
3733            throw new SecurityException("Missing " + permission + " permission");
3734        }
3735
3736        SettingBase sb = (SettingBase) pkg.mExtras;
3737        PermissionsState permissionsState = sb.getPermissionsState();
3738
3739        if (permissionsState.grantInstallPermission(bp) !=
3740                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3741            scheduleWriteSettingsLocked();
3742        }
3743    }
3744
3745    @Override
3746    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3747        mContext.enforceCallingOrSelfPermission(
3748                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3749                "addOnPermissionsChangeListener");
3750
3751        synchronized (mPackages) {
3752            mOnPermissionChangeListeners.addListenerLocked(listener);
3753        }
3754    }
3755
3756    @Override
3757    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3758        synchronized (mPackages) {
3759            mOnPermissionChangeListeners.removeListenerLocked(listener);
3760        }
3761    }
3762
3763    @Override
3764    public boolean isProtectedBroadcast(String actionName) {
3765        synchronized (mPackages) {
3766            return mProtectedBroadcasts.contains(actionName);
3767        }
3768    }
3769
3770    @Override
3771    public int checkSignatures(String pkg1, String pkg2) {
3772        synchronized (mPackages) {
3773            final PackageParser.Package p1 = mPackages.get(pkg1);
3774            final PackageParser.Package p2 = mPackages.get(pkg2);
3775            if (p1 == null || p1.mExtras == null
3776                    || p2 == null || p2.mExtras == null) {
3777                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3778            }
3779            return compareSignatures(p1.mSignatures, p2.mSignatures);
3780        }
3781    }
3782
3783    @Override
3784    public int checkUidSignatures(int uid1, int uid2) {
3785        // Map to base uids.
3786        uid1 = UserHandle.getAppId(uid1);
3787        uid2 = UserHandle.getAppId(uid2);
3788        // reader
3789        synchronized (mPackages) {
3790            Signature[] s1;
3791            Signature[] s2;
3792            Object obj = mSettings.getUserIdLPr(uid1);
3793            if (obj != null) {
3794                if (obj instanceof SharedUserSetting) {
3795                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3796                } else if (obj instanceof PackageSetting) {
3797                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3798                } else {
3799                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3800                }
3801            } else {
3802                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3803            }
3804            obj = mSettings.getUserIdLPr(uid2);
3805            if (obj != null) {
3806                if (obj instanceof SharedUserSetting) {
3807                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3808                } else if (obj instanceof PackageSetting) {
3809                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3810                } else {
3811                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3812                }
3813            } else {
3814                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3815            }
3816            return compareSignatures(s1, s2);
3817        }
3818    }
3819
3820    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3821        final long identity = Binder.clearCallingIdentity();
3822        try {
3823            if (sb instanceof SharedUserSetting) {
3824                SharedUserSetting sus = (SharedUserSetting) sb;
3825                final int packageCount = sus.packages.size();
3826                for (int i = 0; i < packageCount; i++) {
3827                    PackageSetting susPs = sus.packages.valueAt(i);
3828                    if (userId == UserHandle.USER_ALL) {
3829                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3830                    } else {
3831                        final int uid = UserHandle.getUid(userId, susPs.appId);
3832                        killUid(uid, reason);
3833                    }
3834                }
3835            } else if (sb instanceof PackageSetting) {
3836                PackageSetting ps = (PackageSetting) sb;
3837                if (userId == UserHandle.USER_ALL) {
3838                    killApplication(ps.pkg.packageName, ps.appId, reason);
3839                } else {
3840                    final int uid = UserHandle.getUid(userId, ps.appId);
3841                    killUid(uid, reason);
3842                }
3843            }
3844        } finally {
3845            Binder.restoreCallingIdentity(identity);
3846        }
3847    }
3848
3849    private static void killUid(int uid, String reason) {
3850        IActivityManager am = ActivityManagerNative.getDefault();
3851        if (am != null) {
3852            try {
3853                am.killUid(uid, reason);
3854            } catch (RemoteException e) {
3855                /* ignore - same process */
3856            }
3857        }
3858    }
3859
3860    /**
3861     * Compares two sets of signatures. Returns:
3862     * <br />
3863     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3864     * <br />
3865     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3866     * <br />
3867     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3868     * <br />
3869     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3870     * <br />
3871     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3872     */
3873    static int compareSignatures(Signature[] s1, Signature[] s2) {
3874        if (s1 == null) {
3875            return s2 == null
3876                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3877                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3878        }
3879
3880        if (s2 == null) {
3881            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3882        }
3883
3884        if (s1.length != s2.length) {
3885            return PackageManager.SIGNATURE_NO_MATCH;
3886        }
3887
3888        // Since both signature sets are of size 1, we can compare without HashSets.
3889        if (s1.length == 1) {
3890            return s1[0].equals(s2[0]) ?
3891                    PackageManager.SIGNATURE_MATCH :
3892                    PackageManager.SIGNATURE_NO_MATCH;
3893        }
3894
3895        ArraySet<Signature> set1 = new ArraySet<Signature>();
3896        for (Signature sig : s1) {
3897            set1.add(sig);
3898        }
3899        ArraySet<Signature> set2 = new ArraySet<Signature>();
3900        for (Signature sig : s2) {
3901            set2.add(sig);
3902        }
3903        // Make sure s2 contains all signatures in s1.
3904        if (set1.equals(set2)) {
3905            return PackageManager.SIGNATURE_MATCH;
3906        }
3907        return PackageManager.SIGNATURE_NO_MATCH;
3908    }
3909
3910    /**
3911     * If the database version for this type of package (internal storage or
3912     * external storage) is less than the version where package signatures
3913     * were updated, return true.
3914     */
3915    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3916        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3917                DatabaseVersion.SIGNATURE_END_ENTITY))
3918                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3919                        DatabaseVersion.SIGNATURE_END_ENTITY));
3920    }
3921
3922    /**
3923     * Used for backward compatibility to make sure any packages with
3924     * certificate chains get upgraded to the new style. {@code existingSigs}
3925     * will be in the old format (since they were stored on disk from before the
3926     * system upgrade) and {@code scannedSigs} will be in the newer format.
3927     */
3928    private int compareSignaturesCompat(PackageSignatures existingSigs,
3929            PackageParser.Package scannedPkg) {
3930        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3931            return PackageManager.SIGNATURE_NO_MATCH;
3932        }
3933
3934        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3935        for (Signature sig : existingSigs.mSignatures) {
3936            existingSet.add(sig);
3937        }
3938        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3939        for (Signature sig : scannedPkg.mSignatures) {
3940            try {
3941                Signature[] chainSignatures = sig.getChainSignatures();
3942                for (Signature chainSig : chainSignatures) {
3943                    scannedCompatSet.add(chainSig);
3944                }
3945            } catch (CertificateEncodingException e) {
3946                scannedCompatSet.add(sig);
3947            }
3948        }
3949        /*
3950         * Make sure the expanded scanned set contains all signatures in the
3951         * existing one.
3952         */
3953        if (scannedCompatSet.equals(existingSet)) {
3954            // Migrate the old signatures to the new scheme.
3955            existingSigs.assignSignatures(scannedPkg.mSignatures);
3956            // The new KeySets will be re-added later in the scanning process.
3957            synchronized (mPackages) {
3958                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3959            }
3960            return PackageManager.SIGNATURE_MATCH;
3961        }
3962        return PackageManager.SIGNATURE_NO_MATCH;
3963    }
3964
3965    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3966        if (isExternal(scannedPkg)) {
3967            return mSettings.isExternalDatabaseVersionOlderThan(
3968                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3969        } else {
3970            return mSettings.isInternalDatabaseVersionOlderThan(
3971                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3972        }
3973    }
3974
3975    private int compareSignaturesRecover(PackageSignatures existingSigs,
3976            PackageParser.Package scannedPkg) {
3977        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3978            return PackageManager.SIGNATURE_NO_MATCH;
3979        }
3980
3981        String msg = null;
3982        try {
3983            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3984                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3985                        + scannedPkg.packageName);
3986                return PackageManager.SIGNATURE_MATCH;
3987            }
3988        } catch (CertificateException e) {
3989            msg = e.getMessage();
3990        }
3991
3992        logCriticalInfo(Log.INFO,
3993                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3994        return PackageManager.SIGNATURE_NO_MATCH;
3995    }
3996
3997    @Override
3998    public String[] getPackagesForUid(int uid) {
3999        uid = UserHandle.getAppId(uid);
4000        // reader
4001        synchronized (mPackages) {
4002            Object obj = mSettings.getUserIdLPr(uid);
4003            if (obj instanceof SharedUserSetting) {
4004                final SharedUserSetting sus = (SharedUserSetting) obj;
4005                final int N = sus.packages.size();
4006                final String[] res = new String[N];
4007                final Iterator<PackageSetting> it = sus.packages.iterator();
4008                int i = 0;
4009                while (it.hasNext()) {
4010                    res[i++] = it.next().name;
4011                }
4012                return res;
4013            } else if (obj instanceof PackageSetting) {
4014                final PackageSetting ps = (PackageSetting) obj;
4015                return new String[] { ps.name };
4016            }
4017        }
4018        return null;
4019    }
4020
4021    @Override
4022    public String getNameForUid(int uid) {
4023        // reader
4024        synchronized (mPackages) {
4025            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4026            if (obj instanceof SharedUserSetting) {
4027                final SharedUserSetting sus = (SharedUserSetting) obj;
4028                return sus.name + ":" + sus.userId;
4029            } else if (obj instanceof PackageSetting) {
4030                final PackageSetting ps = (PackageSetting) obj;
4031                return ps.name;
4032            }
4033        }
4034        return null;
4035    }
4036
4037    @Override
4038    public int getUidForSharedUser(String sharedUserName) {
4039        if(sharedUserName == null) {
4040            return -1;
4041        }
4042        // reader
4043        synchronized (mPackages) {
4044            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4045            if (suid == null) {
4046                return -1;
4047            }
4048            return suid.userId;
4049        }
4050    }
4051
4052    @Override
4053    public int getFlagsForUid(int uid) {
4054        synchronized (mPackages) {
4055            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4056            if (obj instanceof SharedUserSetting) {
4057                final SharedUserSetting sus = (SharedUserSetting) obj;
4058                return sus.pkgFlags;
4059            } else if (obj instanceof PackageSetting) {
4060                final PackageSetting ps = (PackageSetting) obj;
4061                return ps.pkgFlags;
4062            }
4063        }
4064        return 0;
4065    }
4066
4067    @Override
4068    public int getPrivateFlagsForUid(int uid) {
4069        synchronized (mPackages) {
4070            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4071            if (obj instanceof SharedUserSetting) {
4072                final SharedUserSetting sus = (SharedUserSetting) obj;
4073                return sus.pkgPrivateFlags;
4074            } else if (obj instanceof PackageSetting) {
4075                final PackageSetting ps = (PackageSetting) obj;
4076                return ps.pkgPrivateFlags;
4077            }
4078        }
4079        return 0;
4080    }
4081
4082    @Override
4083    public boolean isUidPrivileged(int uid) {
4084        uid = UserHandle.getAppId(uid);
4085        // reader
4086        synchronized (mPackages) {
4087            Object obj = mSettings.getUserIdLPr(uid);
4088            if (obj instanceof SharedUserSetting) {
4089                final SharedUserSetting sus = (SharedUserSetting) obj;
4090                final Iterator<PackageSetting> it = sus.packages.iterator();
4091                while (it.hasNext()) {
4092                    if (it.next().isPrivileged()) {
4093                        return true;
4094                    }
4095                }
4096            } else if (obj instanceof PackageSetting) {
4097                final PackageSetting ps = (PackageSetting) obj;
4098                return ps.isPrivileged();
4099            }
4100        }
4101        return false;
4102    }
4103
4104    @Override
4105    public String[] getAppOpPermissionPackages(String permissionName) {
4106        synchronized (mPackages) {
4107            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4108            if (pkgs == null) {
4109                return null;
4110            }
4111            return pkgs.toArray(new String[pkgs.size()]);
4112        }
4113    }
4114
4115    @Override
4116    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4117            int flags, int userId) {
4118        if (!sUserManager.exists(userId)) return null;
4119        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4120        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4121        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4122    }
4123
4124    @Override
4125    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4126            IntentFilter filter, int match, ComponentName activity) {
4127        final int userId = UserHandle.getCallingUserId();
4128        if (DEBUG_PREFERRED) {
4129            Log.v(TAG, "setLastChosenActivity intent=" + intent
4130                + " resolvedType=" + resolvedType
4131                + " flags=" + flags
4132                + " filter=" + filter
4133                + " match=" + match
4134                + " activity=" + activity);
4135            filter.dump(new PrintStreamPrinter(System.out), "    ");
4136        }
4137        intent.setComponent(null);
4138        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4139        // Find any earlier preferred or last chosen entries and nuke them
4140        findPreferredActivity(intent, resolvedType,
4141                flags, query, 0, false, true, false, userId);
4142        // Add the new activity as the last chosen for this filter
4143        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4144                "Setting last chosen");
4145    }
4146
4147    @Override
4148    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4149        final int userId = UserHandle.getCallingUserId();
4150        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4151        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4152        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4153                false, false, false, userId);
4154    }
4155
4156    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4157            int flags, List<ResolveInfo> query, int userId) {
4158        if (query != null) {
4159            final int N = query.size();
4160            if (N == 1) {
4161                return query.get(0);
4162            } else if (N > 1) {
4163                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4164                // If there is more than one activity with the same priority,
4165                // then let the user decide between them.
4166                ResolveInfo r0 = query.get(0);
4167                ResolveInfo r1 = query.get(1);
4168                if (DEBUG_INTENT_MATCHING || debug) {
4169                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4170                            + r1.activityInfo.name + "=" + r1.priority);
4171                }
4172                // If the first activity has a higher priority, or a different
4173                // default, then it is always desireable to pick it.
4174                if (r0.priority != r1.priority
4175                        || r0.preferredOrder != r1.preferredOrder
4176                        || r0.isDefault != r1.isDefault) {
4177                    return query.get(0);
4178                }
4179                // If we have saved a preference for a preferred activity for
4180                // this Intent, use that.
4181                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4182                        flags, query, r0.priority, true, false, debug, userId);
4183                if (ri != null) {
4184                    return ri;
4185                }
4186                if (userId != 0) {
4187                    ri = new ResolveInfo(mResolveInfo);
4188                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4189                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4190                            ri.activityInfo.applicationInfo);
4191                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4192                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4193                    return ri;
4194                }
4195                return mResolveInfo;
4196            }
4197        }
4198        return null;
4199    }
4200
4201    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4202            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4203        final int N = query.size();
4204        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4205                .get(userId);
4206        // Get the list of persistent preferred activities that handle the intent
4207        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4208        List<PersistentPreferredActivity> pprefs = ppir != null
4209                ? ppir.queryIntent(intent, resolvedType,
4210                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4211                : null;
4212        if (pprefs != null && pprefs.size() > 0) {
4213            final int M = pprefs.size();
4214            for (int i=0; i<M; i++) {
4215                final PersistentPreferredActivity ppa = pprefs.get(i);
4216                if (DEBUG_PREFERRED || debug) {
4217                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4218                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4219                            + "\n  component=" + ppa.mComponent);
4220                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4221                }
4222                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4223                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4224                if (DEBUG_PREFERRED || debug) {
4225                    Slog.v(TAG, "Found persistent preferred activity:");
4226                    if (ai != null) {
4227                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4228                    } else {
4229                        Slog.v(TAG, "  null");
4230                    }
4231                }
4232                if (ai == null) {
4233                    // This previously registered persistent preferred activity
4234                    // component is no longer known. Ignore it and do NOT remove it.
4235                    continue;
4236                }
4237                for (int j=0; j<N; j++) {
4238                    final ResolveInfo ri = query.get(j);
4239                    if (!ri.activityInfo.applicationInfo.packageName
4240                            .equals(ai.applicationInfo.packageName)) {
4241                        continue;
4242                    }
4243                    if (!ri.activityInfo.name.equals(ai.name)) {
4244                        continue;
4245                    }
4246                    //  Found a persistent preference that can handle the intent.
4247                    if (DEBUG_PREFERRED || debug) {
4248                        Slog.v(TAG, "Returning persistent preferred activity: " +
4249                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4250                    }
4251                    return ri;
4252                }
4253            }
4254        }
4255        return null;
4256    }
4257
4258    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4259            List<ResolveInfo> query, int priority, boolean always,
4260            boolean removeMatches, boolean debug, int userId) {
4261        if (!sUserManager.exists(userId)) return null;
4262        // writer
4263        synchronized (mPackages) {
4264            if (intent.getSelector() != null) {
4265                intent = intent.getSelector();
4266            }
4267            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4268
4269            // Try to find a matching persistent preferred activity.
4270            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4271                    debug, userId);
4272
4273            // If a persistent preferred activity matched, use it.
4274            if (pri != null) {
4275                return pri;
4276            }
4277
4278            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4279            // Get the list of preferred activities that handle the intent
4280            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4281            List<PreferredActivity> prefs = pir != null
4282                    ? pir.queryIntent(intent, resolvedType,
4283                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4284                    : null;
4285            if (prefs != null && prefs.size() > 0) {
4286                boolean changed = false;
4287                try {
4288                    // First figure out how good the original match set is.
4289                    // We will only allow preferred activities that came
4290                    // from the same match quality.
4291                    int match = 0;
4292
4293                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4294
4295                    final int N = query.size();
4296                    for (int j=0; j<N; j++) {
4297                        final ResolveInfo ri = query.get(j);
4298                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4299                                + ": 0x" + Integer.toHexString(match));
4300                        if (ri.match > match) {
4301                            match = ri.match;
4302                        }
4303                    }
4304
4305                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4306                            + Integer.toHexString(match));
4307
4308                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4309                    final int M = prefs.size();
4310                    for (int i=0; i<M; i++) {
4311                        final PreferredActivity pa = prefs.get(i);
4312                        if (DEBUG_PREFERRED || debug) {
4313                            Slog.v(TAG, "Checking PreferredActivity ds="
4314                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4315                                    + "\n  component=" + pa.mPref.mComponent);
4316                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4317                        }
4318                        if (pa.mPref.mMatch != match) {
4319                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4320                                    + Integer.toHexString(pa.mPref.mMatch));
4321                            continue;
4322                        }
4323                        // If it's not an "always" type preferred activity and that's what we're
4324                        // looking for, skip it.
4325                        if (always && !pa.mPref.mAlways) {
4326                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4327                            continue;
4328                        }
4329                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4330                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4331                        if (DEBUG_PREFERRED || debug) {
4332                            Slog.v(TAG, "Found preferred activity:");
4333                            if (ai != null) {
4334                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4335                            } else {
4336                                Slog.v(TAG, "  null");
4337                            }
4338                        }
4339                        if (ai == null) {
4340                            // This previously registered preferred activity
4341                            // component is no longer known.  Most likely an update
4342                            // to the app was installed and in the new version this
4343                            // component no longer exists.  Clean it up by removing
4344                            // it from the preferred activities list, and skip it.
4345                            Slog.w(TAG, "Removing dangling preferred activity: "
4346                                    + pa.mPref.mComponent);
4347                            pir.removeFilter(pa);
4348                            changed = true;
4349                            continue;
4350                        }
4351                        for (int j=0; j<N; j++) {
4352                            final ResolveInfo ri = query.get(j);
4353                            if (!ri.activityInfo.applicationInfo.packageName
4354                                    .equals(ai.applicationInfo.packageName)) {
4355                                continue;
4356                            }
4357                            if (!ri.activityInfo.name.equals(ai.name)) {
4358                                continue;
4359                            }
4360
4361                            if (removeMatches) {
4362                                pir.removeFilter(pa);
4363                                changed = true;
4364                                if (DEBUG_PREFERRED) {
4365                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4366                                }
4367                                break;
4368                            }
4369
4370                            // Okay we found a previously set preferred or last chosen app.
4371                            // If the result set is different from when this
4372                            // was created, we need to clear it and re-ask the
4373                            // user their preference, if we're looking for an "always" type entry.
4374                            if (always && !pa.mPref.sameSet(query)) {
4375                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4376                                        + intent + " type " + resolvedType);
4377                                if (DEBUG_PREFERRED) {
4378                                    Slog.v(TAG, "Removing preferred activity since set changed "
4379                                            + pa.mPref.mComponent);
4380                                }
4381                                pir.removeFilter(pa);
4382                                // Re-add the filter as a "last chosen" entry (!always)
4383                                PreferredActivity lastChosen = new PreferredActivity(
4384                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4385                                pir.addFilter(lastChosen);
4386                                changed = true;
4387                                return null;
4388                            }
4389
4390                            // Yay! Either the set matched or we're looking for the last chosen
4391                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4392                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4393                            return ri;
4394                        }
4395                    }
4396                } finally {
4397                    if (changed) {
4398                        if (DEBUG_PREFERRED) {
4399                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4400                        }
4401                        scheduleWritePackageRestrictionsLocked(userId);
4402                    }
4403                }
4404            }
4405        }
4406        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4407        return null;
4408    }
4409
4410    /*
4411     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4412     */
4413    @Override
4414    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4415            int targetUserId) {
4416        mContext.enforceCallingOrSelfPermission(
4417                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4418        List<CrossProfileIntentFilter> matches =
4419                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4420        if (matches != null) {
4421            int size = matches.size();
4422            for (int i = 0; i < size; i++) {
4423                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4424            }
4425        }
4426        if (hasWebURI(intent)) {
4427            // cross-profile app linking works only towards the parent.
4428            final UserInfo parent = getProfileParent(sourceUserId);
4429            synchronized(mPackages) {
4430                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4431                        intent, resolvedType, 0, sourceUserId, parent.id);
4432                return xpDomainInfo != null;
4433            }
4434        }
4435        return false;
4436    }
4437
4438    private UserInfo getProfileParent(int userId) {
4439        final long identity = Binder.clearCallingIdentity();
4440        try {
4441            return sUserManager.getProfileParent(userId);
4442        } finally {
4443            Binder.restoreCallingIdentity(identity);
4444        }
4445    }
4446
4447    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4448            String resolvedType, int userId) {
4449        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4450        if (resolver != null) {
4451            return resolver.queryIntent(intent, resolvedType, false, userId);
4452        }
4453        return null;
4454    }
4455
4456    @Override
4457    public List<ResolveInfo> queryIntentActivities(Intent intent,
4458            String resolvedType, int flags, int userId) {
4459        if (!sUserManager.exists(userId)) return Collections.emptyList();
4460        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4461        ComponentName comp = intent.getComponent();
4462        if (comp == null) {
4463            if (intent.getSelector() != null) {
4464                intent = intent.getSelector();
4465                comp = intent.getComponent();
4466            }
4467        }
4468
4469        if (comp != null) {
4470            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4471            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4472            if (ai != null) {
4473                final ResolveInfo ri = new ResolveInfo();
4474                ri.activityInfo = ai;
4475                list.add(ri);
4476            }
4477            return list;
4478        }
4479
4480        // reader
4481        synchronized (mPackages) {
4482            final String pkgName = intent.getPackage();
4483            if (pkgName == null) {
4484                List<CrossProfileIntentFilter> matchingFilters =
4485                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4486                // Check for results that need to skip the current profile.
4487                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4488                        resolvedType, flags, userId);
4489                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4490                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4491                    result.add(xpResolveInfo);
4492                    return filterIfNotPrimaryUser(result, userId);
4493                }
4494
4495                // Check for results in the current profile.
4496                List<ResolveInfo> result = mActivities.queryIntent(
4497                        intent, resolvedType, flags, userId);
4498
4499                // Check for cross profile results.
4500                xpResolveInfo = queryCrossProfileIntents(
4501                        matchingFilters, intent, resolvedType, flags, userId);
4502                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4503                    result.add(xpResolveInfo);
4504                    Collections.sort(result, mResolvePrioritySorter);
4505                }
4506                result = filterIfNotPrimaryUser(result, userId);
4507                if (hasWebURI(intent)) {
4508                    CrossProfileDomainInfo xpDomainInfo = null;
4509                    final UserInfo parent = getProfileParent(userId);
4510                    if (parent != null) {
4511                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4512                                flags, userId, parent.id);
4513                    }
4514                    if (xpDomainInfo != null) {
4515                        if (xpResolveInfo != null) {
4516                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4517                            // in the result.
4518                            result.remove(xpResolveInfo);
4519                        }
4520                        if (result.size() == 0) {
4521                            result.add(xpDomainInfo.resolveInfo);
4522                            return result;
4523                        }
4524                    } else if (result.size() <= 1) {
4525                        return result;
4526                    }
4527                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4528                            xpDomainInfo, userId);
4529                    Collections.sort(result, mResolvePrioritySorter);
4530                }
4531                return result;
4532            }
4533            final PackageParser.Package pkg = mPackages.get(pkgName);
4534            if (pkg != null) {
4535                return filterIfNotPrimaryUser(
4536                        mActivities.queryIntentForPackage(
4537                                intent, resolvedType, flags, pkg.activities, userId),
4538                        userId);
4539            }
4540            return new ArrayList<ResolveInfo>();
4541        }
4542    }
4543
4544    private static class CrossProfileDomainInfo {
4545        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4546        ResolveInfo resolveInfo;
4547        /* Best domain verification status of the activities found in the other profile */
4548        int bestDomainVerificationStatus;
4549    }
4550
4551    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4552            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4553        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4554                sourceUserId)) {
4555            return null;
4556        }
4557        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4558                resolvedType, flags, parentUserId);
4559
4560        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4561            return null;
4562        }
4563        CrossProfileDomainInfo result = null;
4564        int size = resultTargetUser.size();
4565        for (int i = 0; i < size; i++) {
4566            ResolveInfo riTargetUser = resultTargetUser.get(i);
4567            // Intent filter verification is only for filters that specify a host. So don't return
4568            // those that handle all web uris.
4569            if (riTargetUser.handleAllWebDataURI) {
4570                continue;
4571            }
4572            String packageName = riTargetUser.activityInfo.packageName;
4573            PackageSetting ps = mSettings.mPackages.get(packageName);
4574            if (ps == null) {
4575                continue;
4576            }
4577            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4578            int status = (int)(verificationState >> 32);
4579            if (result == null) {
4580                result = new CrossProfileDomainInfo();
4581                result.resolveInfo =
4582                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4583                result.bestDomainVerificationStatus = status;
4584            } else {
4585                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4586                        result.bestDomainVerificationStatus);
4587            }
4588        }
4589        // Don't consider matches with status NEVER across profiles.
4590        if (result != null && result.bestDomainVerificationStatus
4591                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4592            return null;
4593        }
4594        return result;
4595    }
4596
4597    /**
4598     * Verification statuses are ordered from the worse to the best, except for
4599     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4600     */
4601    private int bestDomainVerificationStatus(int status1, int status2) {
4602        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4603            return status2;
4604        }
4605        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4606            return status1;
4607        }
4608        return (int) MathUtils.max(status1, status2);
4609    }
4610
4611    private boolean isUserEnabled(int userId) {
4612        long callingId = Binder.clearCallingIdentity();
4613        try {
4614            UserInfo userInfo = sUserManager.getUserInfo(userId);
4615            return userInfo != null && userInfo.isEnabled();
4616        } finally {
4617            Binder.restoreCallingIdentity(callingId);
4618        }
4619    }
4620
4621    /**
4622     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4623     *
4624     * @return filtered list
4625     */
4626    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4627        if (userId == UserHandle.USER_OWNER) {
4628            return resolveInfos;
4629        }
4630        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4631            ResolveInfo info = resolveInfos.get(i);
4632            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4633                resolveInfos.remove(i);
4634            }
4635        }
4636        return resolveInfos;
4637    }
4638
4639    private static boolean hasWebURI(Intent intent) {
4640        if (intent.getData() == null) {
4641            return false;
4642        }
4643        final String scheme = intent.getScheme();
4644        if (TextUtils.isEmpty(scheme)) {
4645            return false;
4646        }
4647        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4648    }
4649
4650    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4651            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4652            int userId) {
4653        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4654
4655        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4656            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4657                    candidates.size());
4658        }
4659
4660        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4661        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4662        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4663        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4664        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4665
4666        synchronized (mPackages) {
4667            final int count = candidates.size();
4668            // First, try to use linked apps. Partition the candidates into four lists:
4669            // one for the final results, one for the "do not use ever", one for "undefined status"
4670            // and finally one for "browser app type".
4671            for (int n=0; n<count; n++) {
4672                ResolveInfo info = candidates.get(n);
4673                String packageName = info.activityInfo.packageName;
4674                PackageSetting ps = mSettings.mPackages.get(packageName);
4675                if (ps != null) {
4676                    // Add to the special match all list (Browser use case)
4677                    if (info.handleAllWebDataURI) {
4678                        matchAllList.add(info);
4679                        continue;
4680                    }
4681                    // Try to get the status from User settings first
4682                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4683                    int status = (int)(packedStatus >> 32);
4684                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4685                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4686                        if (DEBUG_DOMAIN_VERIFICATION) {
4687                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4688                                    + " : linkgen=" + linkGeneration);
4689                        }
4690                        // Use link-enabled generation as preferredOrder, i.e.
4691                        // prefer newly-enabled over earlier-enabled.
4692                        info.preferredOrder = linkGeneration;
4693                        alwaysList.add(info);
4694                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4695                        if (DEBUG_DOMAIN_VERIFICATION) {
4696                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4697                        }
4698                        neverList.add(info);
4699                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4700                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4701                        if (DEBUG_DOMAIN_VERIFICATION) {
4702                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4703                        }
4704                        undefinedList.add(info);
4705                    }
4706                }
4707            }
4708            // First try to add the "always" resolution(s) for the current user, if any
4709            if (alwaysList.size() > 0) {
4710                result.addAll(alwaysList);
4711            // if there is an "always" for the parent user, add it.
4712            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4713                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4714                result.add(xpDomainInfo.resolveInfo);
4715            } else {
4716                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4717                result.addAll(undefinedList);
4718                if (xpDomainInfo != null && (
4719                        xpDomainInfo.bestDomainVerificationStatus
4720                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4721                        || xpDomainInfo.bestDomainVerificationStatus
4722                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4723                    result.add(xpDomainInfo.resolveInfo);
4724                }
4725                // Also add Browsers (all of them or only the default one)
4726                if ((matchFlags & MATCH_ALL) != 0) {
4727                    result.addAll(matchAllList);
4728                } else {
4729                    // Browser/generic handling case.  If there's a default browser, go straight
4730                    // to that (but only if there is no other higher-priority match).
4731                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
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, null);
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                params.grantedRuntimePermissions);
9481        mHandler.sendMessage(msg);
9482    }
9483
9484    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9485        Bundle extras = new Bundle(1);
9486        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9487
9488        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9489                packageName, extras, null, null, new int[] {userId});
9490        try {
9491            IActivityManager am = ActivityManagerNative.getDefault();
9492            final boolean isSystem =
9493                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9494            if (isSystem && am.isUserRunning(userId, false)) {
9495                // The just-installed/enabled app is bundled on the system, so presumed
9496                // to be able to run automatically without needing an explicit launch.
9497                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9498                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9499                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9500                        .setPackage(packageName);
9501                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9502                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9503            }
9504        } catch (RemoteException e) {
9505            // shouldn't happen
9506            Slog.w(TAG, "Unable to bootstrap installed package", e);
9507        }
9508    }
9509
9510    @Override
9511    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9512            int userId) {
9513        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9514        PackageSetting pkgSetting;
9515        final int uid = Binder.getCallingUid();
9516        enforceCrossUserPermission(uid, userId, true, true,
9517                "setApplicationHiddenSetting for user " + userId);
9518
9519        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9520            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9521            return false;
9522        }
9523
9524        long callingId = Binder.clearCallingIdentity();
9525        try {
9526            boolean sendAdded = false;
9527            boolean sendRemoved = false;
9528            // writer
9529            synchronized (mPackages) {
9530                pkgSetting = mSettings.mPackages.get(packageName);
9531                if (pkgSetting == null) {
9532                    return false;
9533                }
9534                if (pkgSetting.getHidden(userId) != hidden) {
9535                    pkgSetting.setHidden(hidden, userId);
9536                    mSettings.writePackageRestrictionsLPr(userId);
9537                    if (hidden) {
9538                        sendRemoved = true;
9539                    } else {
9540                        sendAdded = true;
9541                    }
9542                }
9543            }
9544            if (sendAdded) {
9545                sendPackageAddedForUser(packageName, pkgSetting, userId);
9546                return true;
9547            }
9548            if (sendRemoved) {
9549                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9550                        "hiding pkg");
9551                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9552            }
9553        } finally {
9554            Binder.restoreCallingIdentity(callingId);
9555        }
9556        return false;
9557    }
9558
9559    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9560            int userId) {
9561        final PackageRemovedInfo info = new PackageRemovedInfo();
9562        info.removedPackage = packageName;
9563        info.removedUsers = new int[] {userId};
9564        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9565        info.sendBroadcast(false, false, false);
9566    }
9567
9568    /**
9569     * Returns true if application is not found or there was an error. Otherwise it returns
9570     * the hidden state of the package for the given user.
9571     */
9572    @Override
9573    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9574        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9575        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9576                false, "getApplicationHidden for user " + userId);
9577        PackageSetting pkgSetting;
9578        long callingId = Binder.clearCallingIdentity();
9579        try {
9580            // writer
9581            synchronized (mPackages) {
9582                pkgSetting = mSettings.mPackages.get(packageName);
9583                if (pkgSetting == null) {
9584                    return true;
9585                }
9586                return pkgSetting.getHidden(userId);
9587            }
9588        } finally {
9589            Binder.restoreCallingIdentity(callingId);
9590        }
9591    }
9592
9593    /**
9594     * @hide
9595     */
9596    @Override
9597    public int installExistingPackageAsUser(String packageName, int userId) {
9598        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9599                null);
9600        PackageSetting pkgSetting;
9601        final int uid = Binder.getCallingUid();
9602        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9603                + userId);
9604        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9605            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9606        }
9607
9608        long callingId = Binder.clearCallingIdentity();
9609        try {
9610            boolean sendAdded = false;
9611
9612            // writer
9613            synchronized (mPackages) {
9614                pkgSetting = mSettings.mPackages.get(packageName);
9615                if (pkgSetting == null) {
9616                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9617                }
9618                if (!pkgSetting.getInstalled(userId)) {
9619                    pkgSetting.setInstalled(true, userId);
9620                    pkgSetting.setHidden(false, userId);
9621                    mSettings.writePackageRestrictionsLPr(userId);
9622                    sendAdded = true;
9623                }
9624            }
9625
9626            if (sendAdded) {
9627                sendPackageAddedForUser(packageName, pkgSetting, userId);
9628            }
9629        } finally {
9630            Binder.restoreCallingIdentity(callingId);
9631        }
9632
9633        return PackageManager.INSTALL_SUCCEEDED;
9634    }
9635
9636    boolean isUserRestricted(int userId, String restrictionKey) {
9637        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9638        if (restrictions.getBoolean(restrictionKey, false)) {
9639            Log.w(TAG, "User is restricted: " + restrictionKey);
9640            return true;
9641        }
9642        return false;
9643    }
9644
9645    @Override
9646    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9647        mContext.enforceCallingOrSelfPermission(
9648                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9649                "Only package verification agents can verify applications");
9650
9651        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9652        final PackageVerificationResponse response = new PackageVerificationResponse(
9653                verificationCode, Binder.getCallingUid());
9654        msg.arg1 = id;
9655        msg.obj = response;
9656        mHandler.sendMessage(msg);
9657    }
9658
9659    @Override
9660    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9661            long millisecondsToDelay) {
9662        mContext.enforceCallingOrSelfPermission(
9663                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9664                "Only package verification agents can extend verification timeouts");
9665
9666        final PackageVerificationState state = mPendingVerification.get(id);
9667        final PackageVerificationResponse response = new PackageVerificationResponse(
9668                verificationCodeAtTimeout, Binder.getCallingUid());
9669
9670        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9671            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9672        }
9673        if (millisecondsToDelay < 0) {
9674            millisecondsToDelay = 0;
9675        }
9676        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9677                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9678            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9679        }
9680
9681        if ((state != null) && !state.timeoutExtended()) {
9682            state.extendTimeout();
9683
9684            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9685            msg.arg1 = id;
9686            msg.obj = response;
9687            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9688        }
9689    }
9690
9691    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9692            int verificationCode, UserHandle user) {
9693        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9694        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9695        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9696        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9697        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9698
9699        mContext.sendBroadcastAsUser(intent, user,
9700                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9701    }
9702
9703    private ComponentName matchComponentForVerifier(String packageName,
9704            List<ResolveInfo> receivers) {
9705        ActivityInfo targetReceiver = null;
9706
9707        final int NR = receivers.size();
9708        for (int i = 0; i < NR; i++) {
9709            final ResolveInfo info = receivers.get(i);
9710            if (info.activityInfo == null) {
9711                continue;
9712            }
9713
9714            if (packageName.equals(info.activityInfo.packageName)) {
9715                targetReceiver = info.activityInfo;
9716                break;
9717            }
9718        }
9719
9720        if (targetReceiver == null) {
9721            return null;
9722        }
9723
9724        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9725    }
9726
9727    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9728            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9729        if (pkgInfo.verifiers.length == 0) {
9730            return null;
9731        }
9732
9733        final int N = pkgInfo.verifiers.length;
9734        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9735        for (int i = 0; i < N; i++) {
9736            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9737
9738            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9739                    receivers);
9740            if (comp == null) {
9741                continue;
9742            }
9743
9744            final int verifierUid = getUidForVerifier(verifierInfo);
9745            if (verifierUid == -1) {
9746                continue;
9747            }
9748
9749            if (DEBUG_VERIFY) {
9750                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9751                        + " with the correct signature");
9752            }
9753            sufficientVerifiers.add(comp);
9754            verificationState.addSufficientVerifier(verifierUid);
9755        }
9756
9757        return sufficientVerifiers;
9758    }
9759
9760    private int getUidForVerifier(VerifierInfo verifierInfo) {
9761        synchronized (mPackages) {
9762            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9763            if (pkg == null) {
9764                return -1;
9765            } else if (pkg.mSignatures.length != 1) {
9766                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9767                        + " has more than one signature; ignoring");
9768                return -1;
9769            }
9770
9771            /*
9772             * If the public key of the package's signature does not match
9773             * our expected public key, then this is a different package and
9774             * we should skip.
9775             */
9776
9777            final byte[] expectedPublicKey;
9778            try {
9779                final Signature verifierSig = pkg.mSignatures[0];
9780                final PublicKey publicKey = verifierSig.getPublicKey();
9781                expectedPublicKey = publicKey.getEncoded();
9782            } catch (CertificateException e) {
9783                return -1;
9784            }
9785
9786            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9787
9788            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9789                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9790                        + " does not have the expected public key; ignoring");
9791                return -1;
9792            }
9793
9794            return pkg.applicationInfo.uid;
9795        }
9796    }
9797
9798    @Override
9799    public void finishPackageInstall(int token) {
9800        enforceSystemOrRoot("Only the system is allowed to finish installs");
9801
9802        if (DEBUG_INSTALL) {
9803            Slog.v(TAG, "BM finishing package install for " + token);
9804        }
9805
9806        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9807        mHandler.sendMessage(msg);
9808    }
9809
9810    /**
9811     * Get the verification agent timeout.
9812     *
9813     * @return verification timeout in milliseconds
9814     */
9815    private long getVerificationTimeout() {
9816        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9817                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9818                DEFAULT_VERIFICATION_TIMEOUT);
9819    }
9820
9821    /**
9822     * Get the default verification agent response code.
9823     *
9824     * @return default verification response code
9825     */
9826    private int getDefaultVerificationResponse() {
9827        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9828                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9829                DEFAULT_VERIFICATION_RESPONSE);
9830    }
9831
9832    /**
9833     * Check whether or not package verification has been enabled.
9834     *
9835     * @return true if verification should be performed
9836     */
9837    private boolean isVerificationEnabled(int userId, int installFlags) {
9838        if (!DEFAULT_VERIFY_ENABLE) {
9839            return false;
9840        }
9841
9842        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9843
9844        // Check if installing from ADB
9845        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9846            // Do not run verification in a test harness environment
9847            if (ActivityManager.isRunningInTestHarness()) {
9848                return false;
9849            }
9850            if (ensureVerifyAppsEnabled) {
9851                return true;
9852            }
9853            // Check if the developer does not want package verification for ADB installs
9854            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9855                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9856                return false;
9857            }
9858        }
9859
9860        if (ensureVerifyAppsEnabled) {
9861            return true;
9862        }
9863
9864        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9865                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9866    }
9867
9868    @Override
9869    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9870            throws RemoteException {
9871        mContext.enforceCallingOrSelfPermission(
9872                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9873                "Only intentfilter verification agents can verify applications");
9874
9875        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9876        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9877                Binder.getCallingUid(), verificationCode, failedDomains);
9878        msg.arg1 = id;
9879        msg.obj = response;
9880        mHandler.sendMessage(msg);
9881    }
9882
9883    @Override
9884    public int getIntentVerificationStatus(String packageName, int userId) {
9885        synchronized (mPackages) {
9886            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9887        }
9888    }
9889
9890    @Override
9891    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9892        mContext.enforceCallingOrSelfPermission(
9893                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9894
9895        boolean result = false;
9896        synchronized (mPackages) {
9897            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9898        }
9899        if (result) {
9900            scheduleWritePackageRestrictionsLocked(userId);
9901        }
9902        return result;
9903    }
9904
9905    @Override
9906    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9907        synchronized (mPackages) {
9908            return mSettings.getIntentFilterVerificationsLPr(packageName);
9909        }
9910    }
9911
9912    @Override
9913    public List<IntentFilter> getAllIntentFilters(String packageName) {
9914        if (TextUtils.isEmpty(packageName)) {
9915            return Collections.<IntentFilter>emptyList();
9916        }
9917        synchronized (mPackages) {
9918            PackageParser.Package pkg = mPackages.get(packageName);
9919            if (pkg == null || pkg.activities == null) {
9920                return Collections.<IntentFilter>emptyList();
9921            }
9922            final int count = pkg.activities.size();
9923            ArrayList<IntentFilter> result = new ArrayList<>();
9924            for (int n=0; n<count; n++) {
9925                PackageParser.Activity activity = pkg.activities.get(n);
9926                if (activity.intents != null || activity.intents.size() > 0) {
9927                    result.addAll(activity.intents);
9928                }
9929            }
9930            return result;
9931        }
9932    }
9933
9934    @Override
9935    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9936        mContext.enforceCallingOrSelfPermission(
9937                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9938
9939        synchronized (mPackages) {
9940            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9941            if (packageName != null) {
9942                result |= updateIntentVerificationStatus(packageName,
9943                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9944                        userId);
9945                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9946                        packageName, userId);
9947            }
9948            return result;
9949        }
9950    }
9951
9952    @Override
9953    public String getDefaultBrowserPackageName(int userId) {
9954        synchronized (mPackages) {
9955            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9956        }
9957    }
9958
9959    /**
9960     * Get the "allow unknown sources" setting.
9961     *
9962     * @return the current "allow unknown sources" setting
9963     */
9964    private int getUnknownSourcesSettings() {
9965        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9966                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9967                -1);
9968    }
9969
9970    @Override
9971    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9972        final int uid = Binder.getCallingUid();
9973        // writer
9974        synchronized (mPackages) {
9975            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9976            if (targetPackageSetting == null) {
9977                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9978            }
9979
9980            PackageSetting installerPackageSetting;
9981            if (installerPackageName != null) {
9982                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9983                if (installerPackageSetting == null) {
9984                    throw new IllegalArgumentException("Unknown installer package: "
9985                            + installerPackageName);
9986                }
9987            } else {
9988                installerPackageSetting = null;
9989            }
9990
9991            Signature[] callerSignature;
9992            Object obj = mSettings.getUserIdLPr(uid);
9993            if (obj != null) {
9994                if (obj instanceof SharedUserSetting) {
9995                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9996                } else if (obj instanceof PackageSetting) {
9997                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9998                } else {
9999                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10000                }
10001            } else {
10002                throw new SecurityException("Unknown calling uid " + uid);
10003            }
10004
10005            // Verify: can't set installerPackageName to a package that is
10006            // not signed with the same cert as the caller.
10007            if (installerPackageSetting != null) {
10008                if (compareSignatures(callerSignature,
10009                        installerPackageSetting.signatures.mSignatures)
10010                        != PackageManager.SIGNATURE_MATCH) {
10011                    throw new SecurityException(
10012                            "Caller does not have same cert as new installer package "
10013                            + installerPackageName);
10014                }
10015            }
10016
10017            // Verify: if target already has an installer package, it must
10018            // be signed with the same cert as the caller.
10019            if (targetPackageSetting.installerPackageName != null) {
10020                PackageSetting setting = mSettings.mPackages.get(
10021                        targetPackageSetting.installerPackageName);
10022                // If the currently set package isn't valid, then it's always
10023                // okay to change it.
10024                if (setting != null) {
10025                    if (compareSignatures(callerSignature,
10026                            setting.signatures.mSignatures)
10027                            != PackageManager.SIGNATURE_MATCH) {
10028                        throw new SecurityException(
10029                                "Caller does not have same cert as old installer package "
10030                                + targetPackageSetting.installerPackageName);
10031                    }
10032                }
10033            }
10034
10035            // Okay!
10036            targetPackageSetting.installerPackageName = installerPackageName;
10037            scheduleWriteSettingsLocked();
10038        }
10039    }
10040
10041    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10042        // Queue up an async operation since the package installation may take a little while.
10043        mHandler.post(new Runnable() {
10044            public void run() {
10045                mHandler.removeCallbacks(this);
10046                 // Result object to be returned
10047                PackageInstalledInfo res = new PackageInstalledInfo();
10048                res.returnCode = currentStatus;
10049                res.uid = -1;
10050                res.pkg = null;
10051                res.removedInfo = new PackageRemovedInfo();
10052                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10053                    args.doPreInstall(res.returnCode);
10054                    synchronized (mInstallLock) {
10055                        installPackageLI(args, res);
10056                    }
10057                    args.doPostInstall(res.returnCode, res.uid);
10058                }
10059
10060                // A restore should be performed at this point if (a) the install
10061                // succeeded, (b) the operation is not an update, and (c) the new
10062                // package has not opted out of backup participation.
10063                final boolean update = res.removedInfo.removedPackage != null;
10064                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10065                boolean doRestore = !update
10066                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10067
10068                // Set up the post-install work request bookkeeping.  This will be used
10069                // and cleaned up by the post-install event handling regardless of whether
10070                // there's a restore pass performed.  Token values are >= 1.
10071                int token;
10072                if (mNextInstallToken < 0) mNextInstallToken = 1;
10073                token = mNextInstallToken++;
10074
10075                PostInstallData data = new PostInstallData(args, res);
10076                mRunningInstalls.put(token, data);
10077                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10078
10079                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10080                    // Pass responsibility to the Backup Manager.  It will perform a
10081                    // restore if appropriate, then pass responsibility back to the
10082                    // Package Manager to run the post-install observer callbacks
10083                    // and broadcasts.
10084                    IBackupManager bm = IBackupManager.Stub.asInterface(
10085                            ServiceManager.getService(Context.BACKUP_SERVICE));
10086                    if (bm != null) {
10087                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10088                                + " to BM for possible restore");
10089                        try {
10090                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10091                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10092                            } else {
10093                                doRestore = false;
10094                            }
10095                        } catch (RemoteException e) {
10096                            // can't happen; the backup manager is local
10097                        } catch (Exception e) {
10098                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10099                            doRestore = false;
10100                        }
10101                    } else {
10102                        Slog.e(TAG, "Backup Manager not found!");
10103                        doRestore = false;
10104                    }
10105                }
10106
10107                if (!doRestore) {
10108                    // No restore possible, or the Backup Manager was mysteriously not
10109                    // available -- just fire the post-install work request directly.
10110                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10111                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10112                    mHandler.sendMessage(msg);
10113                }
10114            }
10115        });
10116    }
10117
10118    private abstract class HandlerParams {
10119        private static final int MAX_RETRIES = 4;
10120
10121        /**
10122         * Number of times startCopy() has been attempted and had a non-fatal
10123         * error.
10124         */
10125        private int mRetries = 0;
10126
10127        /** User handle for the user requesting the information or installation. */
10128        private final UserHandle mUser;
10129
10130        HandlerParams(UserHandle user) {
10131            mUser = user;
10132        }
10133
10134        UserHandle getUser() {
10135            return mUser;
10136        }
10137
10138        final boolean startCopy() {
10139            boolean res;
10140            try {
10141                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10142
10143                if (++mRetries > MAX_RETRIES) {
10144                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10145                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10146                    handleServiceError();
10147                    return false;
10148                } else {
10149                    handleStartCopy();
10150                    res = true;
10151                }
10152            } catch (RemoteException e) {
10153                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10154                mHandler.sendEmptyMessage(MCS_RECONNECT);
10155                res = false;
10156            }
10157            handleReturnCode();
10158            return res;
10159        }
10160
10161        final void serviceError() {
10162            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10163            handleServiceError();
10164            handleReturnCode();
10165        }
10166
10167        abstract void handleStartCopy() throws RemoteException;
10168        abstract void handleServiceError();
10169        abstract void handleReturnCode();
10170    }
10171
10172    class MeasureParams extends HandlerParams {
10173        private final PackageStats mStats;
10174        private boolean mSuccess;
10175
10176        private final IPackageStatsObserver mObserver;
10177
10178        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10179            super(new UserHandle(stats.userHandle));
10180            mObserver = observer;
10181            mStats = stats;
10182        }
10183
10184        @Override
10185        public String toString() {
10186            return "MeasureParams{"
10187                + Integer.toHexString(System.identityHashCode(this))
10188                + " " + mStats.packageName + "}";
10189        }
10190
10191        @Override
10192        void handleStartCopy() throws RemoteException {
10193            synchronized (mInstallLock) {
10194                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10195            }
10196
10197            if (mSuccess) {
10198                final boolean mounted;
10199                if (Environment.isExternalStorageEmulated()) {
10200                    mounted = true;
10201                } else {
10202                    final String status = Environment.getExternalStorageState();
10203                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10204                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10205                }
10206
10207                if (mounted) {
10208                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10209
10210                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10211                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10212
10213                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10214                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10215
10216                    // Always subtract cache size, since it's a subdirectory
10217                    mStats.externalDataSize -= mStats.externalCacheSize;
10218
10219                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10220                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10221
10222                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10223                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10224                }
10225            }
10226        }
10227
10228        @Override
10229        void handleReturnCode() {
10230            if (mObserver != null) {
10231                try {
10232                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10233                } catch (RemoteException e) {
10234                    Slog.i(TAG, "Observer no longer exists.");
10235                }
10236            }
10237        }
10238
10239        @Override
10240        void handleServiceError() {
10241            Slog.e(TAG, "Could not measure application " + mStats.packageName
10242                            + " external storage");
10243        }
10244    }
10245
10246    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10247            throws RemoteException {
10248        long result = 0;
10249        for (File path : paths) {
10250            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10251        }
10252        return result;
10253    }
10254
10255    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10256        for (File path : paths) {
10257            try {
10258                mcs.clearDirectory(path.getAbsolutePath());
10259            } catch (RemoteException e) {
10260            }
10261        }
10262    }
10263
10264    static class OriginInfo {
10265        /**
10266         * Location where install is coming from, before it has been
10267         * copied/renamed into place. This could be a single monolithic APK
10268         * file, or a cluster directory. This location may be untrusted.
10269         */
10270        final File file;
10271        final String cid;
10272
10273        /**
10274         * Flag indicating that {@link #file} or {@link #cid} has already been
10275         * staged, meaning downstream users don't need to defensively copy the
10276         * contents.
10277         */
10278        final boolean staged;
10279
10280        /**
10281         * Flag indicating that {@link #file} or {@link #cid} is an already
10282         * installed app that is being moved.
10283         */
10284        final boolean existing;
10285
10286        final String resolvedPath;
10287        final File resolvedFile;
10288
10289        static OriginInfo fromNothing() {
10290            return new OriginInfo(null, null, false, false);
10291        }
10292
10293        static OriginInfo fromUntrustedFile(File file) {
10294            return new OriginInfo(file, null, false, false);
10295        }
10296
10297        static OriginInfo fromExistingFile(File file) {
10298            return new OriginInfo(file, null, false, true);
10299        }
10300
10301        static OriginInfo fromStagedFile(File file) {
10302            return new OriginInfo(file, null, true, false);
10303        }
10304
10305        static OriginInfo fromStagedContainer(String cid) {
10306            return new OriginInfo(null, cid, true, false);
10307        }
10308
10309        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10310            this.file = file;
10311            this.cid = cid;
10312            this.staged = staged;
10313            this.existing = existing;
10314
10315            if (cid != null) {
10316                resolvedPath = PackageHelper.getSdDir(cid);
10317                resolvedFile = new File(resolvedPath);
10318            } else if (file != null) {
10319                resolvedPath = file.getAbsolutePath();
10320                resolvedFile = file;
10321            } else {
10322                resolvedPath = null;
10323                resolvedFile = null;
10324            }
10325        }
10326    }
10327
10328    class MoveInfo {
10329        final int moveId;
10330        final String fromUuid;
10331        final String toUuid;
10332        final String packageName;
10333        final String dataAppName;
10334        final int appId;
10335        final String seinfo;
10336
10337        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10338                String dataAppName, int appId, String seinfo) {
10339            this.moveId = moveId;
10340            this.fromUuid = fromUuid;
10341            this.toUuid = toUuid;
10342            this.packageName = packageName;
10343            this.dataAppName = dataAppName;
10344            this.appId = appId;
10345            this.seinfo = seinfo;
10346        }
10347    }
10348
10349    class InstallParams extends HandlerParams {
10350        final OriginInfo origin;
10351        final MoveInfo move;
10352        final IPackageInstallObserver2 observer;
10353        int installFlags;
10354        final String installerPackageName;
10355        final String volumeUuid;
10356        final VerificationParams verificationParams;
10357        private InstallArgs mArgs;
10358        private int mRet;
10359        final String packageAbiOverride;
10360        final String[] grantedRuntimePermissions;
10361
10362
10363        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10364                int installFlags, String installerPackageName, String volumeUuid,
10365                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10366                String[] grantedPermissions) {
10367            super(user);
10368            this.origin = origin;
10369            this.move = move;
10370            this.observer = observer;
10371            this.installFlags = installFlags;
10372            this.installerPackageName = installerPackageName;
10373            this.volumeUuid = volumeUuid;
10374            this.verificationParams = verificationParams;
10375            this.packageAbiOverride = packageAbiOverride;
10376            this.grantedRuntimePermissions = grantedPermissions;
10377        }
10378
10379        @Override
10380        public String toString() {
10381            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10382                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10383        }
10384
10385        public ManifestDigest getManifestDigest() {
10386            if (verificationParams == null) {
10387                return null;
10388            }
10389            return verificationParams.getManifestDigest();
10390        }
10391
10392        private int installLocationPolicy(PackageInfoLite pkgLite) {
10393            String packageName = pkgLite.packageName;
10394            int installLocation = pkgLite.installLocation;
10395            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10396            // reader
10397            synchronized (mPackages) {
10398                PackageParser.Package pkg = mPackages.get(packageName);
10399                if (pkg != null) {
10400                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10401                        // Check for downgrading.
10402                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10403                            try {
10404                                checkDowngrade(pkg, pkgLite);
10405                            } catch (PackageManagerException e) {
10406                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10407                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10408                            }
10409                        }
10410                        // Check for updated system application.
10411                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10412                            if (onSd) {
10413                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10414                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10415                            }
10416                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10417                        } else {
10418                            if (onSd) {
10419                                // Install flag overrides everything.
10420                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10421                            }
10422                            // If current upgrade specifies particular preference
10423                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10424                                // Application explicitly specified internal.
10425                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10426                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10427                                // App explictly prefers external. Let policy decide
10428                            } else {
10429                                // Prefer previous location
10430                                if (isExternal(pkg)) {
10431                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10432                                }
10433                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10434                            }
10435                        }
10436                    } else {
10437                        // Invalid install. Return error code
10438                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10439                    }
10440                }
10441            }
10442            // All the special cases have been taken care of.
10443            // Return result based on recommended install location.
10444            if (onSd) {
10445                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10446            }
10447            return pkgLite.recommendedInstallLocation;
10448        }
10449
10450        /*
10451         * Invoke remote method to get package information and install
10452         * location values. Override install location based on default
10453         * policy if needed and then create install arguments based
10454         * on the install location.
10455         */
10456        public void handleStartCopy() throws RemoteException {
10457            int ret = PackageManager.INSTALL_SUCCEEDED;
10458
10459            // If we're already staged, we've firmly committed to an install location
10460            if (origin.staged) {
10461                if (origin.file != null) {
10462                    installFlags |= PackageManager.INSTALL_INTERNAL;
10463                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10464                } else if (origin.cid != null) {
10465                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10466                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10467                } else {
10468                    throw new IllegalStateException("Invalid stage location");
10469                }
10470            }
10471
10472            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10473            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10474
10475            PackageInfoLite pkgLite = null;
10476
10477            if (onInt && onSd) {
10478                // Check if both bits are set.
10479                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10480                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10481            } else {
10482                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10483                        packageAbiOverride);
10484
10485                /*
10486                 * If we have too little free space, try to free cache
10487                 * before giving up.
10488                 */
10489                if (!origin.staged && pkgLite.recommendedInstallLocation
10490                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10491                    // TODO: focus freeing disk space on the target device
10492                    final StorageManager storage = StorageManager.from(mContext);
10493                    final long lowThreshold = storage.getStorageLowBytes(
10494                            Environment.getDataDirectory());
10495
10496                    final long sizeBytes = mContainerService.calculateInstalledSize(
10497                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10498
10499                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10500                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10501                                installFlags, packageAbiOverride);
10502                    }
10503
10504                    /*
10505                     * The cache free must have deleted the file we
10506                     * downloaded to install.
10507                     *
10508                     * TODO: fix the "freeCache" call to not delete
10509                     *       the file we care about.
10510                     */
10511                    if (pkgLite.recommendedInstallLocation
10512                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10513                        pkgLite.recommendedInstallLocation
10514                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10515                    }
10516                }
10517            }
10518
10519            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10520                int loc = pkgLite.recommendedInstallLocation;
10521                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10522                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10523                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10524                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10525                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10526                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10527                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10528                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10529                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10530                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10531                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10532                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10533                } else {
10534                    // Override with defaults if needed.
10535                    loc = installLocationPolicy(pkgLite);
10536                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10537                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10538                    } else if (!onSd && !onInt) {
10539                        // Override install location with flags
10540                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10541                            // Set the flag to install on external media.
10542                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10543                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10544                        } else {
10545                            // Make sure the flag for installing on external
10546                            // media is unset
10547                            installFlags |= PackageManager.INSTALL_INTERNAL;
10548                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10549                        }
10550                    }
10551                }
10552            }
10553
10554            final InstallArgs args = createInstallArgs(this);
10555            mArgs = args;
10556
10557            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10558                 /*
10559                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10560                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10561                 */
10562                int userIdentifier = getUser().getIdentifier();
10563                if (userIdentifier == UserHandle.USER_ALL
10564                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10565                    userIdentifier = UserHandle.USER_OWNER;
10566                }
10567
10568                /*
10569                 * Determine if we have any installed package verifiers. If we
10570                 * do, then we'll defer to them to verify the packages.
10571                 */
10572                final int requiredUid = mRequiredVerifierPackage == null ? -1
10573                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10574                if (!origin.existing && requiredUid != -1
10575                        && isVerificationEnabled(userIdentifier, installFlags)) {
10576                    final Intent verification = new Intent(
10577                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10578                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10579                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10580                            PACKAGE_MIME_TYPE);
10581                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10582
10583                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10584                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10585                            0 /* TODO: Which userId? */);
10586
10587                    if (DEBUG_VERIFY) {
10588                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10589                                + verification.toString() + " with " + pkgLite.verifiers.length
10590                                + " optional verifiers");
10591                    }
10592
10593                    final int verificationId = mPendingVerificationToken++;
10594
10595                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10596
10597                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10598                            installerPackageName);
10599
10600                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10601                            installFlags);
10602
10603                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10604                            pkgLite.packageName);
10605
10606                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10607                            pkgLite.versionCode);
10608
10609                    if (verificationParams != null) {
10610                        if (verificationParams.getVerificationURI() != null) {
10611                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10612                                 verificationParams.getVerificationURI());
10613                        }
10614                        if (verificationParams.getOriginatingURI() != null) {
10615                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10616                                  verificationParams.getOriginatingURI());
10617                        }
10618                        if (verificationParams.getReferrer() != null) {
10619                            verification.putExtra(Intent.EXTRA_REFERRER,
10620                                  verificationParams.getReferrer());
10621                        }
10622                        if (verificationParams.getOriginatingUid() >= 0) {
10623                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10624                                  verificationParams.getOriginatingUid());
10625                        }
10626                        if (verificationParams.getInstallerUid() >= 0) {
10627                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10628                                  verificationParams.getInstallerUid());
10629                        }
10630                    }
10631
10632                    final PackageVerificationState verificationState = new PackageVerificationState(
10633                            requiredUid, args);
10634
10635                    mPendingVerification.append(verificationId, verificationState);
10636
10637                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10638                            receivers, verificationState);
10639
10640                    // Apps installed for "all" users use the device owner to verify the app
10641                    UserHandle verifierUser = getUser();
10642                    if (verifierUser == UserHandle.ALL) {
10643                        verifierUser = UserHandle.OWNER;
10644                    }
10645
10646                    /*
10647                     * If any sufficient verifiers were listed in the package
10648                     * manifest, attempt to ask them.
10649                     */
10650                    if (sufficientVerifiers != null) {
10651                        final int N = sufficientVerifiers.size();
10652                        if (N == 0) {
10653                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10654                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10655                        } else {
10656                            for (int i = 0; i < N; i++) {
10657                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10658
10659                                final Intent sufficientIntent = new Intent(verification);
10660                                sufficientIntent.setComponent(verifierComponent);
10661                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10662                            }
10663                        }
10664                    }
10665
10666                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10667                            mRequiredVerifierPackage, receivers);
10668                    if (ret == PackageManager.INSTALL_SUCCEEDED
10669                            && mRequiredVerifierPackage != null) {
10670                        /*
10671                         * Send the intent to the required verification agent,
10672                         * but only start the verification timeout after the
10673                         * target BroadcastReceivers have run.
10674                         */
10675                        verification.setComponent(requiredVerifierComponent);
10676                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10677                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10678                                new BroadcastReceiver() {
10679                                    @Override
10680                                    public void onReceive(Context context, Intent intent) {
10681                                        final Message msg = mHandler
10682                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10683                                        msg.arg1 = verificationId;
10684                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10685                                    }
10686                                }, null, 0, null, null);
10687
10688                        /*
10689                         * We don't want the copy to proceed until verification
10690                         * succeeds, so null out this field.
10691                         */
10692                        mArgs = null;
10693                    }
10694                } else {
10695                    /*
10696                     * No package verification is enabled, so immediately start
10697                     * the remote call to initiate copy using temporary file.
10698                     */
10699                    ret = args.copyApk(mContainerService, true);
10700                }
10701            }
10702
10703            mRet = ret;
10704        }
10705
10706        @Override
10707        void handleReturnCode() {
10708            // If mArgs is null, then MCS couldn't be reached. When it
10709            // reconnects, it will try again to install. At that point, this
10710            // will succeed.
10711            if (mArgs != null) {
10712                processPendingInstall(mArgs, mRet);
10713            }
10714        }
10715
10716        @Override
10717        void handleServiceError() {
10718            mArgs = createInstallArgs(this);
10719            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10720        }
10721
10722        public boolean isForwardLocked() {
10723            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10724        }
10725    }
10726
10727    /**
10728     * Used during creation of InstallArgs
10729     *
10730     * @param installFlags package installation flags
10731     * @return true if should be installed on external storage
10732     */
10733    private static boolean installOnExternalAsec(int installFlags) {
10734        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10735            return false;
10736        }
10737        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10738            return true;
10739        }
10740        return false;
10741    }
10742
10743    /**
10744     * Used during creation of InstallArgs
10745     *
10746     * @param installFlags package installation flags
10747     * @return true if should be installed as forward locked
10748     */
10749    private static boolean installForwardLocked(int installFlags) {
10750        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10751    }
10752
10753    private InstallArgs createInstallArgs(InstallParams params) {
10754        if (params.move != null) {
10755            return new MoveInstallArgs(params);
10756        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10757            return new AsecInstallArgs(params);
10758        } else {
10759            return new FileInstallArgs(params);
10760        }
10761    }
10762
10763    /**
10764     * Create args that describe an existing installed package. Typically used
10765     * when cleaning up old installs, or used as a move source.
10766     */
10767    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10768            String resourcePath, String[] instructionSets) {
10769        final boolean isInAsec;
10770        if (installOnExternalAsec(installFlags)) {
10771            /* Apps on SD card are always in ASEC containers. */
10772            isInAsec = true;
10773        } else if (installForwardLocked(installFlags)
10774                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10775            /*
10776             * Forward-locked apps are only in ASEC containers if they're the
10777             * new style
10778             */
10779            isInAsec = true;
10780        } else {
10781            isInAsec = false;
10782        }
10783
10784        if (isInAsec) {
10785            return new AsecInstallArgs(codePath, instructionSets,
10786                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10787        } else {
10788            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10789        }
10790    }
10791
10792    static abstract class InstallArgs {
10793        /** @see InstallParams#origin */
10794        final OriginInfo origin;
10795        /** @see InstallParams#move */
10796        final MoveInfo move;
10797
10798        final IPackageInstallObserver2 observer;
10799        // Always refers to PackageManager flags only
10800        final int installFlags;
10801        final String installerPackageName;
10802        final String volumeUuid;
10803        final ManifestDigest manifestDigest;
10804        final UserHandle user;
10805        final String abiOverride;
10806        final String[] installGrantPermissions;
10807
10808        // The list of instruction sets supported by this app. This is currently
10809        // only used during the rmdex() phase to clean up resources. We can get rid of this
10810        // if we move dex files under the common app path.
10811        /* nullable */ String[] instructionSets;
10812
10813        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10814                int installFlags, String installerPackageName, String volumeUuid,
10815                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10816                String abiOverride, String[] installGrantPermissions) {
10817            this.origin = origin;
10818            this.move = move;
10819            this.installFlags = installFlags;
10820            this.observer = observer;
10821            this.installerPackageName = installerPackageName;
10822            this.volumeUuid = volumeUuid;
10823            this.manifestDigest = manifestDigest;
10824            this.user = user;
10825            this.instructionSets = instructionSets;
10826            this.abiOverride = abiOverride;
10827            this.installGrantPermissions = installGrantPermissions;
10828        }
10829
10830        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10831        abstract int doPreInstall(int status);
10832
10833        /**
10834         * Rename package into final resting place. All paths on the given
10835         * scanned package should be updated to reflect the rename.
10836         */
10837        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10838        abstract int doPostInstall(int status, int uid);
10839
10840        /** @see PackageSettingBase#codePathString */
10841        abstract String getCodePath();
10842        /** @see PackageSettingBase#resourcePathString */
10843        abstract String getResourcePath();
10844
10845        // Need installer lock especially for dex file removal.
10846        abstract void cleanUpResourcesLI();
10847        abstract boolean doPostDeleteLI(boolean delete);
10848
10849        /**
10850         * Called before the source arguments are copied. This is used mostly
10851         * for MoveParams when it needs to read the source file to put it in the
10852         * destination.
10853         */
10854        int doPreCopy() {
10855            return PackageManager.INSTALL_SUCCEEDED;
10856        }
10857
10858        /**
10859         * Called after the source arguments are copied. This is used mostly for
10860         * MoveParams when it needs to read the source file to put it in the
10861         * destination.
10862         *
10863         * @return
10864         */
10865        int doPostCopy(int uid) {
10866            return PackageManager.INSTALL_SUCCEEDED;
10867        }
10868
10869        protected boolean isFwdLocked() {
10870            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10871        }
10872
10873        protected boolean isExternalAsec() {
10874            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10875        }
10876
10877        UserHandle getUser() {
10878            return user;
10879        }
10880    }
10881
10882    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10883        if (!allCodePaths.isEmpty()) {
10884            if (instructionSets == null) {
10885                throw new IllegalStateException("instructionSet == null");
10886            }
10887            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10888            for (String codePath : allCodePaths) {
10889                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10890                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10891                    if (retCode < 0) {
10892                        Slog.w(TAG, "Couldn't remove dex file for package: "
10893                                + " at location " + codePath + ", retcode=" + retCode);
10894                        // we don't consider this to be a failure of the core package deletion
10895                    }
10896                }
10897            }
10898        }
10899    }
10900
10901    /**
10902     * Logic to handle installation of non-ASEC applications, including copying
10903     * and renaming logic.
10904     */
10905    class FileInstallArgs extends InstallArgs {
10906        private File codeFile;
10907        private File resourceFile;
10908
10909        // Example topology:
10910        // /data/app/com.example/base.apk
10911        // /data/app/com.example/split_foo.apk
10912        // /data/app/com.example/lib/arm/libfoo.so
10913        // /data/app/com.example/lib/arm64/libfoo.so
10914        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10915
10916        /** New install */
10917        FileInstallArgs(InstallParams params) {
10918            super(params.origin, params.move, params.observer, params.installFlags,
10919                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10920                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
10921                    params.grantedRuntimePermissions);
10922            if (isFwdLocked()) {
10923                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10924            }
10925        }
10926
10927        /** Existing install */
10928        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10929            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10930                    null, null);
10931            this.codeFile = (codePath != null) ? new File(codePath) : null;
10932            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10933        }
10934
10935        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10936            if (origin.staged) {
10937                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10938                codeFile = origin.file;
10939                resourceFile = origin.file;
10940                return PackageManager.INSTALL_SUCCEEDED;
10941            }
10942
10943            try {
10944                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10945                codeFile = tempDir;
10946                resourceFile = tempDir;
10947            } catch (IOException e) {
10948                Slog.w(TAG, "Failed to create copy file: " + e);
10949                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10950            }
10951
10952            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10953                @Override
10954                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10955                    if (!FileUtils.isValidExtFilename(name)) {
10956                        throw new IllegalArgumentException("Invalid filename: " + name);
10957                    }
10958                    try {
10959                        final File file = new File(codeFile, name);
10960                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10961                                O_RDWR | O_CREAT, 0644);
10962                        Os.chmod(file.getAbsolutePath(), 0644);
10963                        return new ParcelFileDescriptor(fd);
10964                    } catch (ErrnoException e) {
10965                        throw new RemoteException("Failed to open: " + e.getMessage());
10966                    }
10967                }
10968            };
10969
10970            int ret = PackageManager.INSTALL_SUCCEEDED;
10971            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10972            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10973                Slog.e(TAG, "Failed to copy package");
10974                return ret;
10975            }
10976
10977            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10978            NativeLibraryHelper.Handle handle = null;
10979            try {
10980                handle = NativeLibraryHelper.Handle.create(codeFile);
10981                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10982                        abiOverride);
10983            } catch (IOException e) {
10984                Slog.e(TAG, "Copying native libraries failed", e);
10985                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10986            } finally {
10987                IoUtils.closeQuietly(handle);
10988            }
10989
10990            return ret;
10991        }
10992
10993        int doPreInstall(int status) {
10994            if (status != PackageManager.INSTALL_SUCCEEDED) {
10995                cleanUp();
10996            }
10997            return status;
10998        }
10999
11000        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11001            if (status != PackageManager.INSTALL_SUCCEEDED) {
11002                cleanUp();
11003                return false;
11004            }
11005
11006            final File targetDir = codeFile.getParentFile();
11007            final File beforeCodeFile = codeFile;
11008            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11009
11010            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11011            try {
11012                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11013            } catch (ErrnoException e) {
11014                Slog.w(TAG, "Failed to rename", e);
11015                return false;
11016            }
11017
11018            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11019                Slog.w(TAG, "Failed to restorecon");
11020                return false;
11021            }
11022
11023            // Reflect the rename internally
11024            codeFile = afterCodeFile;
11025            resourceFile = afterCodeFile;
11026
11027            // Reflect the rename in scanned details
11028            pkg.codePath = afterCodeFile.getAbsolutePath();
11029            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11030                    pkg.baseCodePath);
11031            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11032                    pkg.splitCodePaths);
11033
11034            // Reflect the rename in app info
11035            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11036            pkg.applicationInfo.setCodePath(pkg.codePath);
11037            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11038            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11039            pkg.applicationInfo.setResourcePath(pkg.codePath);
11040            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11041            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11042
11043            return true;
11044        }
11045
11046        int doPostInstall(int status, int uid) {
11047            if (status != PackageManager.INSTALL_SUCCEEDED) {
11048                cleanUp();
11049            }
11050            return status;
11051        }
11052
11053        @Override
11054        String getCodePath() {
11055            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11056        }
11057
11058        @Override
11059        String getResourcePath() {
11060            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11061        }
11062
11063        private boolean cleanUp() {
11064            if (codeFile == null || !codeFile.exists()) {
11065                return false;
11066            }
11067
11068            if (codeFile.isDirectory()) {
11069                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11070            } else {
11071                codeFile.delete();
11072            }
11073
11074            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11075                resourceFile.delete();
11076            }
11077
11078            return true;
11079        }
11080
11081        void cleanUpResourcesLI() {
11082            // Try enumerating all code paths before deleting
11083            List<String> allCodePaths = Collections.EMPTY_LIST;
11084            if (codeFile != null && codeFile.exists()) {
11085                try {
11086                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11087                    allCodePaths = pkg.getAllCodePaths();
11088                } catch (PackageParserException e) {
11089                    // Ignored; we tried our best
11090                }
11091            }
11092
11093            cleanUp();
11094            removeDexFiles(allCodePaths, instructionSets);
11095        }
11096
11097        boolean doPostDeleteLI(boolean delete) {
11098            // XXX err, shouldn't we respect the delete flag?
11099            cleanUpResourcesLI();
11100            return true;
11101        }
11102    }
11103
11104    private boolean isAsecExternal(String cid) {
11105        final String asecPath = PackageHelper.getSdFilesystem(cid);
11106        return !asecPath.startsWith(mAsecInternalPath);
11107    }
11108
11109    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11110            PackageManagerException {
11111        if (copyRet < 0) {
11112            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11113                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11114                throw new PackageManagerException(copyRet, message);
11115            }
11116        }
11117    }
11118
11119    /**
11120     * Extract the MountService "container ID" from the full code path of an
11121     * .apk.
11122     */
11123    static String cidFromCodePath(String fullCodePath) {
11124        int eidx = fullCodePath.lastIndexOf("/");
11125        String subStr1 = fullCodePath.substring(0, eidx);
11126        int sidx = subStr1.lastIndexOf("/");
11127        return subStr1.substring(sidx+1, eidx);
11128    }
11129
11130    /**
11131     * Logic to handle installation of ASEC applications, including copying and
11132     * renaming logic.
11133     */
11134    class AsecInstallArgs extends InstallArgs {
11135        static final String RES_FILE_NAME = "pkg.apk";
11136        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11137
11138        String cid;
11139        String packagePath;
11140        String resourcePath;
11141
11142        /** New install */
11143        AsecInstallArgs(InstallParams params) {
11144            super(params.origin, params.move, params.observer, params.installFlags,
11145                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11146                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11147                    params.grantedRuntimePermissions);
11148        }
11149
11150        /** Existing install */
11151        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11152                        boolean isExternal, boolean isForwardLocked) {
11153            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11154                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11155                    instructionSets, null, null);
11156            // Hackily pretend we're still looking at a full code path
11157            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11158                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11159            }
11160
11161            // Extract cid from fullCodePath
11162            int eidx = fullCodePath.lastIndexOf("/");
11163            String subStr1 = fullCodePath.substring(0, eidx);
11164            int sidx = subStr1.lastIndexOf("/");
11165            cid = subStr1.substring(sidx+1, eidx);
11166            setMountPath(subStr1);
11167        }
11168
11169        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11170            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11171                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11172                    instructionSets, null, null);
11173            this.cid = cid;
11174            setMountPath(PackageHelper.getSdDir(cid));
11175        }
11176
11177        void createCopyFile() {
11178            cid = mInstallerService.allocateExternalStageCidLegacy();
11179        }
11180
11181        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11182            if (origin.staged) {
11183                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11184                cid = origin.cid;
11185                setMountPath(PackageHelper.getSdDir(cid));
11186                return PackageManager.INSTALL_SUCCEEDED;
11187            }
11188
11189            if (temp) {
11190                createCopyFile();
11191            } else {
11192                /*
11193                 * Pre-emptively destroy the container since it's destroyed if
11194                 * copying fails due to it existing anyway.
11195                 */
11196                PackageHelper.destroySdDir(cid);
11197            }
11198
11199            final String newMountPath = imcs.copyPackageToContainer(
11200                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11201                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11202
11203            if (newMountPath != null) {
11204                setMountPath(newMountPath);
11205                return PackageManager.INSTALL_SUCCEEDED;
11206            } else {
11207                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11208            }
11209        }
11210
11211        @Override
11212        String getCodePath() {
11213            return packagePath;
11214        }
11215
11216        @Override
11217        String getResourcePath() {
11218            return resourcePath;
11219        }
11220
11221        int doPreInstall(int status) {
11222            if (status != PackageManager.INSTALL_SUCCEEDED) {
11223                // Destroy container
11224                PackageHelper.destroySdDir(cid);
11225            } else {
11226                boolean mounted = PackageHelper.isContainerMounted(cid);
11227                if (!mounted) {
11228                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11229                            Process.SYSTEM_UID);
11230                    if (newMountPath != null) {
11231                        setMountPath(newMountPath);
11232                    } else {
11233                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11234                    }
11235                }
11236            }
11237            return status;
11238        }
11239
11240        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11241            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11242            String newMountPath = null;
11243            if (PackageHelper.isContainerMounted(cid)) {
11244                // Unmount the container
11245                if (!PackageHelper.unMountSdDir(cid)) {
11246                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11247                    return false;
11248                }
11249            }
11250            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11251                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11252                        " which might be stale. Will try to clean up.");
11253                // Clean up the stale container and proceed to recreate.
11254                if (!PackageHelper.destroySdDir(newCacheId)) {
11255                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11256                    return false;
11257                }
11258                // Successfully cleaned up stale container. Try to rename again.
11259                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11260                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11261                            + " inspite of cleaning it up.");
11262                    return false;
11263                }
11264            }
11265            if (!PackageHelper.isContainerMounted(newCacheId)) {
11266                Slog.w(TAG, "Mounting container " + newCacheId);
11267                newMountPath = PackageHelper.mountSdDir(newCacheId,
11268                        getEncryptKey(), Process.SYSTEM_UID);
11269            } else {
11270                newMountPath = PackageHelper.getSdDir(newCacheId);
11271            }
11272            if (newMountPath == null) {
11273                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11274                return false;
11275            }
11276            Log.i(TAG, "Succesfully renamed " + cid +
11277                    " to " + newCacheId +
11278                    " at new path: " + newMountPath);
11279            cid = newCacheId;
11280
11281            final File beforeCodeFile = new File(packagePath);
11282            setMountPath(newMountPath);
11283            final File afterCodeFile = new File(packagePath);
11284
11285            // Reflect the rename in scanned details
11286            pkg.codePath = afterCodeFile.getAbsolutePath();
11287            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11288                    pkg.baseCodePath);
11289            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11290                    pkg.splitCodePaths);
11291
11292            // Reflect the rename in app info
11293            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11294            pkg.applicationInfo.setCodePath(pkg.codePath);
11295            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11296            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11297            pkg.applicationInfo.setResourcePath(pkg.codePath);
11298            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11299            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11300
11301            return true;
11302        }
11303
11304        private void setMountPath(String mountPath) {
11305            final File mountFile = new File(mountPath);
11306
11307            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11308            if (monolithicFile.exists()) {
11309                packagePath = monolithicFile.getAbsolutePath();
11310                if (isFwdLocked()) {
11311                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11312                } else {
11313                    resourcePath = packagePath;
11314                }
11315            } else {
11316                packagePath = mountFile.getAbsolutePath();
11317                resourcePath = packagePath;
11318            }
11319        }
11320
11321        int doPostInstall(int status, int uid) {
11322            if (status != PackageManager.INSTALL_SUCCEEDED) {
11323                cleanUp();
11324            } else {
11325                final int groupOwner;
11326                final String protectedFile;
11327                if (isFwdLocked()) {
11328                    groupOwner = UserHandle.getSharedAppGid(uid);
11329                    protectedFile = RES_FILE_NAME;
11330                } else {
11331                    groupOwner = -1;
11332                    protectedFile = null;
11333                }
11334
11335                if (uid < Process.FIRST_APPLICATION_UID
11336                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11337                    Slog.e(TAG, "Failed to finalize " + cid);
11338                    PackageHelper.destroySdDir(cid);
11339                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11340                }
11341
11342                boolean mounted = PackageHelper.isContainerMounted(cid);
11343                if (!mounted) {
11344                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11345                }
11346            }
11347            return status;
11348        }
11349
11350        private void cleanUp() {
11351            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11352
11353            // Destroy secure container
11354            PackageHelper.destroySdDir(cid);
11355        }
11356
11357        private List<String> getAllCodePaths() {
11358            final File codeFile = new File(getCodePath());
11359            if (codeFile != null && codeFile.exists()) {
11360                try {
11361                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11362                    return pkg.getAllCodePaths();
11363                } catch (PackageParserException e) {
11364                    // Ignored; we tried our best
11365                }
11366            }
11367            return Collections.EMPTY_LIST;
11368        }
11369
11370        void cleanUpResourcesLI() {
11371            // Enumerate all code paths before deleting
11372            cleanUpResourcesLI(getAllCodePaths());
11373        }
11374
11375        private void cleanUpResourcesLI(List<String> allCodePaths) {
11376            cleanUp();
11377            removeDexFiles(allCodePaths, instructionSets);
11378        }
11379
11380        String getPackageName() {
11381            return getAsecPackageName(cid);
11382        }
11383
11384        boolean doPostDeleteLI(boolean delete) {
11385            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11386            final List<String> allCodePaths = getAllCodePaths();
11387            boolean mounted = PackageHelper.isContainerMounted(cid);
11388            if (mounted) {
11389                // Unmount first
11390                if (PackageHelper.unMountSdDir(cid)) {
11391                    mounted = false;
11392                }
11393            }
11394            if (!mounted && delete) {
11395                cleanUpResourcesLI(allCodePaths);
11396            }
11397            return !mounted;
11398        }
11399
11400        @Override
11401        int doPreCopy() {
11402            if (isFwdLocked()) {
11403                if (!PackageHelper.fixSdPermissions(cid,
11404                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11405                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11406                }
11407            }
11408
11409            return PackageManager.INSTALL_SUCCEEDED;
11410        }
11411
11412        @Override
11413        int doPostCopy(int uid) {
11414            if (isFwdLocked()) {
11415                if (uid < Process.FIRST_APPLICATION_UID
11416                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11417                                RES_FILE_NAME)) {
11418                    Slog.e(TAG, "Failed to finalize " + cid);
11419                    PackageHelper.destroySdDir(cid);
11420                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11421                }
11422            }
11423
11424            return PackageManager.INSTALL_SUCCEEDED;
11425        }
11426    }
11427
11428    /**
11429     * Logic to handle movement of existing installed applications.
11430     */
11431    class MoveInstallArgs extends InstallArgs {
11432        private File codeFile;
11433        private File resourceFile;
11434
11435        /** New install */
11436        MoveInstallArgs(InstallParams params) {
11437            super(params.origin, params.move, params.observer, params.installFlags,
11438                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11439                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11440                    params.grantedRuntimePermissions);
11441        }
11442
11443        int copyApk(IMediaContainerService imcs, boolean temp) {
11444            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11445                    + move.fromUuid + " to " + move.toUuid);
11446            synchronized (mInstaller) {
11447                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11448                        move.dataAppName, move.appId, move.seinfo) != 0) {
11449                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11450                }
11451            }
11452
11453            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11454            resourceFile = codeFile;
11455            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11456
11457            return PackageManager.INSTALL_SUCCEEDED;
11458        }
11459
11460        int doPreInstall(int status) {
11461            if (status != PackageManager.INSTALL_SUCCEEDED) {
11462                cleanUp(move.toUuid);
11463            }
11464            return status;
11465        }
11466
11467        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11468            if (status != PackageManager.INSTALL_SUCCEEDED) {
11469                cleanUp(move.toUuid);
11470                return false;
11471            }
11472
11473            // Reflect the move in app info
11474            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11475            pkg.applicationInfo.setCodePath(pkg.codePath);
11476            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11477            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11478            pkg.applicationInfo.setResourcePath(pkg.codePath);
11479            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11480            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11481
11482            return true;
11483        }
11484
11485        int doPostInstall(int status, int uid) {
11486            if (status == PackageManager.INSTALL_SUCCEEDED) {
11487                cleanUp(move.fromUuid);
11488            } else {
11489                cleanUp(move.toUuid);
11490            }
11491            return status;
11492        }
11493
11494        @Override
11495        String getCodePath() {
11496            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11497        }
11498
11499        @Override
11500        String getResourcePath() {
11501            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11502        }
11503
11504        private boolean cleanUp(String volumeUuid) {
11505            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11506                    move.dataAppName);
11507            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11508            synchronized (mInstallLock) {
11509                // Clean up both app data and code
11510                removeDataDirsLI(volumeUuid, move.packageName);
11511                if (codeFile.isDirectory()) {
11512                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11513                } else {
11514                    codeFile.delete();
11515                }
11516            }
11517            return true;
11518        }
11519
11520        void cleanUpResourcesLI() {
11521            throw new UnsupportedOperationException();
11522        }
11523
11524        boolean doPostDeleteLI(boolean delete) {
11525            throw new UnsupportedOperationException();
11526        }
11527    }
11528
11529    static String getAsecPackageName(String packageCid) {
11530        int idx = packageCid.lastIndexOf("-");
11531        if (idx == -1) {
11532            return packageCid;
11533        }
11534        return packageCid.substring(0, idx);
11535    }
11536
11537    // Utility method used to create code paths based on package name and available index.
11538    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11539        String idxStr = "";
11540        int idx = 1;
11541        // Fall back to default value of idx=1 if prefix is not
11542        // part of oldCodePath
11543        if (oldCodePath != null) {
11544            String subStr = oldCodePath;
11545            // Drop the suffix right away
11546            if (suffix != null && subStr.endsWith(suffix)) {
11547                subStr = subStr.substring(0, subStr.length() - suffix.length());
11548            }
11549            // If oldCodePath already contains prefix find out the
11550            // ending index to either increment or decrement.
11551            int sidx = subStr.lastIndexOf(prefix);
11552            if (sidx != -1) {
11553                subStr = subStr.substring(sidx + prefix.length());
11554                if (subStr != null) {
11555                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11556                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11557                    }
11558                    try {
11559                        idx = Integer.parseInt(subStr);
11560                        if (idx <= 1) {
11561                            idx++;
11562                        } else {
11563                            idx--;
11564                        }
11565                    } catch(NumberFormatException e) {
11566                    }
11567                }
11568            }
11569        }
11570        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11571        return prefix + idxStr;
11572    }
11573
11574    private File getNextCodePath(File targetDir, String packageName) {
11575        int suffix = 1;
11576        File result;
11577        do {
11578            result = new File(targetDir, packageName + "-" + suffix);
11579            suffix++;
11580        } while (result.exists());
11581        return result;
11582    }
11583
11584    // Utility method that returns the relative package path with respect
11585    // to the installation directory. Like say for /data/data/com.test-1.apk
11586    // string com.test-1 is returned.
11587    static String deriveCodePathName(String codePath) {
11588        if (codePath == null) {
11589            return null;
11590        }
11591        final File codeFile = new File(codePath);
11592        final String name = codeFile.getName();
11593        if (codeFile.isDirectory()) {
11594            return name;
11595        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11596            final int lastDot = name.lastIndexOf('.');
11597            return name.substring(0, lastDot);
11598        } else {
11599            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11600            return null;
11601        }
11602    }
11603
11604    class PackageInstalledInfo {
11605        String name;
11606        int uid;
11607        // The set of users that originally had this package installed.
11608        int[] origUsers;
11609        // The set of users that now have this package installed.
11610        int[] newUsers;
11611        PackageParser.Package pkg;
11612        int returnCode;
11613        String returnMsg;
11614        PackageRemovedInfo removedInfo;
11615
11616        public void setError(int code, String msg) {
11617            returnCode = code;
11618            returnMsg = msg;
11619            Slog.w(TAG, msg);
11620        }
11621
11622        public void setError(String msg, PackageParserException e) {
11623            returnCode = e.error;
11624            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11625            Slog.w(TAG, msg, e);
11626        }
11627
11628        public void setError(String msg, PackageManagerException e) {
11629            returnCode = e.error;
11630            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11631            Slog.w(TAG, msg, e);
11632        }
11633
11634        // In some error cases we want to convey more info back to the observer
11635        String origPackage;
11636        String origPermission;
11637    }
11638
11639    /*
11640     * Install a non-existing package.
11641     */
11642    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11643            UserHandle user, String installerPackageName, String volumeUuid,
11644            PackageInstalledInfo res) {
11645        // Remember this for later, in case we need to rollback this install
11646        String pkgName = pkg.packageName;
11647
11648        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11649        final boolean dataDirExists = Environment
11650                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11651        synchronized(mPackages) {
11652            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11653                // A package with the same name is already installed, though
11654                // it has been renamed to an older name.  The package we
11655                // are trying to install should be installed as an update to
11656                // the existing one, but that has not been requested, so bail.
11657                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11658                        + " without first uninstalling package running as "
11659                        + mSettings.mRenamedPackages.get(pkgName));
11660                return;
11661            }
11662            if (mPackages.containsKey(pkgName)) {
11663                // Don't allow installation over an existing package with the same name.
11664                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11665                        + " without first uninstalling.");
11666                return;
11667            }
11668        }
11669
11670        try {
11671            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11672                    System.currentTimeMillis(), user);
11673
11674            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11675            // delete the partially installed application. the data directory will have to be
11676            // restored if it was already existing
11677            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11678                // remove package from internal structures.  Note that we want deletePackageX to
11679                // delete the package data and cache directories that it created in
11680                // scanPackageLocked, unless those directories existed before we even tried to
11681                // install.
11682                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11683                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11684                                res.removedInfo, true);
11685            }
11686
11687        } catch (PackageManagerException e) {
11688            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11689        }
11690    }
11691
11692    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11693        // Can't rotate keys during boot or if sharedUser.
11694        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11695                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11696            return false;
11697        }
11698        // app is using upgradeKeySets; make sure all are valid
11699        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11700        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11701        for (int i = 0; i < upgradeKeySets.length; i++) {
11702            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11703                Slog.wtf(TAG, "Package "
11704                         + (oldPs.name != null ? oldPs.name : "<null>")
11705                         + " contains upgrade-key-set reference to unknown key-set: "
11706                         + upgradeKeySets[i]
11707                         + " reverting to signatures check.");
11708                return false;
11709            }
11710        }
11711        return true;
11712    }
11713
11714    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11715        // Upgrade keysets are being used.  Determine if new package has a superset of the
11716        // required keys.
11717        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11718        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11719        for (int i = 0; i < upgradeKeySets.length; i++) {
11720            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11721            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11722                return true;
11723            }
11724        }
11725        return false;
11726    }
11727
11728    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11729            UserHandle user, String installerPackageName, String volumeUuid,
11730            PackageInstalledInfo res) {
11731        final PackageParser.Package oldPackage;
11732        final String pkgName = pkg.packageName;
11733        final int[] allUsers;
11734        final boolean[] perUserInstalled;
11735        final boolean weFroze;
11736
11737        // First find the old package info and check signatures
11738        synchronized(mPackages) {
11739            oldPackage = mPackages.get(pkgName);
11740            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11741            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11742            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11743                if(!checkUpgradeKeySetLP(ps, pkg)) {
11744                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11745                            "New package not signed by keys specified by upgrade-keysets: "
11746                            + pkgName);
11747                    return;
11748                }
11749            } else {
11750                // default to original signature matching
11751                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11752                    != PackageManager.SIGNATURE_MATCH) {
11753                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11754                            "New package has a different signature: " + pkgName);
11755                    return;
11756                }
11757            }
11758
11759            // In case of rollback, remember per-user/profile install state
11760            allUsers = sUserManager.getUserIds();
11761            perUserInstalled = new boolean[allUsers.length];
11762            for (int i = 0; i < allUsers.length; i++) {
11763                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11764            }
11765
11766            // Mark the app as frozen to prevent launching during the upgrade
11767            // process, and then kill all running instances
11768            if (!ps.frozen) {
11769                ps.frozen = true;
11770                weFroze = true;
11771            } else {
11772                weFroze = false;
11773            }
11774        }
11775
11776        // Now that we're guarded by frozen state, kill app during upgrade
11777        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11778
11779        try {
11780            boolean sysPkg = (isSystemApp(oldPackage));
11781            if (sysPkg) {
11782                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11783                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11784            } else {
11785                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11786                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11787            }
11788        } finally {
11789            // Regardless of success or failure of upgrade steps above, always
11790            // unfreeze the package if we froze it
11791            if (weFroze) {
11792                unfreezePackage(pkgName);
11793            }
11794        }
11795    }
11796
11797    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11798            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11799            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11800            String volumeUuid, PackageInstalledInfo res) {
11801        String pkgName = deletedPackage.packageName;
11802        boolean deletedPkg = true;
11803        boolean updatedSettings = false;
11804
11805        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11806                + deletedPackage);
11807        long origUpdateTime;
11808        if (pkg.mExtras != null) {
11809            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11810        } else {
11811            origUpdateTime = 0;
11812        }
11813
11814        // First delete the existing package while retaining the data directory
11815        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11816                res.removedInfo, true)) {
11817            // If the existing package wasn't successfully deleted
11818            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11819            deletedPkg = false;
11820        } else {
11821            // Successfully deleted the old package; proceed with replace.
11822
11823            // If deleted package lived in a container, give users a chance to
11824            // relinquish resources before killing.
11825            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11826                if (DEBUG_INSTALL) {
11827                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11828                }
11829                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11830                final ArrayList<String> pkgList = new ArrayList<String>(1);
11831                pkgList.add(deletedPackage.applicationInfo.packageName);
11832                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11833            }
11834
11835            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11836            try {
11837                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11838                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11839                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11840                        perUserInstalled, res, user);
11841                updatedSettings = true;
11842            } catch (PackageManagerException e) {
11843                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11844            }
11845        }
11846
11847        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11848            // remove package from internal structures.  Note that we want deletePackageX to
11849            // delete the package data and cache directories that it created in
11850            // scanPackageLocked, unless those directories existed before we even tried to
11851            // install.
11852            if(updatedSettings) {
11853                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11854                deletePackageLI(
11855                        pkgName, null, true, allUsers, perUserInstalled,
11856                        PackageManager.DELETE_KEEP_DATA,
11857                                res.removedInfo, true);
11858            }
11859            // Since we failed to install the new package we need to restore the old
11860            // package that we deleted.
11861            if (deletedPkg) {
11862                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11863                File restoreFile = new File(deletedPackage.codePath);
11864                // Parse old package
11865                boolean oldExternal = isExternal(deletedPackage);
11866                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11867                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11868                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11869                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11870                try {
11871                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11872                } catch (PackageManagerException e) {
11873                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11874                            + e.getMessage());
11875                    return;
11876                }
11877                // Restore of old package succeeded. Update permissions.
11878                // writer
11879                synchronized (mPackages) {
11880                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11881                            UPDATE_PERMISSIONS_ALL);
11882                    // can downgrade to reader
11883                    mSettings.writeLPr();
11884                }
11885                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11886            }
11887        }
11888    }
11889
11890    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11891            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11892            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11893            String volumeUuid, PackageInstalledInfo res) {
11894        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11895                + ", old=" + deletedPackage);
11896        boolean disabledSystem = false;
11897        boolean updatedSettings = false;
11898        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11899        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11900                != 0) {
11901            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11902        }
11903        String packageName = deletedPackage.packageName;
11904        if (packageName == null) {
11905            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11906                    "Attempt to delete null packageName.");
11907            return;
11908        }
11909        PackageParser.Package oldPkg;
11910        PackageSetting oldPkgSetting;
11911        // reader
11912        synchronized (mPackages) {
11913            oldPkg = mPackages.get(packageName);
11914            oldPkgSetting = mSettings.mPackages.get(packageName);
11915            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11916                    (oldPkgSetting == null)) {
11917                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11918                        "Couldn't find package:" + packageName + " information");
11919                return;
11920            }
11921        }
11922
11923        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11924        res.removedInfo.removedPackage = packageName;
11925        // Remove existing system package
11926        removePackageLI(oldPkgSetting, true);
11927        // writer
11928        synchronized (mPackages) {
11929            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11930            if (!disabledSystem && deletedPackage != null) {
11931                // We didn't need to disable the .apk as a current system package,
11932                // which means we are replacing another update that is already
11933                // installed.  We need to make sure to delete the older one's .apk.
11934                res.removedInfo.args = createInstallArgsForExisting(0,
11935                        deletedPackage.applicationInfo.getCodePath(),
11936                        deletedPackage.applicationInfo.getResourcePath(),
11937                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11938            } else {
11939                res.removedInfo.args = null;
11940            }
11941        }
11942
11943        // Successfully disabled the old package. Now proceed with re-installation
11944        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11945
11946        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11947        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11948
11949        PackageParser.Package newPackage = null;
11950        try {
11951            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11952            if (newPackage.mExtras != null) {
11953                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11954                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11955                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11956
11957                // is the update attempting to change shared user? that isn't going to work...
11958                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11959                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11960                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11961                            + " to " + newPkgSetting.sharedUser);
11962                    updatedSettings = true;
11963                }
11964            }
11965
11966            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11967                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11968                        perUserInstalled, res, user);
11969                updatedSettings = true;
11970            }
11971
11972        } catch (PackageManagerException e) {
11973            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11974        }
11975
11976        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11977            // Re installation failed. Restore old information
11978            // Remove new pkg information
11979            if (newPackage != null) {
11980                removeInstalledPackageLI(newPackage, true);
11981            }
11982            // Add back the old system package
11983            try {
11984                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11985            } catch (PackageManagerException e) {
11986                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11987            }
11988            // Restore the old system information in Settings
11989            synchronized (mPackages) {
11990                if (disabledSystem) {
11991                    mSettings.enableSystemPackageLPw(packageName);
11992                }
11993                if (updatedSettings) {
11994                    mSettings.setInstallerPackageName(packageName,
11995                            oldPkgSetting.installerPackageName);
11996                }
11997                mSettings.writeLPr();
11998            }
11999        }
12000    }
12001
12002    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12003            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12004            UserHandle user) {
12005        String pkgName = newPackage.packageName;
12006        synchronized (mPackages) {
12007            //write settings. the installStatus will be incomplete at this stage.
12008            //note that the new package setting would have already been
12009            //added to mPackages. It hasn't been persisted yet.
12010            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12011            mSettings.writeLPr();
12012        }
12013
12014        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12015
12016        synchronized (mPackages) {
12017            updatePermissionsLPw(newPackage.packageName, newPackage,
12018                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12019                            ? UPDATE_PERMISSIONS_ALL : 0));
12020            // For system-bundled packages, we assume that installing an upgraded version
12021            // of the package implies that the user actually wants to run that new code,
12022            // so we enable the package.
12023            PackageSetting ps = mSettings.mPackages.get(pkgName);
12024            if (ps != null) {
12025                if (isSystemApp(newPackage)) {
12026                    // NB: implicit assumption that system package upgrades apply to all users
12027                    if (DEBUG_INSTALL) {
12028                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12029                    }
12030                    if (res.origUsers != null) {
12031                        for (int userHandle : res.origUsers) {
12032                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12033                                    userHandle, installerPackageName);
12034                        }
12035                    }
12036                    // Also convey the prior install/uninstall state
12037                    if (allUsers != null && perUserInstalled != null) {
12038                        for (int i = 0; i < allUsers.length; i++) {
12039                            if (DEBUG_INSTALL) {
12040                                Slog.d(TAG, "    user " + allUsers[i]
12041                                        + " => " + perUserInstalled[i]);
12042                            }
12043                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12044                        }
12045                        // these install state changes will be persisted in the
12046                        // upcoming call to mSettings.writeLPr().
12047                    }
12048                }
12049                // It's implied that when a user requests installation, they want the app to be
12050                // installed and enabled.
12051                int userId = user.getIdentifier();
12052                if (userId != UserHandle.USER_ALL) {
12053                    ps.setInstalled(true, userId);
12054                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12055                }
12056            }
12057            res.name = pkgName;
12058            res.uid = newPackage.applicationInfo.uid;
12059            res.pkg = newPackage;
12060            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12061            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12062            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12063            //to update install status
12064            mSettings.writeLPr();
12065        }
12066    }
12067
12068    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12069        final int installFlags = args.installFlags;
12070        final String installerPackageName = args.installerPackageName;
12071        final String volumeUuid = args.volumeUuid;
12072        final File tmpPackageFile = new File(args.getCodePath());
12073        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12074        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12075                || (args.volumeUuid != null));
12076        boolean replace = false;
12077        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12078        if (args.move != null) {
12079            // moving a complete application; perfom an initial scan on the new install location
12080            scanFlags |= SCAN_INITIAL;
12081        }
12082        // Result object to be returned
12083        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12084
12085        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12086        // Retrieve PackageSettings and parse package
12087        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12088                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12089                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12090        PackageParser pp = new PackageParser();
12091        pp.setSeparateProcesses(mSeparateProcesses);
12092        pp.setDisplayMetrics(mMetrics);
12093
12094        final PackageParser.Package pkg;
12095        try {
12096            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12097        } catch (PackageParserException e) {
12098            res.setError("Failed parse during installPackageLI", e);
12099            return;
12100        }
12101
12102        // Mark that we have an install time CPU ABI override.
12103        pkg.cpuAbiOverride = args.abiOverride;
12104
12105        String pkgName = res.name = pkg.packageName;
12106        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12107            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12108                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12109                return;
12110            }
12111        }
12112
12113        try {
12114            pp.collectCertificates(pkg, parseFlags);
12115            pp.collectManifestDigest(pkg);
12116        } catch (PackageParserException e) {
12117            res.setError("Failed collect during installPackageLI", e);
12118            return;
12119        }
12120
12121        /* If the installer passed in a manifest digest, compare it now. */
12122        if (args.manifestDigest != null) {
12123            if (DEBUG_INSTALL) {
12124                final String parsedManifest = pkg.manifestDigest == null ? "null"
12125                        : pkg.manifestDigest.toString();
12126                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12127                        + parsedManifest);
12128            }
12129
12130            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12131                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12132                return;
12133            }
12134        } else if (DEBUG_INSTALL) {
12135            final String parsedManifest = pkg.manifestDigest == null
12136                    ? "null" : pkg.manifestDigest.toString();
12137            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12138        }
12139
12140        // Get rid of all references to package scan path via parser.
12141        pp = null;
12142        String oldCodePath = null;
12143        boolean systemApp = false;
12144        synchronized (mPackages) {
12145            // Check if installing already existing package
12146            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12147                String oldName = mSettings.mRenamedPackages.get(pkgName);
12148                if (pkg.mOriginalPackages != null
12149                        && pkg.mOriginalPackages.contains(oldName)
12150                        && mPackages.containsKey(oldName)) {
12151                    // This package is derived from an original package,
12152                    // and this device has been updating from that original
12153                    // name.  We must continue using the original name, so
12154                    // rename the new package here.
12155                    pkg.setPackageName(oldName);
12156                    pkgName = pkg.packageName;
12157                    replace = true;
12158                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12159                            + oldName + " pkgName=" + pkgName);
12160                } else if (mPackages.containsKey(pkgName)) {
12161                    // This package, under its official name, already exists
12162                    // on the device; we should replace it.
12163                    replace = true;
12164                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12165                }
12166
12167                // Prevent apps opting out from runtime permissions
12168                if (replace) {
12169                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12170                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12171                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12172                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12173                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12174                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12175                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12176                                        + " doesn't support runtime permissions but the old"
12177                                        + " target SDK " + oldTargetSdk + " does.");
12178                        return;
12179                    }
12180                }
12181            }
12182
12183            PackageSetting ps = mSettings.mPackages.get(pkgName);
12184            if (ps != null) {
12185                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12186
12187                // Quick sanity check that we're signed correctly if updating;
12188                // we'll check this again later when scanning, but we want to
12189                // bail early here before tripping over redefined permissions.
12190                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12191                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12192                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12193                                + pkg.packageName + " upgrade keys do not match the "
12194                                + "previously installed version");
12195                        return;
12196                    }
12197                } else {
12198                    try {
12199                        verifySignaturesLP(ps, pkg);
12200                    } catch (PackageManagerException e) {
12201                        res.setError(e.error, e.getMessage());
12202                        return;
12203                    }
12204                }
12205
12206                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12207                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12208                    systemApp = (ps.pkg.applicationInfo.flags &
12209                            ApplicationInfo.FLAG_SYSTEM) != 0;
12210                }
12211                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12212            }
12213
12214            // Check whether the newly-scanned package wants to define an already-defined perm
12215            int N = pkg.permissions.size();
12216            for (int i = N-1; i >= 0; i--) {
12217                PackageParser.Permission perm = pkg.permissions.get(i);
12218                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12219                if (bp != null) {
12220                    // If the defining package is signed with our cert, it's okay.  This
12221                    // also includes the "updating the same package" case, of course.
12222                    // "updating same package" could also involve key-rotation.
12223                    final boolean sigsOk;
12224                    if (bp.sourcePackage.equals(pkg.packageName)
12225                            && (bp.packageSetting instanceof PackageSetting)
12226                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12227                                    scanFlags))) {
12228                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12229                    } else {
12230                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12231                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12232                    }
12233                    if (!sigsOk) {
12234                        // If the owning package is the system itself, we log but allow
12235                        // install to proceed; we fail the install on all other permission
12236                        // redefinitions.
12237                        if (!bp.sourcePackage.equals("android")) {
12238                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12239                                    + pkg.packageName + " attempting to redeclare permission "
12240                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12241                            res.origPermission = perm.info.name;
12242                            res.origPackage = bp.sourcePackage;
12243                            return;
12244                        } else {
12245                            Slog.w(TAG, "Package " + pkg.packageName
12246                                    + " attempting to redeclare system permission "
12247                                    + perm.info.name + "; ignoring new declaration");
12248                            pkg.permissions.remove(i);
12249                        }
12250                    }
12251                }
12252            }
12253
12254        }
12255
12256        if (systemApp && onExternal) {
12257            // Disable updates to system apps on sdcard
12258            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12259                    "Cannot install updates to system apps on sdcard");
12260            return;
12261        }
12262
12263        if (args.move != null) {
12264            // We did an in-place move, so dex is ready to roll
12265            scanFlags |= SCAN_NO_DEX;
12266            scanFlags |= SCAN_MOVE;
12267        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12268            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12269            scanFlags |= SCAN_NO_DEX;
12270
12271            try {
12272                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12273                        true /* extract libs */);
12274            } catch (PackageManagerException pme) {
12275                Slog.e(TAG, "Error deriving application ABI", pme);
12276                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12277                return;
12278            }
12279
12280            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12281            int result = mPackageDexOptimizer
12282                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12283                            false /* defer */, false /* inclDependencies */);
12284            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12285                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12286                return;
12287            }
12288        }
12289
12290        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12291            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12292            return;
12293        }
12294
12295        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12296
12297        if (replace) {
12298            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12299                    installerPackageName, volumeUuid, res);
12300        } else {
12301            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12302                    args.user, installerPackageName, volumeUuid, res);
12303        }
12304        synchronized (mPackages) {
12305            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12306            if (ps != null) {
12307                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12308            }
12309        }
12310    }
12311
12312    private void startIntentFilterVerifications(int userId, boolean replacing,
12313            PackageParser.Package pkg) {
12314        if (mIntentFilterVerifierComponent == null) {
12315            Slog.w(TAG, "No IntentFilter verification will not be done as "
12316                    + "there is no IntentFilterVerifier available!");
12317            return;
12318        }
12319
12320        final int verifierUid = getPackageUid(
12321                mIntentFilterVerifierComponent.getPackageName(),
12322                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12323
12324        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12325        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12326        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12327        mHandler.sendMessage(msg);
12328    }
12329
12330    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12331            PackageParser.Package pkg) {
12332        int size = pkg.activities.size();
12333        if (size == 0) {
12334            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12335                    "No activity, so no need to verify any IntentFilter!");
12336            return;
12337        }
12338
12339        final boolean hasDomainURLs = hasDomainURLs(pkg);
12340        if (!hasDomainURLs) {
12341            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12342                    "No domain URLs, so no need to verify any IntentFilter!");
12343            return;
12344        }
12345
12346        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12347                + " if any IntentFilter from the " + size
12348                + " Activities needs verification ...");
12349
12350        int count = 0;
12351        final String packageName = pkg.packageName;
12352
12353        synchronized (mPackages) {
12354            // If this is a new install and we see that we've already run verification for this
12355            // package, we have nothing to do: it means the state was restored from backup.
12356            if (!replacing) {
12357                IntentFilterVerificationInfo ivi =
12358                        mSettings.getIntentFilterVerificationLPr(packageName);
12359                if (ivi != null) {
12360                    if (DEBUG_DOMAIN_VERIFICATION) {
12361                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12362                                + ivi.getStatusString());
12363                    }
12364                    return;
12365                }
12366            }
12367
12368            // If any filters need to be verified, then all need to be.
12369            boolean needToVerify = false;
12370            for (PackageParser.Activity a : pkg.activities) {
12371                for (ActivityIntentInfo filter : a.intents) {
12372                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12373                        if (DEBUG_DOMAIN_VERIFICATION) {
12374                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12375                        }
12376                        needToVerify = true;
12377                        break;
12378                    }
12379                }
12380            }
12381
12382            if (needToVerify) {
12383                final int verificationId = mIntentFilterVerificationToken++;
12384                for (PackageParser.Activity a : pkg.activities) {
12385                    for (ActivityIntentInfo filter : a.intents) {
12386                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12387                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12388                                    "Verification needed for IntentFilter:" + filter.toString());
12389                            mIntentFilterVerifier.addOneIntentFilterVerification(
12390                                    verifierUid, userId, verificationId, filter, packageName);
12391                            count++;
12392                        }
12393                    }
12394                }
12395            }
12396        }
12397
12398        if (count > 0) {
12399            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12400                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12401                    +  " for userId:" + userId);
12402            mIntentFilterVerifier.startVerifications(userId);
12403        } else {
12404            if (DEBUG_DOMAIN_VERIFICATION) {
12405                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12406            }
12407        }
12408    }
12409
12410    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12411        final ComponentName cn  = filter.activity.getComponentName();
12412        final String packageName = cn.getPackageName();
12413
12414        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12415                packageName);
12416        if (ivi == null) {
12417            return true;
12418        }
12419        int status = ivi.getStatus();
12420        switch (status) {
12421            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12422            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12423                return true;
12424
12425            default:
12426                // Nothing to do
12427                return false;
12428        }
12429    }
12430
12431    private static boolean isMultiArch(PackageSetting ps) {
12432        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12433    }
12434
12435    private static boolean isMultiArch(ApplicationInfo info) {
12436        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12437    }
12438
12439    private static boolean isExternal(PackageParser.Package pkg) {
12440        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12441    }
12442
12443    private static boolean isExternal(PackageSetting ps) {
12444        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12445    }
12446
12447    private static boolean isExternal(ApplicationInfo info) {
12448        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12449    }
12450
12451    private static boolean isSystemApp(PackageParser.Package pkg) {
12452        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12453    }
12454
12455    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12456        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12457    }
12458
12459    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12460        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12461    }
12462
12463    private static boolean isSystemApp(PackageSetting ps) {
12464        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12465    }
12466
12467    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12468        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12469    }
12470
12471    private int packageFlagsToInstallFlags(PackageSetting ps) {
12472        int installFlags = 0;
12473        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12474            // This existing package was an external ASEC install when we have
12475            // the external flag without a UUID
12476            installFlags |= PackageManager.INSTALL_EXTERNAL;
12477        }
12478        if (ps.isForwardLocked()) {
12479            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12480        }
12481        return installFlags;
12482    }
12483
12484    private void deleteTempPackageFiles() {
12485        final FilenameFilter filter = new FilenameFilter() {
12486            public boolean accept(File dir, String name) {
12487                return name.startsWith("vmdl") && name.endsWith(".tmp");
12488            }
12489        };
12490        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12491            file.delete();
12492        }
12493    }
12494
12495    @Override
12496    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12497            int flags) {
12498        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12499                flags);
12500    }
12501
12502    @Override
12503    public void deletePackage(final String packageName,
12504            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12505        mContext.enforceCallingOrSelfPermission(
12506                android.Manifest.permission.DELETE_PACKAGES, null);
12507        Preconditions.checkNotNull(packageName);
12508        Preconditions.checkNotNull(observer);
12509        final int uid = Binder.getCallingUid();
12510        if (UserHandle.getUserId(uid) != userId) {
12511            mContext.enforceCallingPermission(
12512                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12513                    "deletePackage for user " + userId);
12514        }
12515        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12516            try {
12517                observer.onPackageDeleted(packageName,
12518                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12519            } catch (RemoteException re) {
12520            }
12521            return;
12522        }
12523
12524        boolean uninstallBlocked = false;
12525        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12526            int[] users = sUserManager.getUserIds();
12527            for (int i = 0; i < users.length; ++i) {
12528                if (getBlockUninstallForUser(packageName, users[i])) {
12529                    uninstallBlocked = true;
12530                    break;
12531                }
12532            }
12533        } else {
12534            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12535        }
12536        if (uninstallBlocked) {
12537            try {
12538                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12539                        null);
12540            } catch (RemoteException re) {
12541            }
12542            return;
12543        }
12544
12545        if (DEBUG_REMOVE) {
12546            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12547        }
12548        // Queue up an async operation since the package deletion may take a little while.
12549        mHandler.post(new Runnable() {
12550            public void run() {
12551                mHandler.removeCallbacks(this);
12552                final int returnCode = deletePackageX(packageName, userId, flags);
12553                if (observer != null) {
12554                    try {
12555                        observer.onPackageDeleted(packageName, returnCode, null);
12556                    } catch (RemoteException e) {
12557                        Log.i(TAG, "Observer no longer exists.");
12558                    } //end catch
12559                } //end if
12560            } //end run
12561        });
12562    }
12563
12564    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12565        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12566                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12567        try {
12568            if (dpm != null) {
12569                if (dpm.isDeviceOwner(packageName)) {
12570                    return true;
12571                }
12572                int[] users;
12573                if (userId == UserHandle.USER_ALL) {
12574                    users = sUserManager.getUserIds();
12575                } else {
12576                    users = new int[]{userId};
12577                }
12578                for (int i = 0; i < users.length; ++i) {
12579                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12580                        return true;
12581                    }
12582                }
12583            }
12584        } catch (RemoteException e) {
12585        }
12586        return false;
12587    }
12588
12589    /**
12590     *  This method is an internal method that could be get invoked either
12591     *  to delete an installed package or to clean up a failed installation.
12592     *  After deleting an installed package, a broadcast is sent to notify any
12593     *  listeners that the package has been installed. For cleaning up a failed
12594     *  installation, the broadcast is not necessary since the package's
12595     *  installation wouldn't have sent the initial broadcast either
12596     *  The key steps in deleting a package are
12597     *  deleting the package information in internal structures like mPackages,
12598     *  deleting the packages base directories through installd
12599     *  updating mSettings to reflect current status
12600     *  persisting settings for later use
12601     *  sending a broadcast if necessary
12602     */
12603    private int deletePackageX(String packageName, int userId, int flags) {
12604        final PackageRemovedInfo info = new PackageRemovedInfo();
12605        final boolean res;
12606
12607        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12608                ? UserHandle.ALL : new UserHandle(userId);
12609
12610        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12611            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12612            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12613        }
12614
12615        boolean removedForAllUsers = false;
12616        boolean systemUpdate = false;
12617
12618        // for the uninstall-updates case and restricted profiles, remember the per-
12619        // userhandle installed state
12620        int[] allUsers;
12621        boolean[] perUserInstalled;
12622        synchronized (mPackages) {
12623            PackageSetting ps = mSettings.mPackages.get(packageName);
12624            allUsers = sUserManager.getUserIds();
12625            perUserInstalled = new boolean[allUsers.length];
12626            for (int i = 0; i < allUsers.length; i++) {
12627                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12628            }
12629        }
12630
12631        synchronized (mInstallLock) {
12632            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12633            res = deletePackageLI(packageName, removeForUser,
12634                    true, allUsers, perUserInstalled,
12635                    flags | REMOVE_CHATTY, info, true);
12636            systemUpdate = info.isRemovedPackageSystemUpdate;
12637            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12638                removedForAllUsers = true;
12639            }
12640            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12641                    + " removedForAllUsers=" + removedForAllUsers);
12642        }
12643
12644        if (res) {
12645            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12646
12647            // If the removed package was a system update, the old system package
12648            // was re-enabled; we need to broadcast this information
12649            if (systemUpdate) {
12650                Bundle extras = new Bundle(1);
12651                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12652                        ? info.removedAppId : info.uid);
12653                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12654
12655                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12656                        extras, null, null, null);
12657                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12658                        extras, null, null, null);
12659                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12660                        null, packageName, null, null);
12661            }
12662        }
12663        // Force a gc here.
12664        Runtime.getRuntime().gc();
12665        // Delete the resources here after sending the broadcast to let
12666        // other processes clean up before deleting resources.
12667        if (info.args != null) {
12668            synchronized (mInstallLock) {
12669                info.args.doPostDeleteLI(true);
12670            }
12671        }
12672
12673        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12674    }
12675
12676    class PackageRemovedInfo {
12677        String removedPackage;
12678        int uid = -1;
12679        int removedAppId = -1;
12680        int[] removedUsers = null;
12681        boolean isRemovedPackageSystemUpdate = false;
12682        // Clean up resources deleted packages.
12683        InstallArgs args = null;
12684
12685        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12686            Bundle extras = new Bundle(1);
12687            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12688            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12689            if (replacing) {
12690                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12691            }
12692            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12693            if (removedPackage != null) {
12694                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12695                        extras, null, null, removedUsers);
12696                if (fullRemove && !replacing) {
12697                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12698                            extras, null, null, removedUsers);
12699                }
12700            }
12701            if (removedAppId >= 0) {
12702                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12703                        removedUsers);
12704            }
12705        }
12706    }
12707
12708    /*
12709     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12710     * flag is not set, the data directory is removed as well.
12711     * make sure this flag is set for partially installed apps. If not its meaningless to
12712     * delete a partially installed application.
12713     */
12714    private void removePackageDataLI(PackageSetting ps,
12715            int[] allUserHandles, boolean[] perUserInstalled,
12716            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12717        String packageName = ps.name;
12718        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12719        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12720        // Retrieve object to delete permissions for shared user later on
12721        final PackageSetting deletedPs;
12722        // reader
12723        synchronized (mPackages) {
12724            deletedPs = mSettings.mPackages.get(packageName);
12725            if (outInfo != null) {
12726                outInfo.removedPackage = packageName;
12727                outInfo.removedUsers = deletedPs != null
12728                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12729                        : null;
12730            }
12731        }
12732        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12733            removeDataDirsLI(ps.volumeUuid, packageName);
12734            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12735        }
12736        // writer
12737        synchronized (mPackages) {
12738            if (deletedPs != null) {
12739                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12740                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12741                    clearDefaultBrowserIfNeeded(packageName);
12742                    if (outInfo != null) {
12743                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12744                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12745                    }
12746                    updatePermissionsLPw(deletedPs.name, null, 0);
12747                    if (deletedPs.sharedUser != null) {
12748                        // Remove permissions associated with package. Since runtime
12749                        // permissions are per user we have to kill the removed package
12750                        // or packages running under the shared user of the removed
12751                        // package if revoking the permissions requested only by the removed
12752                        // package is successful and this causes a change in gids.
12753                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12754                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12755                                    userId);
12756                            if (userIdToKill == UserHandle.USER_ALL
12757                                    || userIdToKill >= UserHandle.USER_OWNER) {
12758                                // If gids changed for this user, kill all affected packages.
12759                                mHandler.post(new Runnable() {
12760                                    @Override
12761                                    public void run() {
12762                                        // This has to happen with no lock held.
12763                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12764                                                KILL_APP_REASON_GIDS_CHANGED);
12765                                    }
12766                                });
12767                                break;
12768                            }
12769                        }
12770                    }
12771                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12772                }
12773                // make sure to preserve per-user disabled state if this removal was just
12774                // a downgrade of a system app to the factory package
12775                if (allUserHandles != null && perUserInstalled != null) {
12776                    if (DEBUG_REMOVE) {
12777                        Slog.d(TAG, "Propagating install state across downgrade");
12778                    }
12779                    for (int i = 0; i < allUserHandles.length; i++) {
12780                        if (DEBUG_REMOVE) {
12781                            Slog.d(TAG, "    user " + allUserHandles[i]
12782                                    + " => " + perUserInstalled[i]);
12783                        }
12784                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12785                    }
12786                }
12787            }
12788            // can downgrade to reader
12789            if (writeSettings) {
12790                // Save settings now
12791                mSettings.writeLPr();
12792            }
12793        }
12794        if (outInfo != null) {
12795            // A user ID was deleted here. Go through all users and remove it
12796            // from KeyStore.
12797            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12798        }
12799    }
12800
12801    static boolean locationIsPrivileged(File path) {
12802        try {
12803            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12804                    .getCanonicalPath();
12805            return path.getCanonicalPath().startsWith(privilegedAppDir);
12806        } catch (IOException e) {
12807            Slog.e(TAG, "Unable to access code path " + path);
12808        }
12809        return false;
12810    }
12811
12812    /*
12813     * Tries to delete system package.
12814     */
12815    private boolean deleteSystemPackageLI(PackageSetting newPs,
12816            int[] allUserHandles, boolean[] perUserInstalled,
12817            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12818        final boolean applyUserRestrictions
12819                = (allUserHandles != null) && (perUserInstalled != null);
12820        PackageSetting disabledPs = null;
12821        // Confirm if the system package has been updated
12822        // An updated system app can be deleted. This will also have to restore
12823        // the system pkg from system partition
12824        // reader
12825        synchronized (mPackages) {
12826            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12827        }
12828        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12829                + " disabledPs=" + disabledPs);
12830        if (disabledPs == null) {
12831            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12832            return false;
12833        } else if (DEBUG_REMOVE) {
12834            Slog.d(TAG, "Deleting system pkg from data partition");
12835        }
12836        if (DEBUG_REMOVE) {
12837            if (applyUserRestrictions) {
12838                Slog.d(TAG, "Remembering install states:");
12839                for (int i = 0; i < allUserHandles.length; i++) {
12840                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12841                }
12842            }
12843        }
12844        // Delete the updated package
12845        outInfo.isRemovedPackageSystemUpdate = true;
12846        if (disabledPs.versionCode < newPs.versionCode) {
12847            // Delete data for downgrades
12848            flags &= ~PackageManager.DELETE_KEEP_DATA;
12849        } else {
12850            // Preserve data by setting flag
12851            flags |= PackageManager.DELETE_KEEP_DATA;
12852        }
12853        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12854                allUserHandles, perUserInstalled, outInfo, writeSettings);
12855        if (!ret) {
12856            return false;
12857        }
12858        // writer
12859        synchronized (mPackages) {
12860            // Reinstate the old system package
12861            mSettings.enableSystemPackageLPw(newPs.name);
12862            // Remove any native libraries from the upgraded package.
12863            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12864        }
12865        // Install the system package
12866        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12867        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12868        if (locationIsPrivileged(disabledPs.codePath)) {
12869            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12870        }
12871
12872        final PackageParser.Package newPkg;
12873        try {
12874            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12875        } catch (PackageManagerException e) {
12876            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12877            return false;
12878        }
12879
12880        // writer
12881        synchronized (mPackages) {
12882            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12883
12884            // Propagate the permissions state as we do want to drop on the floor
12885            // runtime permissions. The update permissions method below will take
12886            // care of removing obsolete permissions and grant install permissions.
12887            ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState());
12888            updatePermissionsLPw(newPkg.packageName, newPkg,
12889                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12890
12891            if (applyUserRestrictions) {
12892                if (DEBUG_REMOVE) {
12893                    Slog.d(TAG, "Propagating install state across reinstall");
12894                }
12895                for (int i = 0; i < allUserHandles.length; i++) {
12896                    if (DEBUG_REMOVE) {
12897                        Slog.d(TAG, "    user " + allUserHandles[i]
12898                                + " => " + perUserInstalled[i]);
12899                    }
12900                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12901                }
12902                // Regardless of writeSettings we need to ensure that this restriction
12903                // state propagation is persisted
12904                mSettings.writeAllUsersPackageRestrictionsLPr();
12905            }
12906            // can downgrade to reader here
12907            if (writeSettings) {
12908                mSettings.writeLPr();
12909            }
12910        }
12911        return true;
12912    }
12913
12914    private boolean deleteInstalledPackageLI(PackageSetting ps,
12915            boolean deleteCodeAndResources, int flags,
12916            int[] allUserHandles, boolean[] perUserInstalled,
12917            PackageRemovedInfo outInfo, boolean writeSettings) {
12918        if (outInfo != null) {
12919            outInfo.uid = ps.appId;
12920        }
12921
12922        // Delete package data from internal structures and also remove data if flag is set
12923        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12924
12925        // Delete application code and resources
12926        if (deleteCodeAndResources && (outInfo != null)) {
12927            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12928                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12929            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12930        }
12931        return true;
12932    }
12933
12934    @Override
12935    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12936            int userId) {
12937        mContext.enforceCallingOrSelfPermission(
12938                android.Manifest.permission.DELETE_PACKAGES, null);
12939        synchronized (mPackages) {
12940            PackageSetting ps = mSettings.mPackages.get(packageName);
12941            if (ps == null) {
12942                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12943                return false;
12944            }
12945            if (!ps.getInstalled(userId)) {
12946                // Can't block uninstall for an app that is not installed or enabled.
12947                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12948                return false;
12949            }
12950            ps.setBlockUninstall(blockUninstall, userId);
12951            mSettings.writePackageRestrictionsLPr(userId);
12952        }
12953        return true;
12954    }
12955
12956    @Override
12957    public boolean getBlockUninstallForUser(String packageName, int userId) {
12958        synchronized (mPackages) {
12959            PackageSetting ps = mSettings.mPackages.get(packageName);
12960            if (ps == null) {
12961                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12962                return false;
12963            }
12964            return ps.getBlockUninstall(userId);
12965        }
12966    }
12967
12968    /*
12969     * This method handles package deletion in general
12970     */
12971    private boolean deletePackageLI(String packageName, UserHandle user,
12972            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12973            int flags, PackageRemovedInfo outInfo,
12974            boolean writeSettings) {
12975        if (packageName == null) {
12976            Slog.w(TAG, "Attempt to delete null packageName.");
12977            return false;
12978        }
12979        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12980        PackageSetting ps;
12981        boolean dataOnly = false;
12982        int removeUser = -1;
12983        int appId = -1;
12984        synchronized (mPackages) {
12985            ps = mSettings.mPackages.get(packageName);
12986            if (ps == null) {
12987                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12988                return false;
12989            }
12990            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12991                    && user.getIdentifier() != UserHandle.USER_ALL) {
12992                // The caller is asking that the package only be deleted for a single
12993                // user.  To do this, we just mark its uninstalled state and delete
12994                // its data.  If this is a system app, we only allow this to happen if
12995                // they have set the special DELETE_SYSTEM_APP which requests different
12996                // semantics than normal for uninstalling system apps.
12997                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12998                ps.setUserState(user.getIdentifier(),
12999                        COMPONENT_ENABLED_STATE_DEFAULT,
13000                        false, //installed
13001                        true,  //stopped
13002                        true,  //notLaunched
13003                        false, //hidden
13004                        null, null, null,
13005                        false, // blockUninstall
13006                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0);
13007                if (!isSystemApp(ps)) {
13008                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13009                        // Other user 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, "Still installed by other users");
13013                        removeUser = user.getIdentifier();
13014                        appId = ps.appId;
13015                        scheduleWritePackageRestrictionsLocked(removeUser);
13016                    } else {
13017                        // We need to set it back to 'installed' so the uninstall
13018                        // broadcasts will be sent correctly.
13019                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13020                        ps.setInstalled(true, user.getIdentifier());
13021                    }
13022                } else {
13023                    // This is a system app, so we assume that the
13024                    // other users still have this package installed, so all
13025                    // we need to do is clear this user's data and save that
13026                    // it is uninstalled.
13027                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13028                    removeUser = user.getIdentifier();
13029                    appId = ps.appId;
13030                    scheduleWritePackageRestrictionsLocked(removeUser);
13031                }
13032            }
13033        }
13034
13035        if (removeUser >= 0) {
13036            // From above, we determined that we are deleting this only
13037            // for a single user.  Continue the work here.
13038            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13039            if (outInfo != null) {
13040                outInfo.removedPackage = packageName;
13041                outInfo.removedAppId = appId;
13042                outInfo.removedUsers = new int[] {removeUser};
13043            }
13044            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13045            removeKeystoreDataIfNeeded(removeUser, appId);
13046            schedulePackageCleaning(packageName, removeUser, false);
13047            synchronized (mPackages) {
13048                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13049                    scheduleWritePackageRestrictionsLocked(removeUser);
13050                }
13051                resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser);
13052            }
13053            return true;
13054        }
13055
13056        if (dataOnly) {
13057            // Delete application data first
13058            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13059            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13060            return true;
13061        }
13062
13063        boolean ret = false;
13064        if (isSystemApp(ps)) {
13065            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13066            // When an updated system application is deleted we delete the existing resources as well and
13067            // fall back to existing code in system partition
13068            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13069                    flags, outInfo, writeSettings);
13070        } else {
13071            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13072            // Kill application pre-emptively especially for apps on sd.
13073            killApplication(packageName, ps.appId, "uninstall pkg");
13074            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13075                    allUserHandles, perUserInstalled,
13076                    outInfo, writeSettings);
13077        }
13078
13079        return ret;
13080    }
13081
13082    private final class ClearStorageConnection implements ServiceConnection {
13083        IMediaContainerService mContainerService;
13084
13085        @Override
13086        public void onServiceConnected(ComponentName name, IBinder service) {
13087            synchronized (this) {
13088                mContainerService = IMediaContainerService.Stub.asInterface(service);
13089                notifyAll();
13090            }
13091        }
13092
13093        @Override
13094        public void onServiceDisconnected(ComponentName name) {
13095        }
13096    }
13097
13098    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13099        final boolean mounted;
13100        if (Environment.isExternalStorageEmulated()) {
13101            mounted = true;
13102        } else {
13103            final String status = Environment.getExternalStorageState();
13104
13105            mounted = status.equals(Environment.MEDIA_MOUNTED)
13106                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13107        }
13108
13109        if (!mounted) {
13110            return;
13111        }
13112
13113        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13114        int[] users;
13115        if (userId == UserHandle.USER_ALL) {
13116            users = sUserManager.getUserIds();
13117        } else {
13118            users = new int[] { userId };
13119        }
13120        final ClearStorageConnection conn = new ClearStorageConnection();
13121        if (mContext.bindServiceAsUser(
13122                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13123            try {
13124                for (int curUser : users) {
13125                    long timeout = SystemClock.uptimeMillis() + 5000;
13126                    synchronized (conn) {
13127                        long now = SystemClock.uptimeMillis();
13128                        while (conn.mContainerService == null && now < timeout) {
13129                            try {
13130                                conn.wait(timeout - now);
13131                            } catch (InterruptedException e) {
13132                            }
13133                        }
13134                    }
13135                    if (conn.mContainerService == null) {
13136                        return;
13137                    }
13138
13139                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13140                    clearDirectory(conn.mContainerService,
13141                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13142                    if (allData) {
13143                        clearDirectory(conn.mContainerService,
13144                                userEnv.buildExternalStorageAppDataDirs(packageName));
13145                        clearDirectory(conn.mContainerService,
13146                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13147                    }
13148                }
13149            } finally {
13150                mContext.unbindService(conn);
13151            }
13152        }
13153    }
13154
13155    @Override
13156    public void clearApplicationUserData(final String packageName,
13157            final IPackageDataObserver observer, final int userId) {
13158        mContext.enforceCallingOrSelfPermission(
13159                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13160        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13161        // Queue up an async operation since the package deletion may take a little while.
13162        mHandler.post(new Runnable() {
13163            public void run() {
13164                mHandler.removeCallbacks(this);
13165                final boolean succeeded;
13166                synchronized (mInstallLock) {
13167                    succeeded = clearApplicationUserDataLI(packageName, userId);
13168                }
13169                clearExternalStorageDataSync(packageName, userId, true);
13170                if (succeeded) {
13171                    // invoke DeviceStorageMonitor's update method to clear any notifications
13172                    DeviceStorageMonitorInternal
13173                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13174                    if (dsm != null) {
13175                        dsm.checkMemory();
13176                    }
13177                }
13178                if(observer != null) {
13179                    try {
13180                        observer.onRemoveCompleted(packageName, succeeded);
13181                    } catch (RemoteException e) {
13182                        Log.i(TAG, "Observer no longer exists.");
13183                    }
13184                } //end if observer
13185            } //end run
13186        });
13187    }
13188
13189    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13190        if (packageName == null) {
13191            Slog.w(TAG, "Attempt to delete null packageName.");
13192            return false;
13193        }
13194
13195        // Try finding details about the requested package
13196        PackageParser.Package pkg;
13197        synchronized (mPackages) {
13198            pkg = mPackages.get(packageName);
13199            if (pkg == null) {
13200                final PackageSetting ps = mSettings.mPackages.get(packageName);
13201                if (ps != null) {
13202                    pkg = ps.pkg;
13203                }
13204            }
13205
13206            if (pkg == null) {
13207                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13208                return false;
13209            }
13210
13211            PackageSetting ps = (PackageSetting) pkg.mExtras;
13212            resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
13213        }
13214
13215        // Always delete data directories for package, even if we found no other
13216        // record of app. This helps users recover from UID mismatches without
13217        // resorting to a full data wipe.
13218        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13219        if (retCode < 0) {
13220            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13221            return false;
13222        }
13223
13224        final int appId = pkg.applicationInfo.uid;
13225        removeKeystoreDataIfNeeded(userId, appId);
13226
13227        // Create a native library symlink only if we have native libraries
13228        // and if the native libraries are 32 bit libraries. We do not provide
13229        // this symlink for 64 bit libraries.
13230        if (pkg.applicationInfo.primaryCpuAbi != null &&
13231                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13232            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13233            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13234                    nativeLibPath, userId) < 0) {
13235                Slog.w(TAG, "Failed linking native library dir");
13236                return false;
13237            }
13238        }
13239
13240        return true;
13241    }
13242
13243    /**
13244     * Reverts user permission state changes (permissions and flags).
13245     *
13246     * @param ps The package for which to reset.
13247     * @param userId The device user for which to do a reset.
13248     */
13249    private void resetUserChangesToRuntimePermissionsAndFlagsLocked(
13250            final PackageSetting ps, final int userId) {
13251        if (ps.pkg == null) {
13252            return;
13253        }
13254
13255        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13256                | FLAG_PERMISSION_USER_FIXED
13257                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13258
13259        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13260                | FLAG_PERMISSION_POLICY_FIXED;
13261
13262        boolean writeInstallPermissions = false;
13263        boolean writeRuntimePermissions = false;
13264
13265        final int permissionCount = ps.pkg.requestedPermissions.size();
13266        for (int i = 0; i < permissionCount; i++) {
13267            String permission = ps.pkg.requestedPermissions.get(i);
13268
13269            BasePermission bp = mSettings.mPermissions.get(permission);
13270            if (bp == null) {
13271                continue;
13272            }
13273
13274            // If shared user we just reset the state to which only this app contributed.
13275            if (ps.sharedUser != null) {
13276                boolean used = false;
13277                final int packageCount = ps.sharedUser.packages.size();
13278                for (int j = 0; j < packageCount; j++) {
13279                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13280                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13281                            && pkg.pkg.requestedPermissions.contains(permission)) {
13282                        used = true;
13283                        break;
13284                    }
13285                }
13286                if (used) {
13287                    continue;
13288                }
13289            }
13290
13291            PermissionsState permissionsState = ps.getPermissionsState();
13292
13293            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13294
13295            // Always clear the user settable flags.
13296            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13297                    bp.name) != null;
13298            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13299                if (hasInstallState) {
13300                    writeInstallPermissions = true;
13301                } else {
13302                    writeRuntimePermissions = true;
13303                }
13304            }
13305
13306            // Below is only runtime permission handling.
13307            if (!bp.isRuntime()) {
13308                continue;
13309            }
13310
13311            // Never clobber system or policy.
13312            if ((oldFlags & policyOrSystemFlags) != 0) {
13313                continue;
13314            }
13315
13316            // If this permission was granted by default, make sure it is.
13317            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13318                if (permissionsState.grantRuntimePermission(bp, userId)
13319                        != PERMISSION_OPERATION_FAILURE) {
13320                    writeRuntimePermissions = true;
13321                }
13322            } else {
13323                // Otherwise, reset the permission.
13324                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13325                switch (revokeResult) {
13326                    case PERMISSION_OPERATION_SUCCESS: {
13327                        writeRuntimePermissions = true;
13328                    } break;
13329
13330                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13331                        writeRuntimePermissions = true;
13332                        // If gids changed for this user, kill all affected packages.
13333                        mHandler.post(new Runnable() {
13334                            @Override
13335                            public void run() {
13336                                // This has to happen with no lock held.
13337                                killSettingPackagesForUser(ps, userId,
13338                                        KILL_APP_REASON_GIDS_CHANGED);
13339                            }
13340                        });
13341                    } break;
13342                }
13343            }
13344        }
13345
13346        // Synchronously write as we are taking permissions away.
13347        if (writeRuntimePermissions) {
13348            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13349        }
13350
13351        // Synchronously write as we are taking permissions away.
13352        if (writeInstallPermissions) {
13353            mSettings.writeLPr();
13354        }
13355    }
13356
13357    /**
13358     * Remove entries from the keystore daemon. Will only remove it if the
13359     * {@code appId} is valid.
13360     */
13361    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13362        if (appId < 0) {
13363            return;
13364        }
13365
13366        final KeyStore keyStore = KeyStore.getInstance();
13367        if (keyStore != null) {
13368            if (userId == UserHandle.USER_ALL) {
13369                for (final int individual : sUserManager.getUserIds()) {
13370                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13371                }
13372            } else {
13373                keyStore.clearUid(UserHandle.getUid(userId, appId));
13374            }
13375        } else {
13376            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13377        }
13378    }
13379
13380    @Override
13381    public void deleteApplicationCacheFiles(final String packageName,
13382            final IPackageDataObserver observer) {
13383        mContext.enforceCallingOrSelfPermission(
13384                android.Manifest.permission.DELETE_CACHE_FILES, null);
13385        // Queue up an async operation since the package deletion may take a little while.
13386        final int userId = UserHandle.getCallingUserId();
13387        mHandler.post(new Runnable() {
13388            public void run() {
13389                mHandler.removeCallbacks(this);
13390                final boolean succeded;
13391                synchronized (mInstallLock) {
13392                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13393                }
13394                clearExternalStorageDataSync(packageName, userId, false);
13395                if (observer != null) {
13396                    try {
13397                        observer.onRemoveCompleted(packageName, succeded);
13398                    } catch (RemoteException e) {
13399                        Log.i(TAG, "Observer no longer exists.");
13400                    }
13401                } //end if observer
13402            } //end run
13403        });
13404    }
13405
13406    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13407        if (packageName == null) {
13408            Slog.w(TAG, "Attempt to delete null packageName.");
13409            return false;
13410        }
13411        PackageParser.Package p;
13412        synchronized (mPackages) {
13413            p = mPackages.get(packageName);
13414        }
13415        if (p == null) {
13416            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13417            return false;
13418        }
13419        final ApplicationInfo applicationInfo = p.applicationInfo;
13420        if (applicationInfo == null) {
13421            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13422            return false;
13423        }
13424        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13425        if (retCode < 0) {
13426            Slog.w(TAG, "Couldn't remove cache files for package: "
13427                       + packageName + " u" + userId);
13428            return false;
13429        }
13430        return true;
13431    }
13432
13433    @Override
13434    public void getPackageSizeInfo(final String packageName, int userHandle,
13435            final IPackageStatsObserver observer) {
13436        mContext.enforceCallingOrSelfPermission(
13437                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13438        if (packageName == null) {
13439            throw new IllegalArgumentException("Attempt to get size of null packageName");
13440        }
13441
13442        PackageStats stats = new PackageStats(packageName, userHandle);
13443
13444        /*
13445         * Queue up an async operation since the package measurement may take a
13446         * little while.
13447         */
13448        Message msg = mHandler.obtainMessage(INIT_COPY);
13449        msg.obj = new MeasureParams(stats, observer);
13450        mHandler.sendMessage(msg);
13451    }
13452
13453    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13454            PackageStats pStats) {
13455        if (packageName == null) {
13456            Slog.w(TAG, "Attempt to get size of null packageName.");
13457            return false;
13458        }
13459        PackageParser.Package p;
13460        boolean dataOnly = false;
13461        String libDirRoot = null;
13462        String asecPath = null;
13463        PackageSetting ps = null;
13464        synchronized (mPackages) {
13465            p = mPackages.get(packageName);
13466            ps = mSettings.mPackages.get(packageName);
13467            if(p == null) {
13468                dataOnly = true;
13469                if((ps == null) || (ps.pkg == null)) {
13470                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13471                    return false;
13472                }
13473                p = ps.pkg;
13474            }
13475            if (ps != null) {
13476                libDirRoot = ps.legacyNativeLibraryPathString;
13477            }
13478            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13479                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13480                if (secureContainerId != null) {
13481                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13482                }
13483            }
13484        }
13485        String publicSrcDir = null;
13486        if(!dataOnly) {
13487            final ApplicationInfo applicationInfo = p.applicationInfo;
13488            if (applicationInfo == null) {
13489                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13490                return false;
13491            }
13492            if (p.isForwardLocked()) {
13493                publicSrcDir = applicationInfo.getBaseResourcePath();
13494            }
13495        }
13496        // TODO: extend to measure size of split APKs
13497        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13498        // not just the first level.
13499        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13500        // just the primary.
13501        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13502        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13503                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13504        if (res < 0) {
13505            return false;
13506        }
13507
13508        // Fix-up for forward-locked applications in ASEC containers.
13509        if (!isExternal(p)) {
13510            pStats.codeSize += pStats.externalCodeSize;
13511            pStats.externalCodeSize = 0L;
13512        }
13513
13514        return true;
13515    }
13516
13517
13518    @Override
13519    public void addPackageToPreferred(String packageName) {
13520        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13521    }
13522
13523    @Override
13524    public void removePackageFromPreferred(String packageName) {
13525        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13526    }
13527
13528    @Override
13529    public List<PackageInfo> getPreferredPackages(int flags) {
13530        return new ArrayList<PackageInfo>();
13531    }
13532
13533    private int getUidTargetSdkVersionLockedLPr(int uid) {
13534        Object obj = mSettings.getUserIdLPr(uid);
13535        if (obj instanceof SharedUserSetting) {
13536            final SharedUserSetting sus = (SharedUserSetting) obj;
13537            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13538            final Iterator<PackageSetting> it = sus.packages.iterator();
13539            while (it.hasNext()) {
13540                final PackageSetting ps = it.next();
13541                if (ps.pkg != null) {
13542                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13543                    if (v < vers) vers = v;
13544                }
13545            }
13546            return vers;
13547        } else if (obj instanceof PackageSetting) {
13548            final PackageSetting ps = (PackageSetting) obj;
13549            if (ps.pkg != null) {
13550                return ps.pkg.applicationInfo.targetSdkVersion;
13551            }
13552        }
13553        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13554    }
13555
13556    @Override
13557    public void addPreferredActivity(IntentFilter filter, int match,
13558            ComponentName[] set, ComponentName activity, int userId) {
13559        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13560                "Adding preferred");
13561    }
13562
13563    private void addPreferredActivityInternal(IntentFilter filter, int match,
13564            ComponentName[] set, ComponentName activity, boolean always, int userId,
13565            String opname) {
13566        // writer
13567        int callingUid = Binder.getCallingUid();
13568        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13569        if (filter.countActions() == 0) {
13570            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13571            return;
13572        }
13573        synchronized (mPackages) {
13574            if (mContext.checkCallingOrSelfPermission(
13575                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13576                    != PackageManager.PERMISSION_GRANTED) {
13577                if (getUidTargetSdkVersionLockedLPr(callingUid)
13578                        < Build.VERSION_CODES.FROYO) {
13579                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13580                            + callingUid);
13581                    return;
13582                }
13583                mContext.enforceCallingOrSelfPermission(
13584                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13585            }
13586
13587            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13588            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13589                    + userId + ":");
13590            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13591            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13592            scheduleWritePackageRestrictionsLocked(userId);
13593        }
13594    }
13595
13596    @Override
13597    public void replacePreferredActivity(IntentFilter filter, int match,
13598            ComponentName[] set, ComponentName activity, int userId) {
13599        if (filter.countActions() != 1) {
13600            throw new IllegalArgumentException(
13601                    "replacePreferredActivity expects filter to have only 1 action.");
13602        }
13603        if (filter.countDataAuthorities() != 0
13604                || filter.countDataPaths() != 0
13605                || filter.countDataSchemes() > 1
13606                || filter.countDataTypes() != 0) {
13607            throw new IllegalArgumentException(
13608                    "replacePreferredActivity expects filter to have no data authorities, " +
13609                    "paths, or types; and at most one scheme.");
13610        }
13611
13612        final int callingUid = Binder.getCallingUid();
13613        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13614        synchronized (mPackages) {
13615            if (mContext.checkCallingOrSelfPermission(
13616                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13617                    != PackageManager.PERMISSION_GRANTED) {
13618                if (getUidTargetSdkVersionLockedLPr(callingUid)
13619                        < Build.VERSION_CODES.FROYO) {
13620                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13621                            + Binder.getCallingUid());
13622                    return;
13623                }
13624                mContext.enforceCallingOrSelfPermission(
13625                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13626            }
13627
13628            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13629            if (pir != null) {
13630                // Get all of the existing entries that exactly match this filter.
13631                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13632                if (existing != null && existing.size() == 1) {
13633                    PreferredActivity cur = existing.get(0);
13634                    if (DEBUG_PREFERRED) {
13635                        Slog.i(TAG, "Checking replace of preferred:");
13636                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13637                        if (!cur.mPref.mAlways) {
13638                            Slog.i(TAG, "  -- CUR; not mAlways!");
13639                        } else {
13640                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13641                            Slog.i(TAG, "  -- CUR: mSet="
13642                                    + Arrays.toString(cur.mPref.mSetComponents));
13643                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13644                            Slog.i(TAG, "  -- NEW: mMatch="
13645                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13646                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13647                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13648                        }
13649                    }
13650                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13651                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13652                            && cur.mPref.sameSet(set)) {
13653                        // Setting the preferred activity to what it happens to be already
13654                        if (DEBUG_PREFERRED) {
13655                            Slog.i(TAG, "Replacing with same preferred activity "
13656                                    + cur.mPref.mShortComponent + " for user "
13657                                    + userId + ":");
13658                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13659                        }
13660                        return;
13661                    }
13662                }
13663
13664                if (existing != null) {
13665                    if (DEBUG_PREFERRED) {
13666                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13667                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13668                    }
13669                    for (int i = 0; i < existing.size(); i++) {
13670                        PreferredActivity pa = existing.get(i);
13671                        if (DEBUG_PREFERRED) {
13672                            Slog.i(TAG, "Removing existing preferred activity "
13673                                    + pa.mPref.mComponent + ":");
13674                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13675                        }
13676                        pir.removeFilter(pa);
13677                    }
13678                }
13679            }
13680            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13681                    "Replacing preferred");
13682        }
13683    }
13684
13685    @Override
13686    public void clearPackagePreferredActivities(String packageName) {
13687        final int uid = Binder.getCallingUid();
13688        // writer
13689        synchronized (mPackages) {
13690            PackageParser.Package pkg = mPackages.get(packageName);
13691            if (pkg == null || pkg.applicationInfo.uid != uid) {
13692                if (mContext.checkCallingOrSelfPermission(
13693                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13694                        != PackageManager.PERMISSION_GRANTED) {
13695                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13696                            < Build.VERSION_CODES.FROYO) {
13697                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13698                                + Binder.getCallingUid());
13699                        return;
13700                    }
13701                    mContext.enforceCallingOrSelfPermission(
13702                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13703                }
13704            }
13705
13706            int user = UserHandle.getCallingUserId();
13707            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13708                scheduleWritePackageRestrictionsLocked(user);
13709            }
13710        }
13711    }
13712
13713    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13714    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13715        ArrayList<PreferredActivity> removed = null;
13716        boolean changed = false;
13717        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13718            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13719            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13720            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13721                continue;
13722            }
13723            Iterator<PreferredActivity> it = pir.filterIterator();
13724            while (it.hasNext()) {
13725                PreferredActivity pa = it.next();
13726                // Mark entry for removal only if it matches the package name
13727                // and the entry is of type "always".
13728                if (packageName == null ||
13729                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13730                                && pa.mPref.mAlways)) {
13731                    if (removed == null) {
13732                        removed = new ArrayList<PreferredActivity>();
13733                    }
13734                    removed.add(pa);
13735                }
13736            }
13737            if (removed != null) {
13738                for (int j=0; j<removed.size(); j++) {
13739                    PreferredActivity pa = removed.get(j);
13740                    pir.removeFilter(pa);
13741                }
13742                changed = true;
13743            }
13744        }
13745        return changed;
13746    }
13747
13748    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13749    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13750        if (userId == UserHandle.USER_ALL) {
13751            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13752                    sUserManager.getUserIds())) {
13753                for (int oneUserId : sUserManager.getUserIds()) {
13754                    scheduleWritePackageRestrictionsLocked(oneUserId);
13755                }
13756            }
13757        } else {
13758            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13759                scheduleWritePackageRestrictionsLocked(userId);
13760            }
13761        }
13762    }
13763
13764
13765    void clearDefaultBrowserIfNeeded(String packageName) {
13766        for (int oneUserId : sUserManager.getUserIds()) {
13767            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13768            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13769            if (packageName.equals(defaultBrowserPackageName)) {
13770                setDefaultBrowserPackageName(null, oneUserId);
13771            }
13772        }
13773    }
13774
13775    @Override
13776    public void resetPreferredActivities(int userId) {
13777        mContext.enforceCallingOrSelfPermission(
13778                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13779        // writer
13780        synchronized (mPackages) {
13781            clearPackagePreferredActivitiesLPw(null, userId);
13782            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13783            applyFactoryDefaultBrowserLPw(userId);
13784            primeDomainVerificationsLPw(userId);
13785
13786            scheduleWritePackageRestrictionsLocked(userId);
13787        }
13788    }
13789
13790    @Override
13791    public int getPreferredActivities(List<IntentFilter> outFilters,
13792            List<ComponentName> outActivities, String packageName) {
13793
13794        int num = 0;
13795        final int userId = UserHandle.getCallingUserId();
13796        // reader
13797        synchronized (mPackages) {
13798            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13799            if (pir != null) {
13800                final Iterator<PreferredActivity> it = pir.filterIterator();
13801                while (it.hasNext()) {
13802                    final PreferredActivity pa = it.next();
13803                    if (packageName == null
13804                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13805                                    && pa.mPref.mAlways)) {
13806                        if (outFilters != null) {
13807                            outFilters.add(new IntentFilter(pa));
13808                        }
13809                        if (outActivities != null) {
13810                            outActivities.add(pa.mPref.mComponent);
13811                        }
13812                    }
13813                }
13814            }
13815        }
13816
13817        return num;
13818    }
13819
13820    @Override
13821    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13822            int userId) {
13823        int callingUid = Binder.getCallingUid();
13824        if (callingUid != Process.SYSTEM_UID) {
13825            throw new SecurityException(
13826                    "addPersistentPreferredActivity can only be run by the system");
13827        }
13828        if (filter.countActions() == 0) {
13829            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13830            return;
13831        }
13832        synchronized (mPackages) {
13833            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13834                    " :");
13835            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13836            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13837                    new PersistentPreferredActivity(filter, activity));
13838            scheduleWritePackageRestrictionsLocked(userId);
13839        }
13840    }
13841
13842    @Override
13843    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13844        int callingUid = Binder.getCallingUid();
13845        if (callingUid != Process.SYSTEM_UID) {
13846            throw new SecurityException(
13847                    "clearPackagePersistentPreferredActivities can only be run by the system");
13848        }
13849        ArrayList<PersistentPreferredActivity> removed = null;
13850        boolean changed = false;
13851        synchronized (mPackages) {
13852            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13853                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13854                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13855                        .valueAt(i);
13856                if (userId != thisUserId) {
13857                    continue;
13858                }
13859                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13860                while (it.hasNext()) {
13861                    PersistentPreferredActivity ppa = it.next();
13862                    // Mark entry for removal only if it matches the package name.
13863                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13864                        if (removed == null) {
13865                            removed = new ArrayList<PersistentPreferredActivity>();
13866                        }
13867                        removed.add(ppa);
13868                    }
13869                }
13870                if (removed != null) {
13871                    for (int j=0; j<removed.size(); j++) {
13872                        PersistentPreferredActivity ppa = removed.get(j);
13873                        ppir.removeFilter(ppa);
13874                    }
13875                    changed = true;
13876                }
13877            }
13878
13879            if (changed) {
13880                scheduleWritePackageRestrictionsLocked(userId);
13881            }
13882        }
13883    }
13884
13885    /**
13886     * Common machinery for picking apart a restored XML blob and passing
13887     * it to a caller-supplied functor to be applied to the running system.
13888     */
13889    private void restoreFromXml(XmlPullParser parser, int userId,
13890            String expectedStartTag, BlobXmlRestorer functor)
13891            throws IOException, XmlPullParserException {
13892        int type;
13893        while ((type = parser.next()) != XmlPullParser.START_TAG
13894                && type != XmlPullParser.END_DOCUMENT) {
13895        }
13896        if (type != XmlPullParser.START_TAG) {
13897            // oops didn't find a start tag?!
13898            if (DEBUG_BACKUP) {
13899                Slog.e(TAG, "Didn't find start tag during restore");
13900            }
13901            return;
13902        }
13903
13904        // this is supposed to be TAG_PREFERRED_BACKUP
13905        if (!expectedStartTag.equals(parser.getName())) {
13906            if (DEBUG_BACKUP) {
13907                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13908            }
13909            return;
13910        }
13911
13912        // skip interfering stuff, then we're aligned with the backing implementation
13913        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13914        functor.apply(parser, userId);
13915    }
13916
13917    private interface BlobXmlRestorer {
13918        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13919    }
13920
13921    /**
13922     * Non-Binder method, support for the backup/restore mechanism: write the
13923     * full set of preferred activities in its canonical XML format.  Returns the
13924     * XML output as a byte array, or null if there is none.
13925     */
13926    @Override
13927    public byte[] getPreferredActivityBackup(int userId) {
13928        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13929            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13930        }
13931
13932        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13933        try {
13934            final XmlSerializer serializer = new FastXmlSerializer();
13935            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13936            serializer.startDocument(null, true);
13937            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13938
13939            synchronized (mPackages) {
13940                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13941            }
13942
13943            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13944            serializer.endDocument();
13945            serializer.flush();
13946        } catch (Exception e) {
13947            if (DEBUG_BACKUP) {
13948                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13949            }
13950            return null;
13951        }
13952
13953        return dataStream.toByteArray();
13954    }
13955
13956    @Override
13957    public void restorePreferredActivities(byte[] backup, int userId) {
13958        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13959            throw new SecurityException("Only the system may call restorePreferredActivities()");
13960        }
13961
13962        try {
13963            final XmlPullParser parser = Xml.newPullParser();
13964            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13965            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13966                    new BlobXmlRestorer() {
13967                        @Override
13968                        public void apply(XmlPullParser parser, int userId)
13969                                throws XmlPullParserException, IOException {
13970                            synchronized (mPackages) {
13971                                mSettings.readPreferredActivitiesLPw(parser, userId);
13972                            }
13973                        }
13974                    } );
13975        } catch (Exception e) {
13976            if (DEBUG_BACKUP) {
13977                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13978            }
13979        }
13980    }
13981
13982    /**
13983     * Non-Binder method, support for the backup/restore mechanism: write the
13984     * default browser (etc) settings in its canonical XML format.  Returns the default
13985     * browser XML representation as a byte array, or null if there is none.
13986     */
13987    @Override
13988    public byte[] getDefaultAppsBackup(int userId) {
13989        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13990            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13991        }
13992
13993        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13994        try {
13995            final XmlSerializer serializer = new FastXmlSerializer();
13996            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13997            serializer.startDocument(null, true);
13998            serializer.startTag(null, TAG_DEFAULT_APPS);
13999
14000            synchronized (mPackages) {
14001                mSettings.writeDefaultAppsLPr(serializer, userId);
14002            }
14003
14004            serializer.endTag(null, TAG_DEFAULT_APPS);
14005            serializer.endDocument();
14006            serializer.flush();
14007        } catch (Exception e) {
14008            if (DEBUG_BACKUP) {
14009                Slog.e(TAG, "Unable to write default apps for backup", e);
14010            }
14011            return null;
14012        }
14013
14014        return dataStream.toByteArray();
14015    }
14016
14017    @Override
14018    public void restoreDefaultApps(byte[] backup, int userId) {
14019        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14020            throw new SecurityException("Only the system may call restoreDefaultApps()");
14021        }
14022
14023        try {
14024            final XmlPullParser parser = Xml.newPullParser();
14025            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14026            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14027                    new BlobXmlRestorer() {
14028                        @Override
14029                        public void apply(XmlPullParser parser, int userId)
14030                                throws XmlPullParserException, IOException {
14031                            synchronized (mPackages) {
14032                                mSettings.readDefaultAppsLPw(parser, userId);
14033                            }
14034                        }
14035                    } );
14036        } catch (Exception e) {
14037            if (DEBUG_BACKUP) {
14038                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14039            }
14040        }
14041    }
14042
14043    @Override
14044    public byte[] getIntentFilterVerificationBackup(int userId) {
14045        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14046            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14047        }
14048
14049        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14050        try {
14051            final XmlSerializer serializer = new FastXmlSerializer();
14052            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14053            serializer.startDocument(null, true);
14054            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14055
14056            synchronized (mPackages) {
14057                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14058            }
14059
14060            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14061            serializer.endDocument();
14062            serializer.flush();
14063        } catch (Exception e) {
14064            if (DEBUG_BACKUP) {
14065                Slog.e(TAG, "Unable to write default apps for backup", e);
14066            }
14067            return null;
14068        }
14069
14070        return dataStream.toByteArray();
14071    }
14072
14073    @Override
14074    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14075        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14076            throw new SecurityException("Only the system may call restorePreferredActivities()");
14077        }
14078
14079        try {
14080            final XmlPullParser parser = Xml.newPullParser();
14081            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14082            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14083                    new BlobXmlRestorer() {
14084                        @Override
14085                        public void apply(XmlPullParser parser, int userId)
14086                                throws XmlPullParserException, IOException {
14087                            synchronized (mPackages) {
14088                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14089                                mSettings.writeLPr();
14090                            }
14091                        }
14092                    } );
14093        } catch (Exception e) {
14094            if (DEBUG_BACKUP) {
14095                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14096            }
14097        }
14098    }
14099
14100    @Override
14101    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14102            int sourceUserId, int targetUserId, int flags) {
14103        mContext.enforceCallingOrSelfPermission(
14104                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14105        int callingUid = Binder.getCallingUid();
14106        enforceOwnerRights(ownerPackage, callingUid);
14107        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14108        if (intentFilter.countActions() == 0) {
14109            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14110            return;
14111        }
14112        synchronized (mPackages) {
14113            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14114                    ownerPackage, targetUserId, flags);
14115            CrossProfileIntentResolver resolver =
14116                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14117            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14118            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14119            if (existing != null) {
14120                int size = existing.size();
14121                for (int i = 0; i < size; i++) {
14122                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14123                        return;
14124                    }
14125                }
14126            }
14127            resolver.addFilter(newFilter);
14128            scheduleWritePackageRestrictionsLocked(sourceUserId);
14129        }
14130    }
14131
14132    @Override
14133    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14134        mContext.enforceCallingOrSelfPermission(
14135                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14136        int callingUid = Binder.getCallingUid();
14137        enforceOwnerRights(ownerPackage, callingUid);
14138        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14139        synchronized (mPackages) {
14140            CrossProfileIntentResolver resolver =
14141                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14142            ArraySet<CrossProfileIntentFilter> set =
14143                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14144            for (CrossProfileIntentFilter filter : set) {
14145                if (filter.getOwnerPackage().equals(ownerPackage)) {
14146                    resolver.removeFilter(filter);
14147                }
14148            }
14149            scheduleWritePackageRestrictionsLocked(sourceUserId);
14150        }
14151    }
14152
14153    // Enforcing that callingUid is owning pkg on userId
14154    private void enforceOwnerRights(String pkg, int callingUid) {
14155        // The system owns everything.
14156        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14157            return;
14158        }
14159        int callingUserId = UserHandle.getUserId(callingUid);
14160        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14161        if (pi == null) {
14162            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14163                    + callingUserId);
14164        }
14165        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14166            throw new SecurityException("Calling uid " + callingUid
14167                    + " does not own package " + pkg);
14168        }
14169    }
14170
14171    @Override
14172    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14173        Intent intent = new Intent(Intent.ACTION_MAIN);
14174        intent.addCategory(Intent.CATEGORY_HOME);
14175
14176        final int callingUserId = UserHandle.getCallingUserId();
14177        List<ResolveInfo> list = queryIntentActivities(intent, null,
14178                PackageManager.GET_META_DATA, callingUserId);
14179        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14180                true, false, false, callingUserId);
14181
14182        allHomeCandidates.clear();
14183        if (list != null) {
14184            for (ResolveInfo ri : list) {
14185                allHomeCandidates.add(ri);
14186            }
14187        }
14188        return (preferred == null || preferred.activityInfo == null)
14189                ? null
14190                : new ComponentName(preferred.activityInfo.packageName,
14191                        preferred.activityInfo.name);
14192    }
14193
14194    @Override
14195    public void setApplicationEnabledSetting(String appPackageName,
14196            int newState, int flags, int userId, String callingPackage) {
14197        if (!sUserManager.exists(userId)) return;
14198        if (callingPackage == null) {
14199            callingPackage = Integer.toString(Binder.getCallingUid());
14200        }
14201        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14202    }
14203
14204    @Override
14205    public void setComponentEnabledSetting(ComponentName componentName,
14206            int newState, int flags, int userId) {
14207        if (!sUserManager.exists(userId)) return;
14208        setEnabledSetting(componentName.getPackageName(),
14209                componentName.getClassName(), newState, flags, userId, null);
14210    }
14211
14212    private void setEnabledSetting(final String packageName, String className, int newState,
14213            final int flags, int userId, String callingPackage) {
14214        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14215              || newState == COMPONENT_ENABLED_STATE_ENABLED
14216              || newState == COMPONENT_ENABLED_STATE_DISABLED
14217              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14218              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14219            throw new IllegalArgumentException("Invalid new component state: "
14220                    + newState);
14221        }
14222        PackageSetting pkgSetting;
14223        final int uid = Binder.getCallingUid();
14224        final int permission = mContext.checkCallingOrSelfPermission(
14225                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14226        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14227        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14228        boolean sendNow = false;
14229        boolean isApp = (className == null);
14230        String componentName = isApp ? packageName : className;
14231        int packageUid = -1;
14232        ArrayList<String> components;
14233
14234        // writer
14235        synchronized (mPackages) {
14236            pkgSetting = mSettings.mPackages.get(packageName);
14237            if (pkgSetting == null) {
14238                if (className == null) {
14239                    throw new IllegalArgumentException(
14240                            "Unknown package: " + packageName);
14241                }
14242                throw new IllegalArgumentException(
14243                        "Unknown component: " + packageName
14244                        + "/" + className);
14245            }
14246            // Allow root and verify that userId is not being specified by a different user
14247            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14248                throw new SecurityException(
14249                        "Permission Denial: attempt to change component state from pid="
14250                        + Binder.getCallingPid()
14251                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14252            }
14253            if (className == null) {
14254                // We're dealing with an application/package level state change
14255                if (pkgSetting.getEnabled(userId) == newState) {
14256                    // Nothing to do
14257                    return;
14258                }
14259                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14260                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14261                    // Don't care about who enables an app.
14262                    callingPackage = null;
14263                }
14264                pkgSetting.setEnabled(newState, userId, callingPackage);
14265                // pkgSetting.pkg.mSetEnabled = newState;
14266            } else {
14267                // We're dealing with a component level state change
14268                // First, verify that this is a valid class name.
14269                PackageParser.Package pkg = pkgSetting.pkg;
14270                if (pkg == null || !pkg.hasComponentClassName(className)) {
14271                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14272                        throw new IllegalArgumentException("Component class " + className
14273                                + " does not exist in " + packageName);
14274                    } else {
14275                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14276                                + className + " does not exist in " + packageName);
14277                    }
14278                }
14279                switch (newState) {
14280                case COMPONENT_ENABLED_STATE_ENABLED:
14281                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14282                        return;
14283                    }
14284                    break;
14285                case COMPONENT_ENABLED_STATE_DISABLED:
14286                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14287                        return;
14288                    }
14289                    break;
14290                case COMPONENT_ENABLED_STATE_DEFAULT:
14291                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14292                        return;
14293                    }
14294                    break;
14295                default:
14296                    Slog.e(TAG, "Invalid new component state: " + newState);
14297                    return;
14298                }
14299            }
14300            scheduleWritePackageRestrictionsLocked(userId);
14301            components = mPendingBroadcasts.get(userId, packageName);
14302            final boolean newPackage = components == null;
14303            if (newPackage) {
14304                components = new ArrayList<String>();
14305            }
14306            if (!components.contains(componentName)) {
14307                components.add(componentName);
14308            }
14309            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14310                sendNow = true;
14311                // Purge entry from pending broadcast list if another one exists already
14312                // since we are sending one right away.
14313                mPendingBroadcasts.remove(userId, packageName);
14314            } else {
14315                if (newPackage) {
14316                    mPendingBroadcasts.put(userId, packageName, components);
14317                }
14318                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14319                    // Schedule a message
14320                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14321                }
14322            }
14323        }
14324
14325        long callingId = Binder.clearCallingIdentity();
14326        try {
14327            if (sendNow) {
14328                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14329                sendPackageChangedBroadcast(packageName,
14330                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14331            }
14332        } finally {
14333            Binder.restoreCallingIdentity(callingId);
14334        }
14335    }
14336
14337    private void sendPackageChangedBroadcast(String packageName,
14338            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14339        if (DEBUG_INSTALL)
14340            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14341                    + componentNames);
14342        Bundle extras = new Bundle(4);
14343        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14344        String nameList[] = new String[componentNames.size()];
14345        componentNames.toArray(nameList);
14346        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14347        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14348        extras.putInt(Intent.EXTRA_UID, packageUid);
14349        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14350                new int[] {UserHandle.getUserId(packageUid)});
14351    }
14352
14353    @Override
14354    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14355        if (!sUserManager.exists(userId)) return;
14356        final int uid = Binder.getCallingUid();
14357        final int permission = mContext.checkCallingOrSelfPermission(
14358                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14359        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14360        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14361        // writer
14362        synchronized (mPackages) {
14363            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14364                    allowedByPermission, uid, userId)) {
14365                scheduleWritePackageRestrictionsLocked(userId);
14366            }
14367        }
14368    }
14369
14370    @Override
14371    public String getInstallerPackageName(String packageName) {
14372        // reader
14373        synchronized (mPackages) {
14374            return mSettings.getInstallerPackageNameLPr(packageName);
14375        }
14376    }
14377
14378    @Override
14379    public int getApplicationEnabledSetting(String packageName, int userId) {
14380        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14381        int uid = Binder.getCallingUid();
14382        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14383        // reader
14384        synchronized (mPackages) {
14385            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14386        }
14387    }
14388
14389    @Override
14390    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14391        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14392        int uid = Binder.getCallingUid();
14393        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14394        // reader
14395        synchronized (mPackages) {
14396            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14397        }
14398    }
14399
14400    @Override
14401    public void enterSafeMode() {
14402        enforceSystemOrRoot("Only the system can request entering safe mode");
14403
14404        if (!mSystemReady) {
14405            mSafeMode = true;
14406        }
14407    }
14408
14409    @Override
14410    public void systemReady() {
14411        mSystemReady = true;
14412
14413        // Read the compatibilty setting when the system is ready.
14414        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14415                mContext.getContentResolver(),
14416                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14417        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14418        if (DEBUG_SETTINGS) {
14419            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14420        }
14421
14422        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14423
14424        synchronized (mPackages) {
14425            // Verify that all of the preferred activity components actually
14426            // exist.  It is possible for applications to be updated and at
14427            // that point remove a previously declared activity component that
14428            // had been set as a preferred activity.  We try to clean this up
14429            // the next time we encounter that preferred activity, but it is
14430            // possible for the user flow to never be able to return to that
14431            // situation so here we do a sanity check to make sure we haven't
14432            // left any junk around.
14433            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14434            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14435                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14436                removed.clear();
14437                for (PreferredActivity pa : pir.filterSet()) {
14438                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14439                        removed.add(pa);
14440                    }
14441                }
14442                if (removed.size() > 0) {
14443                    for (int r=0; r<removed.size(); r++) {
14444                        PreferredActivity pa = removed.get(r);
14445                        Slog.w(TAG, "Removing dangling preferred activity: "
14446                                + pa.mPref.mComponent);
14447                        pir.removeFilter(pa);
14448                    }
14449                    mSettings.writePackageRestrictionsLPr(
14450                            mSettings.mPreferredActivities.keyAt(i));
14451                }
14452            }
14453
14454            for (int userId : UserManagerService.getInstance().getUserIds()) {
14455                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14456                    grantPermissionsUserIds = ArrayUtils.appendInt(
14457                            grantPermissionsUserIds, userId);
14458                }
14459            }
14460        }
14461        sUserManager.systemReady();
14462
14463        // If we upgraded grant all default permissions before kicking off.
14464        for (int userId : grantPermissionsUserIds) {
14465            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14466        }
14467
14468        // Kick off any messages waiting for system ready
14469        if (mPostSystemReadyMessages != null) {
14470            for (Message msg : mPostSystemReadyMessages) {
14471                msg.sendToTarget();
14472            }
14473            mPostSystemReadyMessages = null;
14474        }
14475
14476        // Watch for external volumes that come and go over time
14477        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14478        storage.registerListener(mStorageListener);
14479
14480        mInstallerService.systemReady();
14481        mPackageDexOptimizer.systemReady();
14482
14483        MountServiceInternal mountServiceInternal = LocalServices.getService(
14484                MountServiceInternal.class);
14485        mountServiceInternal.addExternalStoragePolicy(
14486                new MountServiceInternal.ExternalStorageMountPolicy() {
14487            @Override
14488            public int getMountMode(int uid, String packageName) {
14489                if (Process.isIsolated(uid)) {
14490                    return Zygote.MOUNT_EXTERNAL_NONE;
14491                }
14492                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14493                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14494                }
14495                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14496                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14497                }
14498                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14499                    return Zygote.MOUNT_EXTERNAL_READ;
14500                }
14501                return Zygote.MOUNT_EXTERNAL_WRITE;
14502            }
14503
14504            @Override
14505            public boolean hasExternalStorage(int uid, String packageName) {
14506                return true;
14507            }
14508        });
14509    }
14510
14511    @Override
14512    public boolean isSafeMode() {
14513        return mSafeMode;
14514    }
14515
14516    @Override
14517    public boolean hasSystemUidErrors() {
14518        return mHasSystemUidErrors;
14519    }
14520
14521    static String arrayToString(int[] array) {
14522        StringBuffer buf = new StringBuffer(128);
14523        buf.append('[');
14524        if (array != null) {
14525            for (int i=0; i<array.length; i++) {
14526                if (i > 0) buf.append(", ");
14527                buf.append(array[i]);
14528            }
14529        }
14530        buf.append(']');
14531        return buf.toString();
14532    }
14533
14534    static class DumpState {
14535        public static final int DUMP_LIBS = 1 << 0;
14536        public static final int DUMP_FEATURES = 1 << 1;
14537        public static final int DUMP_RESOLVERS = 1 << 2;
14538        public static final int DUMP_PERMISSIONS = 1 << 3;
14539        public static final int DUMP_PACKAGES = 1 << 4;
14540        public static final int DUMP_SHARED_USERS = 1 << 5;
14541        public static final int DUMP_MESSAGES = 1 << 6;
14542        public static final int DUMP_PROVIDERS = 1 << 7;
14543        public static final int DUMP_VERIFIERS = 1 << 8;
14544        public static final int DUMP_PREFERRED = 1 << 9;
14545        public static final int DUMP_PREFERRED_XML = 1 << 10;
14546        public static final int DUMP_KEYSETS = 1 << 11;
14547        public static final int DUMP_VERSION = 1 << 12;
14548        public static final int DUMP_INSTALLS = 1 << 13;
14549        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14550        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14551
14552        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14553
14554        private int mTypes;
14555
14556        private int mOptions;
14557
14558        private boolean mTitlePrinted;
14559
14560        private SharedUserSetting mSharedUser;
14561
14562        public boolean isDumping(int type) {
14563            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14564                return true;
14565            }
14566
14567            return (mTypes & type) != 0;
14568        }
14569
14570        public void setDump(int type) {
14571            mTypes |= type;
14572        }
14573
14574        public boolean isOptionEnabled(int option) {
14575            return (mOptions & option) != 0;
14576        }
14577
14578        public void setOptionEnabled(int option) {
14579            mOptions |= option;
14580        }
14581
14582        public boolean onTitlePrinted() {
14583            final boolean printed = mTitlePrinted;
14584            mTitlePrinted = true;
14585            return printed;
14586        }
14587
14588        public boolean getTitlePrinted() {
14589            return mTitlePrinted;
14590        }
14591
14592        public void setTitlePrinted(boolean enabled) {
14593            mTitlePrinted = enabled;
14594        }
14595
14596        public SharedUserSetting getSharedUser() {
14597            return mSharedUser;
14598        }
14599
14600        public void setSharedUser(SharedUserSetting user) {
14601            mSharedUser = user;
14602        }
14603    }
14604
14605    @Override
14606    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14607        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14608                != PackageManager.PERMISSION_GRANTED) {
14609            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14610                    + Binder.getCallingPid()
14611                    + ", uid=" + Binder.getCallingUid()
14612                    + " without permission "
14613                    + android.Manifest.permission.DUMP);
14614            return;
14615        }
14616
14617        DumpState dumpState = new DumpState();
14618        boolean fullPreferred = false;
14619        boolean checkin = false;
14620
14621        String packageName = null;
14622        ArraySet<String> permissionNames = null;
14623
14624        int opti = 0;
14625        while (opti < args.length) {
14626            String opt = args[opti];
14627            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14628                break;
14629            }
14630            opti++;
14631
14632            if ("-a".equals(opt)) {
14633                // Right now we only know how to print all.
14634            } else if ("-h".equals(opt)) {
14635                pw.println("Package manager dump options:");
14636                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14637                pw.println("    --checkin: dump for a checkin");
14638                pw.println("    -f: print details of intent filters");
14639                pw.println("    -h: print this help");
14640                pw.println("  cmd may be one of:");
14641                pw.println("    l[ibraries]: list known shared libraries");
14642                pw.println("    f[ibraries]: list device features");
14643                pw.println("    k[eysets]: print known keysets");
14644                pw.println("    r[esolvers]: dump intent resolvers");
14645                pw.println("    perm[issions]: dump permissions");
14646                pw.println("    permission [name ...]: dump declaration and use of given permission");
14647                pw.println("    pref[erred]: print preferred package settings");
14648                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14649                pw.println("    prov[iders]: dump content providers");
14650                pw.println("    p[ackages]: dump installed packages");
14651                pw.println("    s[hared-users]: dump shared user IDs");
14652                pw.println("    m[essages]: print collected runtime messages");
14653                pw.println("    v[erifiers]: print package verifier info");
14654                pw.println("    version: print database version info");
14655                pw.println("    write: write current settings now");
14656                pw.println("    <package.name>: info about given package");
14657                pw.println("    installs: details about install sessions");
14658                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14659                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14660                return;
14661            } else if ("--checkin".equals(opt)) {
14662                checkin = true;
14663            } else if ("-f".equals(opt)) {
14664                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14665            } else {
14666                pw.println("Unknown argument: " + opt + "; use -h for help");
14667            }
14668        }
14669
14670        // Is the caller requesting to dump a particular piece of data?
14671        if (opti < args.length) {
14672            String cmd = args[opti];
14673            opti++;
14674            // Is this a package name?
14675            if ("android".equals(cmd) || cmd.contains(".")) {
14676                packageName = cmd;
14677                // When dumping a single package, we always dump all of its
14678                // filter information since the amount of data will be reasonable.
14679                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14680            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14681                dumpState.setDump(DumpState.DUMP_LIBS);
14682            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14683                dumpState.setDump(DumpState.DUMP_FEATURES);
14684            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14685                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14686            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14687                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14688            } else if ("permission".equals(cmd)) {
14689                if (opti >= args.length) {
14690                    pw.println("Error: permission requires permission name");
14691                    return;
14692                }
14693                permissionNames = new ArraySet<>();
14694                while (opti < args.length) {
14695                    permissionNames.add(args[opti]);
14696                    opti++;
14697                }
14698                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14699                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14700            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14701                dumpState.setDump(DumpState.DUMP_PREFERRED);
14702            } else if ("preferred-xml".equals(cmd)) {
14703                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14704                if (opti < args.length && "--full".equals(args[opti])) {
14705                    fullPreferred = true;
14706                    opti++;
14707                }
14708            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14709                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14710            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14711                dumpState.setDump(DumpState.DUMP_PACKAGES);
14712            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14713                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14714            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14715                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14716            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14717                dumpState.setDump(DumpState.DUMP_MESSAGES);
14718            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14719                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14720            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14721                    || "intent-filter-verifiers".equals(cmd)) {
14722                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14723            } else if ("version".equals(cmd)) {
14724                dumpState.setDump(DumpState.DUMP_VERSION);
14725            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14726                dumpState.setDump(DumpState.DUMP_KEYSETS);
14727            } else if ("installs".equals(cmd)) {
14728                dumpState.setDump(DumpState.DUMP_INSTALLS);
14729            } else if ("write".equals(cmd)) {
14730                synchronized (mPackages) {
14731                    mSettings.writeLPr();
14732                    pw.println("Settings written.");
14733                    return;
14734                }
14735            }
14736        }
14737
14738        if (checkin) {
14739            pw.println("vers,1");
14740        }
14741
14742        // reader
14743        synchronized (mPackages) {
14744            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14745                if (!checkin) {
14746                    if (dumpState.onTitlePrinted())
14747                        pw.println();
14748                    pw.println("Database versions:");
14749                    pw.print("  SDK Version:");
14750                    pw.print(" internal=");
14751                    pw.print(mSettings.mInternalSdkPlatform);
14752                    pw.print(" external=");
14753                    pw.println(mSettings.mExternalSdkPlatform);
14754                    pw.print("  DB Version:");
14755                    pw.print(" internal=");
14756                    pw.print(mSettings.mInternalDatabaseVersion);
14757                    pw.print(" external=");
14758                    pw.println(mSettings.mExternalDatabaseVersion);
14759                }
14760            }
14761
14762            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14763                if (!checkin) {
14764                    if (dumpState.onTitlePrinted())
14765                        pw.println();
14766                    pw.println("Verifiers:");
14767                    pw.print("  Required: ");
14768                    pw.print(mRequiredVerifierPackage);
14769                    pw.print(" (uid=");
14770                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14771                    pw.println(")");
14772                } else if (mRequiredVerifierPackage != null) {
14773                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14774                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14775                }
14776            }
14777
14778            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14779                    packageName == null) {
14780                if (mIntentFilterVerifierComponent != null) {
14781                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14782                    if (!checkin) {
14783                        if (dumpState.onTitlePrinted())
14784                            pw.println();
14785                        pw.println("Intent Filter Verifier:");
14786                        pw.print("  Using: ");
14787                        pw.print(verifierPackageName);
14788                        pw.print(" (uid=");
14789                        pw.print(getPackageUid(verifierPackageName, 0));
14790                        pw.println(")");
14791                    } else if (verifierPackageName != null) {
14792                        pw.print("ifv,"); pw.print(verifierPackageName);
14793                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14794                    }
14795                } else {
14796                    pw.println();
14797                    pw.println("No Intent Filter Verifier available!");
14798                }
14799            }
14800
14801            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14802                boolean printedHeader = false;
14803                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14804                while (it.hasNext()) {
14805                    String name = it.next();
14806                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14807                    if (!checkin) {
14808                        if (!printedHeader) {
14809                            if (dumpState.onTitlePrinted())
14810                                pw.println();
14811                            pw.println("Libraries:");
14812                            printedHeader = true;
14813                        }
14814                        pw.print("  ");
14815                    } else {
14816                        pw.print("lib,");
14817                    }
14818                    pw.print(name);
14819                    if (!checkin) {
14820                        pw.print(" -> ");
14821                    }
14822                    if (ent.path != null) {
14823                        if (!checkin) {
14824                            pw.print("(jar) ");
14825                            pw.print(ent.path);
14826                        } else {
14827                            pw.print(",jar,");
14828                            pw.print(ent.path);
14829                        }
14830                    } else {
14831                        if (!checkin) {
14832                            pw.print("(apk) ");
14833                            pw.print(ent.apk);
14834                        } else {
14835                            pw.print(",apk,");
14836                            pw.print(ent.apk);
14837                        }
14838                    }
14839                    pw.println();
14840                }
14841            }
14842
14843            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14844                if (dumpState.onTitlePrinted())
14845                    pw.println();
14846                if (!checkin) {
14847                    pw.println("Features:");
14848                }
14849                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14850                while (it.hasNext()) {
14851                    String name = it.next();
14852                    if (!checkin) {
14853                        pw.print("  ");
14854                    } else {
14855                        pw.print("feat,");
14856                    }
14857                    pw.println(name);
14858                }
14859            }
14860
14861            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14862                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14863                        : "Activity Resolver Table:", "  ", packageName,
14864                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14865                    dumpState.setTitlePrinted(true);
14866                }
14867                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14868                        : "Receiver Resolver Table:", "  ", packageName,
14869                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14870                    dumpState.setTitlePrinted(true);
14871                }
14872                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14873                        : "Service Resolver Table:", "  ", packageName,
14874                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14875                    dumpState.setTitlePrinted(true);
14876                }
14877                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14878                        : "Provider Resolver Table:", "  ", packageName,
14879                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14880                    dumpState.setTitlePrinted(true);
14881                }
14882            }
14883
14884            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14885                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14886                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14887                    int user = mSettings.mPreferredActivities.keyAt(i);
14888                    if (pir.dump(pw,
14889                            dumpState.getTitlePrinted()
14890                                ? "\nPreferred Activities User " + user + ":"
14891                                : "Preferred Activities User " + user + ":", "  ",
14892                            packageName, true, false)) {
14893                        dumpState.setTitlePrinted(true);
14894                    }
14895                }
14896            }
14897
14898            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14899                pw.flush();
14900                FileOutputStream fout = new FileOutputStream(fd);
14901                BufferedOutputStream str = new BufferedOutputStream(fout);
14902                XmlSerializer serializer = new FastXmlSerializer();
14903                try {
14904                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14905                    serializer.startDocument(null, true);
14906                    serializer.setFeature(
14907                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14908                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14909                    serializer.endDocument();
14910                    serializer.flush();
14911                } catch (IllegalArgumentException e) {
14912                    pw.println("Failed writing: " + e);
14913                } catch (IllegalStateException e) {
14914                    pw.println("Failed writing: " + e);
14915                } catch (IOException e) {
14916                    pw.println("Failed writing: " + e);
14917                }
14918            }
14919
14920            if (!checkin
14921                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14922                    && packageName == null) {
14923                pw.println();
14924                int count = mSettings.mPackages.size();
14925                if (count == 0) {
14926                    pw.println("No applications!");
14927                    pw.println();
14928                } else {
14929                    final String prefix = "  ";
14930                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14931                    if (allPackageSettings.size() == 0) {
14932                        pw.println("No domain preferred apps!");
14933                        pw.println();
14934                    } else {
14935                        pw.println("App verification status:");
14936                        pw.println();
14937                        count = 0;
14938                        for (PackageSetting ps : allPackageSettings) {
14939                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14940                            if (ivi == null || ivi.getPackageName() == null) continue;
14941                            pw.println(prefix + "Package: " + ivi.getPackageName());
14942                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14943                            pw.println(prefix + "Status:  " + ivi.getStatusString());
14944                            pw.println();
14945                            count++;
14946                        }
14947                        if (count == 0) {
14948                            pw.println(prefix + "No app verification established.");
14949                            pw.println();
14950                        }
14951                        for (int userId : sUserManager.getUserIds()) {
14952                            pw.println("App linkages for user " + userId + ":");
14953                            pw.println();
14954                            count = 0;
14955                            for (PackageSetting ps : allPackageSettings) {
14956                                final long status = ps.getDomainVerificationStatusForUser(userId);
14957                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14958                                    continue;
14959                                }
14960                                pw.println(prefix + "Package: " + ps.name);
14961                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
14962                                String statusStr = IntentFilterVerificationInfo.
14963                                        getStatusStringFromValue(status);
14964                                pw.println(prefix + "Status:  " + statusStr);
14965                                pw.println();
14966                                count++;
14967                            }
14968                            if (count == 0) {
14969                                pw.println(prefix + "No configured app linkages.");
14970                                pw.println();
14971                            }
14972                        }
14973                    }
14974                }
14975            }
14976
14977            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14978                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14979                if (packageName == null && permissionNames == null) {
14980                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14981                        if (iperm == 0) {
14982                            if (dumpState.onTitlePrinted())
14983                                pw.println();
14984                            pw.println("AppOp Permissions:");
14985                        }
14986                        pw.print("  AppOp Permission ");
14987                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14988                        pw.println(":");
14989                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14990                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14991                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14992                        }
14993                    }
14994                }
14995            }
14996
14997            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14998                boolean printedSomething = false;
14999                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15000                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15001                        continue;
15002                    }
15003                    if (!printedSomething) {
15004                        if (dumpState.onTitlePrinted())
15005                            pw.println();
15006                        pw.println("Registered ContentProviders:");
15007                        printedSomething = true;
15008                    }
15009                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15010                    pw.print("    "); pw.println(p.toString());
15011                }
15012                printedSomething = false;
15013                for (Map.Entry<String, PackageParser.Provider> entry :
15014                        mProvidersByAuthority.entrySet()) {
15015                    PackageParser.Provider p = entry.getValue();
15016                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15017                        continue;
15018                    }
15019                    if (!printedSomething) {
15020                        if (dumpState.onTitlePrinted())
15021                            pw.println();
15022                        pw.println("ContentProvider Authorities:");
15023                        printedSomething = true;
15024                    }
15025                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15026                    pw.print("    "); pw.println(p.toString());
15027                    if (p.info != null && p.info.applicationInfo != null) {
15028                        final String appInfo = p.info.applicationInfo.toString();
15029                        pw.print("      applicationInfo="); pw.println(appInfo);
15030                    }
15031                }
15032            }
15033
15034            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15035                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15036            }
15037
15038            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15039                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15040            }
15041
15042            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15043                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15044            }
15045
15046            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15047                // XXX should handle packageName != null by dumping only install data that
15048                // the given package is involved with.
15049                if (dumpState.onTitlePrinted()) pw.println();
15050                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15051            }
15052
15053            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15054                if (dumpState.onTitlePrinted()) pw.println();
15055                mSettings.dumpReadMessagesLPr(pw, dumpState);
15056
15057                pw.println();
15058                pw.println("Package warning messages:");
15059                BufferedReader in = null;
15060                String line = null;
15061                try {
15062                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15063                    while ((line = in.readLine()) != null) {
15064                        if (line.contains("ignored: updated version")) continue;
15065                        pw.println(line);
15066                    }
15067                } catch (IOException ignored) {
15068                } finally {
15069                    IoUtils.closeQuietly(in);
15070                }
15071            }
15072
15073            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15074                BufferedReader in = null;
15075                String line = null;
15076                try {
15077                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15078                    while ((line = in.readLine()) != null) {
15079                        if (line.contains("ignored: updated version")) continue;
15080                        pw.print("msg,");
15081                        pw.println(line);
15082                    }
15083                } catch (IOException ignored) {
15084                } finally {
15085                    IoUtils.closeQuietly(in);
15086                }
15087            }
15088        }
15089    }
15090
15091    private String dumpDomainString(String packageName) {
15092        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15093        List<IntentFilter> filters = getAllIntentFilters(packageName);
15094
15095        ArraySet<String> result = new ArraySet<>();
15096        if (iviList.size() > 0) {
15097            for (IntentFilterVerificationInfo ivi : iviList) {
15098                for (String host : ivi.getDomains()) {
15099                    result.add(host);
15100                }
15101            }
15102        }
15103        if (filters != null && filters.size() > 0) {
15104            for (IntentFilter filter : filters) {
15105                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15106                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15107                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15108                    result.addAll(filter.getHostsList());
15109                }
15110            }
15111        }
15112
15113        StringBuilder sb = new StringBuilder(result.size() * 16);
15114        for (String domain : result) {
15115            if (sb.length() > 0) sb.append(" ");
15116            sb.append(domain);
15117        }
15118        return sb.toString();
15119    }
15120
15121    // ------- apps on sdcard specific code -------
15122    static final boolean DEBUG_SD_INSTALL = false;
15123
15124    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15125
15126    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15127
15128    private boolean mMediaMounted = false;
15129
15130    static String getEncryptKey() {
15131        try {
15132            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15133                    SD_ENCRYPTION_KEYSTORE_NAME);
15134            if (sdEncKey == null) {
15135                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15136                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15137                if (sdEncKey == null) {
15138                    Slog.e(TAG, "Failed to create encryption keys");
15139                    return null;
15140                }
15141            }
15142            return sdEncKey;
15143        } catch (NoSuchAlgorithmException nsae) {
15144            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15145            return null;
15146        } catch (IOException ioe) {
15147            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15148            return null;
15149        }
15150    }
15151
15152    /*
15153     * Update media status on PackageManager.
15154     */
15155    @Override
15156    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15157        int callingUid = Binder.getCallingUid();
15158        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15159            throw new SecurityException("Media status can only be updated by the system");
15160        }
15161        // reader; this apparently protects mMediaMounted, but should probably
15162        // be a different lock in that case.
15163        synchronized (mPackages) {
15164            Log.i(TAG, "Updating external media status from "
15165                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15166                    + (mediaStatus ? "mounted" : "unmounted"));
15167            if (DEBUG_SD_INSTALL)
15168                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15169                        + ", mMediaMounted=" + mMediaMounted);
15170            if (mediaStatus == mMediaMounted) {
15171                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15172                        : 0, -1);
15173                mHandler.sendMessage(msg);
15174                return;
15175            }
15176            mMediaMounted = mediaStatus;
15177        }
15178        // Queue up an async operation since the package installation may take a
15179        // little while.
15180        mHandler.post(new Runnable() {
15181            public void run() {
15182                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15183            }
15184        });
15185    }
15186
15187    /**
15188     * Called by MountService when the initial ASECs to scan are available.
15189     * Should block until all the ASEC containers are finished being scanned.
15190     */
15191    public void scanAvailableAsecs() {
15192        updateExternalMediaStatusInner(true, false, false);
15193        if (mShouldRestoreconData) {
15194            SELinuxMMAC.setRestoreconDone();
15195            mShouldRestoreconData = false;
15196        }
15197    }
15198
15199    /*
15200     * Collect information of applications on external media, map them against
15201     * existing containers and update information based on current mount status.
15202     * Please note that we always have to report status if reportStatus has been
15203     * set to true especially when unloading packages.
15204     */
15205    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15206            boolean externalStorage) {
15207        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15208        int[] uidArr = EmptyArray.INT;
15209
15210        final String[] list = PackageHelper.getSecureContainerList();
15211        if (ArrayUtils.isEmpty(list)) {
15212            Log.i(TAG, "No secure containers found");
15213        } else {
15214            // Process list of secure containers and categorize them
15215            // as active or stale based on their package internal state.
15216
15217            // reader
15218            synchronized (mPackages) {
15219                for (String cid : list) {
15220                    // Leave stages untouched for now; installer service owns them
15221                    if (PackageInstallerService.isStageName(cid)) continue;
15222
15223                    if (DEBUG_SD_INSTALL)
15224                        Log.i(TAG, "Processing container " + cid);
15225                    String pkgName = getAsecPackageName(cid);
15226                    if (pkgName == null) {
15227                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15228                        continue;
15229                    }
15230                    if (DEBUG_SD_INSTALL)
15231                        Log.i(TAG, "Looking for pkg : " + pkgName);
15232
15233                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15234                    if (ps == null) {
15235                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15236                        continue;
15237                    }
15238
15239                    /*
15240                     * Skip packages that are not external if we're unmounting
15241                     * external storage.
15242                     */
15243                    if (externalStorage && !isMounted && !isExternal(ps)) {
15244                        continue;
15245                    }
15246
15247                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15248                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15249                    // The package status is changed only if the code path
15250                    // matches between settings and the container id.
15251                    if (ps.codePathString != null
15252                            && ps.codePathString.startsWith(args.getCodePath())) {
15253                        if (DEBUG_SD_INSTALL) {
15254                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15255                                    + " at code path: " + ps.codePathString);
15256                        }
15257
15258                        // We do have a valid package installed on sdcard
15259                        processCids.put(args, ps.codePathString);
15260                        final int uid = ps.appId;
15261                        if (uid != -1) {
15262                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15263                        }
15264                    } else {
15265                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15266                                + ps.codePathString);
15267                    }
15268                }
15269            }
15270
15271            Arrays.sort(uidArr);
15272        }
15273
15274        // Process packages with valid entries.
15275        if (isMounted) {
15276            if (DEBUG_SD_INSTALL)
15277                Log.i(TAG, "Loading packages");
15278            loadMediaPackages(processCids, uidArr);
15279            startCleaningPackages();
15280            mInstallerService.onSecureContainersAvailable();
15281        } else {
15282            if (DEBUG_SD_INSTALL)
15283                Log.i(TAG, "Unloading packages");
15284            unloadMediaPackages(processCids, uidArr, reportStatus);
15285        }
15286    }
15287
15288    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15289            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15290        final int size = infos.size();
15291        final String[] packageNames = new String[size];
15292        final int[] packageUids = new int[size];
15293        for (int i = 0; i < size; i++) {
15294            final ApplicationInfo info = infos.get(i);
15295            packageNames[i] = info.packageName;
15296            packageUids[i] = info.uid;
15297        }
15298        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15299                finishedReceiver);
15300    }
15301
15302    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15303            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15304        sendResourcesChangedBroadcast(mediaStatus, replacing,
15305                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15306    }
15307
15308    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15309            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15310        int size = pkgList.length;
15311        if (size > 0) {
15312            // Send broadcasts here
15313            Bundle extras = new Bundle();
15314            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15315            if (uidArr != null) {
15316                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15317            }
15318            if (replacing) {
15319                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15320            }
15321            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15322                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15323            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15324        }
15325    }
15326
15327   /*
15328     * Look at potentially valid container ids from processCids If package
15329     * information doesn't match the one on record or package scanning fails,
15330     * the cid is added to list of removeCids. We currently don't delete stale
15331     * containers.
15332     */
15333    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15334        ArrayList<String> pkgList = new ArrayList<String>();
15335        Set<AsecInstallArgs> keys = processCids.keySet();
15336
15337        for (AsecInstallArgs args : keys) {
15338            String codePath = processCids.get(args);
15339            if (DEBUG_SD_INSTALL)
15340                Log.i(TAG, "Loading container : " + args.cid);
15341            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15342            try {
15343                // Make sure there are no container errors first.
15344                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15345                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15346                            + " when installing from sdcard");
15347                    continue;
15348                }
15349                // Check code path here.
15350                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15351                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15352                            + " does not match one in settings " + codePath);
15353                    continue;
15354                }
15355                // Parse package
15356                int parseFlags = mDefParseFlags;
15357                if (args.isExternalAsec()) {
15358                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15359                }
15360                if (args.isFwdLocked()) {
15361                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15362                }
15363
15364                synchronized (mInstallLock) {
15365                    PackageParser.Package pkg = null;
15366                    try {
15367                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15368                    } catch (PackageManagerException e) {
15369                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15370                    }
15371                    // Scan the package
15372                    if (pkg != null) {
15373                        /*
15374                         * TODO why is the lock being held? doPostInstall is
15375                         * called in other places without the lock. This needs
15376                         * to be straightened out.
15377                         */
15378                        // writer
15379                        synchronized (mPackages) {
15380                            retCode = PackageManager.INSTALL_SUCCEEDED;
15381                            pkgList.add(pkg.packageName);
15382                            // Post process args
15383                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15384                                    pkg.applicationInfo.uid);
15385                        }
15386                    } else {
15387                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15388                    }
15389                }
15390
15391            } finally {
15392                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15393                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15394                }
15395            }
15396        }
15397        // writer
15398        synchronized (mPackages) {
15399            // If the platform SDK has changed since the last time we booted,
15400            // we need to re-grant app permission to catch any new ones that
15401            // appear. This is really a hack, and means that apps can in some
15402            // cases get permissions that the user didn't initially explicitly
15403            // allow... it would be nice to have some better way to handle
15404            // this situation.
15405            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15406            if (regrantPermissions)
15407                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15408                        + mSdkVersion + "; regranting permissions for external storage");
15409            mSettings.mExternalSdkPlatform = mSdkVersion;
15410
15411            // Make sure group IDs have been assigned, and any permission
15412            // changes in other apps are accounted for
15413            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15414                    | (regrantPermissions
15415                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15416                            : 0));
15417
15418            mSettings.updateExternalDatabaseVersion();
15419
15420            // can downgrade to reader
15421            // Persist settings
15422            mSettings.writeLPr();
15423        }
15424        // Send a broadcast to let everyone know we are done processing
15425        if (pkgList.size() > 0) {
15426            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15427        }
15428    }
15429
15430   /*
15431     * Utility method to unload a list of specified containers
15432     */
15433    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15434        // Just unmount all valid containers.
15435        for (AsecInstallArgs arg : cidArgs) {
15436            synchronized (mInstallLock) {
15437                arg.doPostDeleteLI(false);
15438           }
15439       }
15440   }
15441
15442    /*
15443     * Unload packages mounted on external media. This involves deleting package
15444     * data from internal structures, sending broadcasts about diabled packages,
15445     * gc'ing to free up references, unmounting all secure containers
15446     * corresponding to packages on external media, and posting a
15447     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15448     * that we always have to post this message if status has been requested no
15449     * matter what.
15450     */
15451    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15452            final boolean reportStatus) {
15453        if (DEBUG_SD_INSTALL)
15454            Log.i(TAG, "unloading media packages");
15455        ArrayList<String> pkgList = new ArrayList<String>();
15456        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15457        final Set<AsecInstallArgs> keys = processCids.keySet();
15458        for (AsecInstallArgs args : keys) {
15459            String pkgName = args.getPackageName();
15460            if (DEBUG_SD_INSTALL)
15461                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15462            // Delete package internally
15463            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15464            synchronized (mInstallLock) {
15465                boolean res = deletePackageLI(pkgName, null, false, null, null,
15466                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15467                if (res) {
15468                    pkgList.add(pkgName);
15469                } else {
15470                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15471                    failedList.add(args);
15472                }
15473            }
15474        }
15475
15476        // reader
15477        synchronized (mPackages) {
15478            // We didn't update the settings after removing each package;
15479            // write them now for all packages.
15480            mSettings.writeLPr();
15481        }
15482
15483        // We have to absolutely send UPDATED_MEDIA_STATUS only
15484        // after confirming that all the receivers processed the ordered
15485        // broadcast when packages get disabled, force a gc to clean things up.
15486        // and unload all the containers.
15487        if (pkgList.size() > 0) {
15488            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15489                    new IIntentReceiver.Stub() {
15490                public void performReceive(Intent intent, int resultCode, String data,
15491                        Bundle extras, boolean ordered, boolean sticky,
15492                        int sendingUser) throws RemoteException {
15493                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15494                            reportStatus ? 1 : 0, 1, keys);
15495                    mHandler.sendMessage(msg);
15496                }
15497            });
15498        } else {
15499            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15500                    keys);
15501            mHandler.sendMessage(msg);
15502        }
15503    }
15504
15505    private void loadPrivatePackages(VolumeInfo vol) {
15506        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15507        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15508        synchronized (mInstallLock) {
15509        synchronized (mPackages) {
15510            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15511            for (PackageSetting ps : packages) {
15512                final PackageParser.Package pkg;
15513                try {
15514                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15515                    loaded.add(pkg.applicationInfo);
15516                } catch (PackageManagerException e) {
15517                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15518                }
15519            }
15520
15521            // TODO: regrant any permissions that changed based since original install
15522
15523            mSettings.writeLPr();
15524        }
15525        }
15526
15527        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15528        sendResourcesChangedBroadcast(true, false, loaded, null);
15529    }
15530
15531    private void unloadPrivatePackages(VolumeInfo vol) {
15532        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15533        synchronized (mInstallLock) {
15534        synchronized (mPackages) {
15535            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15536            for (PackageSetting ps : packages) {
15537                if (ps.pkg == null) continue;
15538
15539                final ApplicationInfo info = ps.pkg.applicationInfo;
15540                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15541                if (deletePackageLI(ps.name, null, false, null, null,
15542                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15543                    unloaded.add(info);
15544                } else {
15545                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15546                }
15547            }
15548
15549            mSettings.writeLPr();
15550        }
15551        }
15552
15553        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15554        sendResourcesChangedBroadcast(false, false, unloaded, null);
15555    }
15556
15557    /**
15558     * Examine all users present on given mounted volume, and destroy data
15559     * belonging to users that are no longer valid, or whose user ID has been
15560     * recycled.
15561     */
15562    private void reconcileUsers(String volumeUuid) {
15563        final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
15564        if (ArrayUtils.isEmpty(files)) {
15565            Slog.d(TAG, "No users found on " + volumeUuid);
15566            return;
15567        }
15568
15569        for (File file : files) {
15570            if (!file.isDirectory()) continue;
15571
15572            final int userId;
15573            final UserInfo info;
15574            try {
15575                userId = Integer.parseInt(file.getName());
15576                info = sUserManager.getUserInfo(userId);
15577            } catch (NumberFormatException e) {
15578                Slog.w(TAG, "Invalid user directory " + file);
15579                continue;
15580            }
15581
15582            boolean destroyUser = false;
15583            if (info == null) {
15584                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15585                        + " because no matching user was found");
15586                destroyUser = true;
15587            } else {
15588                try {
15589                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15590                } catch (IOException e) {
15591                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15592                            + " because we failed to enforce serial number: " + e);
15593                    destroyUser = true;
15594                }
15595            }
15596
15597            if (destroyUser) {
15598                synchronized (mInstallLock) {
15599                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15600                }
15601            }
15602        }
15603
15604        final UserManager um = mContext.getSystemService(UserManager.class);
15605        for (UserInfo user : um.getUsers()) {
15606            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15607            if (userDir.exists()) continue;
15608
15609            try {
15610                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15611                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15612            } catch (IOException e) {
15613                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15614            }
15615        }
15616    }
15617
15618    /**
15619     * Examine all apps present on given mounted volume, and destroy apps that
15620     * aren't expected, either due to uninstallation or reinstallation on
15621     * another volume.
15622     */
15623    private void reconcileApps(String volumeUuid) {
15624        final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
15625        if (ArrayUtils.isEmpty(files)) {
15626            Slog.d(TAG, "No apps found on " + volumeUuid);
15627            return;
15628        }
15629
15630        for (File file : files) {
15631            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15632                    && !PackageInstallerService.isStageName(file.getName());
15633            if (!isPackage) {
15634                // Ignore entries which are not packages
15635                continue;
15636            }
15637
15638            boolean destroyApp = false;
15639            String packageName = null;
15640            try {
15641                final PackageLite pkg = PackageParser.parsePackageLite(file,
15642                        PackageParser.PARSE_MUST_BE_APK);
15643                packageName = pkg.packageName;
15644
15645                synchronized (mPackages) {
15646                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15647                    if (ps == null) {
15648                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15649                                + volumeUuid + " because we found no install record");
15650                        destroyApp = true;
15651                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15652                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15653                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15654                        destroyApp = true;
15655                    }
15656                }
15657
15658            } catch (PackageParserException e) {
15659                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15660                destroyApp = true;
15661            }
15662
15663            if (destroyApp) {
15664                synchronized (mInstallLock) {
15665                    if (packageName != null) {
15666                        removeDataDirsLI(volumeUuid, packageName);
15667                    }
15668                    if (file.isDirectory()) {
15669                        mInstaller.rmPackageDir(file.getAbsolutePath());
15670                    } else {
15671                        file.delete();
15672                    }
15673                }
15674            }
15675        }
15676    }
15677
15678    private void unfreezePackage(String packageName) {
15679        synchronized (mPackages) {
15680            final PackageSetting ps = mSettings.mPackages.get(packageName);
15681            if (ps != null) {
15682                ps.frozen = false;
15683            }
15684        }
15685    }
15686
15687    @Override
15688    public int movePackage(final String packageName, final String volumeUuid) {
15689        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15690
15691        final int moveId = mNextMoveId.getAndIncrement();
15692        try {
15693            movePackageInternal(packageName, volumeUuid, moveId);
15694        } catch (PackageManagerException e) {
15695            Slog.w(TAG, "Failed to move " + packageName, e);
15696            mMoveCallbacks.notifyStatusChanged(moveId,
15697                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15698        }
15699        return moveId;
15700    }
15701
15702    private void movePackageInternal(final String packageName, final String volumeUuid,
15703            final int moveId) throws PackageManagerException {
15704        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15705        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15706        final PackageManager pm = mContext.getPackageManager();
15707
15708        final boolean currentAsec;
15709        final String currentVolumeUuid;
15710        final File codeFile;
15711        final String installerPackageName;
15712        final String packageAbiOverride;
15713        final int appId;
15714        final String seinfo;
15715        final String label;
15716
15717        // reader
15718        synchronized (mPackages) {
15719            final PackageParser.Package pkg = mPackages.get(packageName);
15720            final PackageSetting ps = mSettings.mPackages.get(packageName);
15721            if (pkg == null || ps == null) {
15722                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15723            }
15724
15725            if (pkg.applicationInfo.isSystemApp()) {
15726                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15727                        "Cannot move system application");
15728            }
15729
15730            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15731                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15732                        "Package already moved to " + volumeUuid);
15733            }
15734
15735            final File probe = new File(pkg.codePath);
15736            final File probeOat = new File(probe, "oat");
15737            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15738                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15739                        "Move only supported for modern cluster style installs");
15740            }
15741
15742            if (ps.frozen) {
15743                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15744                        "Failed to move already frozen package");
15745            }
15746            ps.frozen = true;
15747
15748            currentAsec = pkg.applicationInfo.isForwardLocked()
15749                    || pkg.applicationInfo.isExternalAsec();
15750            currentVolumeUuid = ps.volumeUuid;
15751            codeFile = new File(pkg.codePath);
15752            installerPackageName = ps.installerPackageName;
15753            packageAbiOverride = ps.cpuAbiOverrideString;
15754            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15755            seinfo = pkg.applicationInfo.seinfo;
15756            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15757        }
15758
15759        // Now that we're guarded by frozen state, kill app during move
15760        killApplication(packageName, appId, "move pkg");
15761
15762        final Bundle extras = new Bundle();
15763        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15764        extras.putString(Intent.EXTRA_TITLE, label);
15765        mMoveCallbacks.notifyCreated(moveId, extras);
15766
15767        int installFlags;
15768        final boolean moveCompleteApp;
15769        final File measurePath;
15770
15771        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15772            installFlags = INSTALL_INTERNAL;
15773            moveCompleteApp = !currentAsec;
15774            measurePath = Environment.getDataAppDirectory(volumeUuid);
15775        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15776            installFlags = INSTALL_EXTERNAL;
15777            moveCompleteApp = false;
15778            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15779        } else {
15780            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15781            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15782                    || !volume.isMountedWritable()) {
15783                unfreezePackage(packageName);
15784                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15785                        "Move location not mounted private volume");
15786            }
15787
15788            Preconditions.checkState(!currentAsec);
15789
15790            installFlags = INSTALL_INTERNAL;
15791            moveCompleteApp = true;
15792            measurePath = Environment.getDataAppDirectory(volumeUuid);
15793        }
15794
15795        final PackageStats stats = new PackageStats(null, -1);
15796        synchronized (mInstaller) {
15797            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15798                unfreezePackage(packageName);
15799                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15800                        "Failed to measure package size");
15801            }
15802        }
15803
15804        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15805                + stats.dataSize);
15806
15807        final long startFreeBytes = measurePath.getFreeSpace();
15808        final long sizeBytes;
15809        if (moveCompleteApp) {
15810            sizeBytes = stats.codeSize + stats.dataSize;
15811        } else {
15812            sizeBytes = stats.codeSize;
15813        }
15814
15815        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15816            unfreezePackage(packageName);
15817            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15818                    "Not enough free space to move");
15819        }
15820
15821        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15822
15823        final CountDownLatch installedLatch = new CountDownLatch(1);
15824        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15825            @Override
15826            public void onUserActionRequired(Intent intent) throws RemoteException {
15827                throw new IllegalStateException();
15828            }
15829
15830            @Override
15831            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15832                    Bundle extras) throws RemoteException {
15833                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15834                        + PackageManager.installStatusToString(returnCode, msg));
15835
15836                installedLatch.countDown();
15837
15838                // Regardless of success or failure of the move operation,
15839                // always unfreeze the package
15840                unfreezePackage(packageName);
15841
15842                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15843                switch (status) {
15844                    case PackageInstaller.STATUS_SUCCESS:
15845                        mMoveCallbacks.notifyStatusChanged(moveId,
15846                                PackageManager.MOVE_SUCCEEDED);
15847                        break;
15848                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15849                        mMoveCallbacks.notifyStatusChanged(moveId,
15850                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15851                        break;
15852                    default:
15853                        mMoveCallbacks.notifyStatusChanged(moveId,
15854                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15855                        break;
15856                }
15857            }
15858        };
15859
15860        final MoveInfo move;
15861        if (moveCompleteApp) {
15862            // Kick off a thread to report progress estimates
15863            new Thread() {
15864                @Override
15865                public void run() {
15866                    while (true) {
15867                        try {
15868                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15869                                break;
15870                            }
15871                        } catch (InterruptedException ignored) {
15872                        }
15873
15874                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15875                        final int progress = 10 + (int) MathUtils.constrain(
15876                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15877                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15878                    }
15879                }
15880            }.start();
15881
15882            final String dataAppName = codeFile.getName();
15883            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15884                    dataAppName, appId, seinfo);
15885        } else {
15886            move = null;
15887        }
15888
15889        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15890
15891        final Message msg = mHandler.obtainMessage(INIT_COPY);
15892        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15893        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15894                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
15895        mHandler.sendMessage(msg);
15896    }
15897
15898    @Override
15899    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15900        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15901
15902        final int realMoveId = mNextMoveId.getAndIncrement();
15903        final Bundle extras = new Bundle();
15904        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15905        mMoveCallbacks.notifyCreated(realMoveId, extras);
15906
15907        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15908            @Override
15909            public void onCreated(int moveId, Bundle extras) {
15910                // Ignored
15911            }
15912
15913            @Override
15914            public void onStatusChanged(int moveId, int status, long estMillis) {
15915                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15916            }
15917        };
15918
15919        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15920        storage.setPrimaryStorageUuid(volumeUuid, callback);
15921        return realMoveId;
15922    }
15923
15924    @Override
15925    public int getMoveStatus(int moveId) {
15926        mContext.enforceCallingOrSelfPermission(
15927                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15928        return mMoveCallbacks.mLastStatus.get(moveId);
15929    }
15930
15931    @Override
15932    public void registerMoveCallback(IPackageMoveObserver callback) {
15933        mContext.enforceCallingOrSelfPermission(
15934                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15935        mMoveCallbacks.register(callback);
15936    }
15937
15938    @Override
15939    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15940        mContext.enforceCallingOrSelfPermission(
15941                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15942        mMoveCallbacks.unregister(callback);
15943    }
15944
15945    @Override
15946    public boolean setInstallLocation(int loc) {
15947        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15948                null);
15949        if (getInstallLocation() == loc) {
15950            return true;
15951        }
15952        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15953                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15954            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15955                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15956            return true;
15957        }
15958        return false;
15959   }
15960
15961    @Override
15962    public int getInstallLocation() {
15963        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15964                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15965                PackageHelper.APP_INSTALL_AUTO);
15966    }
15967
15968    /** Called by UserManagerService */
15969    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15970        mDirtyUsers.remove(userHandle);
15971        mSettings.removeUserLPw(userHandle);
15972        mPendingBroadcasts.remove(userHandle);
15973        if (mInstaller != null) {
15974            // Technically, we shouldn't be doing this with the package lock
15975            // held.  However, this is very rare, and there is already so much
15976            // other disk I/O going on, that we'll let it slide for now.
15977            final StorageManager storage = mContext.getSystemService(StorageManager.class);
15978            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
15979                final String volumeUuid = vol.getFsUuid();
15980                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15981                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15982            }
15983        }
15984        mUserNeedsBadging.delete(userHandle);
15985        removeUnusedPackagesLILPw(userManager, userHandle);
15986    }
15987
15988    /**
15989     * We're removing userHandle and would like to remove any downloaded packages
15990     * that are no longer in use by any other user.
15991     * @param userHandle the user being removed
15992     */
15993    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15994        final boolean DEBUG_CLEAN_APKS = false;
15995        int [] users = userManager.getUserIdsLPr();
15996        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15997        while (psit.hasNext()) {
15998            PackageSetting ps = psit.next();
15999            if (ps.pkg == null) {
16000                continue;
16001            }
16002            final String packageName = ps.pkg.packageName;
16003            // Skip over if system app
16004            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16005                continue;
16006            }
16007            if (DEBUG_CLEAN_APKS) {
16008                Slog.i(TAG, "Checking package " + packageName);
16009            }
16010            boolean keep = false;
16011            for (int i = 0; i < users.length; i++) {
16012                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16013                    keep = true;
16014                    if (DEBUG_CLEAN_APKS) {
16015                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16016                                + users[i]);
16017                    }
16018                    break;
16019                }
16020            }
16021            if (!keep) {
16022                if (DEBUG_CLEAN_APKS) {
16023                    Slog.i(TAG, "  Removing package " + packageName);
16024                }
16025                mHandler.post(new Runnable() {
16026                    public void run() {
16027                        deletePackageX(packageName, userHandle, 0);
16028                    } //end run
16029                });
16030            }
16031        }
16032    }
16033
16034    /** Called by UserManagerService */
16035    void createNewUserLILPw(int userHandle) {
16036        if (mInstaller != null) {
16037            mInstaller.createUserConfig(userHandle);
16038            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16039            applyFactoryDefaultBrowserLPw(userHandle);
16040            primeDomainVerificationsLPw(userHandle);
16041        }
16042    }
16043
16044    void newUserCreated(final int userHandle) {
16045        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16046    }
16047
16048    @Override
16049    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16050        mContext.enforceCallingOrSelfPermission(
16051                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16052                "Only package verification agents can read the verifier device identity");
16053
16054        synchronized (mPackages) {
16055            return mSettings.getVerifierDeviceIdentityLPw();
16056        }
16057    }
16058
16059    @Override
16060    public void setPermissionEnforced(String permission, boolean enforced) {
16061        // TODO: Now that we no longer change GID for storage, this should to away.
16062        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16063                "setPermissionEnforced");
16064        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16065            synchronized (mPackages) {
16066                if (mSettings.mReadExternalStorageEnforced == null
16067                        || mSettings.mReadExternalStorageEnforced != enforced) {
16068                    mSettings.mReadExternalStorageEnforced = enforced;
16069                    mSettings.writeLPr();
16070                }
16071            }
16072            // kill any non-foreground processes so we restart them and
16073            // grant/revoke the GID.
16074            final IActivityManager am = ActivityManagerNative.getDefault();
16075            if (am != null) {
16076                final long token = Binder.clearCallingIdentity();
16077                try {
16078                    am.killProcessesBelowForeground("setPermissionEnforcement");
16079                } catch (RemoteException e) {
16080                } finally {
16081                    Binder.restoreCallingIdentity(token);
16082                }
16083            }
16084        } else {
16085            throw new IllegalArgumentException("No selective enforcement for " + permission);
16086        }
16087    }
16088
16089    @Override
16090    @Deprecated
16091    public boolean isPermissionEnforced(String permission) {
16092        return true;
16093    }
16094
16095    @Override
16096    public boolean isStorageLow() {
16097        final long token = Binder.clearCallingIdentity();
16098        try {
16099            final DeviceStorageMonitorInternal
16100                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16101            if (dsm != null) {
16102                return dsm.isMemoryLow();
16103            } else {
16104                return false;
16105            }
16106        } finally {
16107            Binder.restoreCallingIdentity(token);
16108        }
16109    }
16110
16111    @Override
16112    public IPackageInstaller getPackageInstaller() {
16113        return mInstallerService;
16114    }
16115
16116    private boolean userNeedsBadging(int userId) {
16117        int index = mUserNeedsBadging.indexOfKey(userId);
16118        if (index < 0) {
16119            final UserInfo userInfo;
16120            final long token = Binder.clearCallingIdentity();
16121            try {
16122                userInfo = sUserManager.getUserInfo(userId);
16123            } finally {
16124                Binder.restoreCallingIdentity(token);
16125            }
16126            final boolean b;
16127            if (userInfo != null && userInfo.isManagedProfile()) {
16128                b = true;
16129            } else {
16130                b = false;
16131            }
16132            mUserNeedsBadging.put(userId, b);
16133            return b;
16134        }
16135        return mUserNeedsBadging.valueAt(index);
16136    }
16137
16138    @Override
16139    public KeySet getKeySetByAlias(String packageName, String alias) {
16140        if (packageName == null || alias == null) {
16141            return null;
16142        }
16143        synchronized(mPackages) {
16144            final PackageParser.Package pkg = mPackages.get(packageName);
16145            if (pkg == null) {
16146                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16147                throw new IllegalArgumentException("Unknown package: " + packageName);
16148            }
16149            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16150            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16151        }
16152    }
16153
16154    @Override
16155    public KeySet getSigningKeySet(String packageName) {
16156        if (packageName == null) {
16157            return null;
16158        }
16159        synchronized(mPackages) {
16160            final PackageParser.Package pkg = mPackages.get(packageName);
16161            if (pkg == null) {
16162                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16163                throw new IllegalArgumentException("Unknown package: " + packageName);
16164            }
16165            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16166                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16167                throw new SecurityException("May not access signing KeySet of other apps.");
16168            }
16169            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16170            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16171        }
16172    }
16173
16174    @Override
16175    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16176        if (packageName == null || ks == null) {
16177            return false;
16178        }
16179        synchronized(mPackages) {
16180            final PackageParser.Package pkg = mPackages.get(packageName);
16181            if (pkg == null) {
16182                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16183                throw new IllegalArgumentException("Unknown package: " + packageName);
16184            }
16185            IBinder ksh = ks.getToken();
16186            if (ksh instanceof KeySetHandle) {
16187                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16188                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16189            }
16190            return false;
16191        }
16192    }
16193
16194    @Override
16195    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16196        if (packageName == null || ks == null) {
16197            return false;
16198        }
16199        synchronized(mPackages) {
16200            final PackageParser.Package pkg = mPackages.get(packageName);
16201            if (pkg == null) {
16202                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16203                throw new IllegalArgumentException("Unknown package: " + packageName);
16204            }
16205            IBinder ksh = ks.getToken();
16206            if (ksh instanceof KeySetHandle) {
16207                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16208                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16209            }
16210            return false;
16211        }
16212    }
16213
16214    public void getUsageStatsIfNoPackageUsageInfo() {
16215        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16216            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16217            if (usm == null) {
16218                throw new IllegalStateException("UsageStatsManager must be initialized");
16219            }
16220            long now = System.currentTimeMillis();
16221            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16222            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16223                String packageName = entry.getKey();
16224                PackageParser.Package pkg = mPackages.get(packageName);
16225                if (pkg == null) {
16226                    continue;
16227                }
16228                UsageStats usage = entry.getValue();
16229                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16230                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16231            }
16232        }
16233    }
16234
16235    /**
16236     * Check and throw if the given before/after packages would be considered a
16237     * downgrade.
16238     */
16239    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16240            throws PackageManagerException {
16241        if (after.versionCode < before.mVersionCode) {
16242            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16243                    "Update version code " + after.versionCode + " is older than current "
16244                    + before.mVersionCode);
16245        } else if (after.versionCode == before.mVersionCode) {
16246            if (after.baseRevisionCode < before.baseRevisionCode) {
16247                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16248                        "Update base revision code " + after.baseRevisionCode
16249                        + " is older than current " + before.baseRevisionCode);
16250            }
16251
16252            if (!ArrayUtils.isEmpty(after.splitNames)) {
16253                for (int i = 0; i < after.splitNames.length; i++) {
16254                    final String splitName = after.splitNames[i];
16255                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16256                    if (j != -1) {
16257                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16258                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16259                                    "Update split " + splitName + " revision code "
16260                                    + after.splitRevisionCodes[i] + " is older than current "
16261                                    + before.splitRevisionCodes[j]);
16262                        }
16263                    }
16264                }
16265            }
16266        }
16267    }
16268
16269    private static class MoveCallbacks extends Handler {
16270        private static final int MSG_CREATED = 1;
16271        private static final int MSG_STATUS_CHANGED = 2;
16272
16273        private final RemoteCallbackList<IPackageMoveObserver>
16274                mCallbacks = new RemoteCallbackList<>();
16275
16276        private final SparseIntArray mLastStatus = new SparseIntArray();
16277
16278        public MoveCallbacks(Looper looper) {
16279            super(looper);
16280        }
16281
16282        public void register(IPackageMoveObserver callback) {
16283            mCallbacks.register(callback);
16284        }
16285
16286        public void unregister(IPackageMoveObserver callback) {
16287            mCallbacks.unregister(callback);
16288        }
16289
16290        @Override
16291        public void handleMessage(Message msg) {
16292            final SomeArgs args = (SomeArgs) msg.obj;
16293            final int n = mCallbacks.beginBroadcast();
16294            for (int i = 0; i < n; i++) {
16295                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16296                try {
16297                    invokeCallback(callback, msg.what, args);
16298                } catch (RemoteException ignored) {
16299                }
16300            }
16301            mCallbacks.finishBroadcast();
16302            args.recycle();
16303        }
16304
16305        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16306                throws RemoteException {
16307            switch (what) {
16308                case MSG_CREATED: {
16309                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16310                    break;
16311                }
16312                case MSG_STATUS_CHANGED: {
16313                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16314                    break;
16315                }
16316            }
16317        }
16318
16319        private void notifyCreated(int moveId, Bundle extras) {
16320            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16321
16322            final SomeArgs args = SomeArgs.obtain();
16323            args.argi1 = moveId;
16324            args.arg2 = extras;
16325            obtainMessage(MSG_CREATED, args).sendToTarget();
16326        }
16327
16328        private void notifyStatusChanged(int moveId, int status) {
16329            notifyStatusChanged(moveId, status, -1);
16330        }
16331
16332        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16333            Slog.v(TAG, "Move " + moveId + " status " + status);
16334
16335            final SomeArgs args = SomeArgs.obtain();
16336            args.argi1 = moveId;
16337            args.argi2 = status;
16338            args.arg3 = estMillis;
16339            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16340
16341            synchronized (mLastStatus) {
16342                mLastStatus.put(moveId, status);
16343            }
16344        }
16345    }
16346
16347    private final class OnPermissionChangeListeners extends Handler {
16348        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16349
16350        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16351                new RemoteCallbackList<>();
16352
16353        public OnPermissionChangeListeners(Looper looper) {
16354            super(looper);
16355        }
16356
16357        @Override
16358        public void handleMessage(Message msg) {
16359            switch (msg.what) {
16360                case MSG_ON_PERMISSIONS_CHANGED: {
16361                    final int uid = msg.arg1;
16362                    handleOnPermissionsChanged(uid);
16363                } break;
16364            }
16365        }
16366
16367        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16368            mPermissionListeners.register(listener);
16369
16370        }
16371
16372        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16373            mPermissionListeners.unregister(listener);
16374        }
16375
16376        public void onPermissionsChanged(int uid) {
16377            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16378                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16379            }
16380        }
16381
16382        private void handleOnPermissionsChanged(int uid) {
16383            final int count = mPermissionListeners.beginBroadcast();
16384            try {
16385                for (int i = 0; i < count; i++) {
16386                    IOnPermissionsChangeListener callback = mPermissionListeners
16387                            .getBroadcastItem(i);
16388                    try {
16389                        callback.onPermissionsChanged(uid);
16390                    } catch (RemoteException e) {
16391                        Log.e(TAG, "Permission listener is dead", e);
16392                    }
16393                }
16394            } finally {
16395                mPermissionListeners.finishBroadcast();
16396            }
16397        }
16398    }
16399
16400    private class PackageManagerInternalImpl extends PackageManagerInternal {
16401        @Override
16402        public void setLocationPackagesProvider(PackagesProvider provider) {
16403            synchronized (mPackages) {
16404                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16405            }
16406        }
16407
16408        @Override
16409        public void setImePackagesProvider(PackagesProvider provider) {
16410            synchronized (mPackages) {
16411                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16412            }
16413        }
16414
16415        @Override
16416        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16417            synchronized (mPackages) {
16418                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16419            }
16420        }
16421
16422        @Override
16423        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16424            synchronized (mPackages) {
16425                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16426            }
16427        }
16428
16429        @Override
16430        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16431            synchronized (mPackages) {
16432                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16433            }
16434        }
16435
16436        @Override
16437        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16438            synchronized (mPackages) {
16439                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16440            }
16441        }
16442
16443        @Override
16444        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16445            synchronized (mPackages) {
16446                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16447                        packageName, userId);
16448            }
16449        }
16450
16451        @Override
16452        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16453            synchronized (mPackages) {
16454                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16455                        packageName, userId);
16456            }
16457        }
16458    }
16459
16460    @Override
16461    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16462        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16463        synchronized (mPackages) {
16464            final long identity = Binder.clearCallingIdentity();
16465            try {
16466                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16467                        packageNames, userId);
16468            } finally {
16469                Binder.restoreCallingIdentity(identity);
16470            }
16471        }
16472    }
16473
16474    private static void enforceSystemOrPhoneCaller(String tag) {
16475        int callingUid = Binder.getCallingUid();
16476        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16477            throw new SecurityException(
16478                    "Cannot call " + tag + " from UID " + callingUid);
16479        }
16480    }
16481}
16482