PackageManagerService.java revision 16c268ee90b36defa86ad24f030d7b5a73df2933
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            if (component.equals(mResolveComponentName)) {
2969                // The resolver supports EVERYTHING!
2970                return true;
2971            }
2972            PackageParser.Activity a = mActivities.mActivities.get(component);
2973            if (a == null) {
2974                return false;
2975            }
2976            for (int i=0; i<a.intents.size(); i++) {
2977                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2978                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2979                    return true;
2980                }
2981            }
2982            return false;
2983        }
2984    }
2985
2986    @Override
2987    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2988        if (!sUserManager.exists(userId)) return null;
2989        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2990        synchronized (mPackages) {
2991            PackageParser.Activity a = mReceivers.mActivities.get(component);
2992            if (DEBUG_PACKAGE_INFO) Log.v(
2993                TAG, "getReceiverInfo " + component + ": " + a);
2994            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2995                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2996                if (ps == null) return null;
2997                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2998                        userId);
2999            }
3000        }
3001        return null;
3002    }
3003
3004    @Override
3005    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3006        if (!sUserManager.exists(userId)) return null;
3007        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3008        synchronized (mPackages) {
3009            PackageParser.Service s = mServices.mServices.get(component);
3010            if (DEBUG_PACKAGE_INFO) Log.v(
3011                TAG, "getServiceInfo " + component + ": " + s);
3012            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3013                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3014                if (ps == null) return null;
3015                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3016                        userId);
3017            }
3018        }
3019        return null;
3020    }
3021
3022    @Override
3023    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3024        if (!sUserManager.exists(userId)) return null;
3025        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3026        synchronized (mPackages) {
3027            PackageParser.Provider p = mProviders.mProviders.get(component);
3028            if (DEBUG_PACKAGE_INFO) Log.v(
3029                TAG, "getProviderInfo " + component + ": " + p);
3030            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3031                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3032                if (ps == null) return null;
3033                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3034                        userId);
3035            }
3036        }
3037        return null;
3038    }
3039
3040    @Override
3041    public String[] getSystemSharedLibraryNames() {
3042        Set<String> libSet;
3043        synchronized (mPackages) {
3044            libSet = mSharedLibraries.keySet();
3045            int size = libSet.size();
3046            if (size > 0) {
3047                String[] libs = new String[size];
3048                libSet.toArray(libs);
3049                return libs;
3050            }
3051        }
3052        return null;
3053    }
3054
3055    /**
3056     * @hide
3057     */
3058    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3059        synchronized (mPackages) {
3060            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3061            if (lib != null && lib.apk != null) {
3062                return mPackages.get(lib.apk);
3063            }
3064        }
3065        return null;
3066    }
3067
3068    @Override
3069    public FeatureInfo[] getSystemAvailableFeatures() {
3070        Collection<FeatureInfo> featSet;
3071        synchronized (mPackages) {
3072            featSet = mAvailableFeatures.values();
3073            int size = featSet.size();
3074            if (size > 0) {
3075                FeatureInfo[] features = new FeatureInfo[size+1];
3076                featSet.toArray(features);
3077                FeatureInfo fi = new FeatureInfo();
3078                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3079                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3080                features[size] = fi;
3081                return features;
3082            }
3083        }
3084        return null;
3085    }
3086
3087    @Override
3088    public boolean hasSystemFeature(String name) {
3089        synchronized (mPackages) {
3090            return mAvailableFeatures.containsKey(name);
3091        }
3092    }
3093
3094    private void checkValidCaller(int uid, int userId) {
3095        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3096            return;
3097
3098        throw new SecurityException("Caller uid=" + uid
3099                + " is not privileged to communicate with user=" + userId);
3100    }
3101
3102    @Override
3103    public int checkPermission(String permName, String pkgName, int userId) {
3104        if (!sUserManager.exists(userId)) {
3105            return PackageManager.PERMISSION_DENIED;
3106        }
3107
3108        synchronized (mPackages) {
3109            final PackageParser.Package p = mPackages.get(pkgName);
3110            if (p != null && p.mExtras != null) {
3111                final PackageSetting ps = (PackageSetting) p.mExtras;
3112                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3113                    return PackageManager.PERMISSION_GRANTED;
3114                }
3115            }
3116        }
3117
3118        return PackageManager.PERMISSION_DENIED;
3119    }
3120
3121    @Override
3122    public int checkUidPermission(String permName, int uid) {
3123        final int userId = UserHandle.getUserId(uid);
3124
3125        if (!sUserManager.exists(userId)) {
3126            return PackageManager.PERMISSION_DENIED;
3127        }
3128
3129        synchronized (mPackages) {
3130            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3131            if (obj != null) {
3132                final SettingBase ps = (SettingBase) obj;
3133                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3134                    return PackageManager.PERMISSION_GRANTED;
3135                }
3136            } else {
3137                ArraySet<String> perms = mSystemPermissions.get(uid);
3138                if (perms != null && perms.contains(permName)) {
3139                    return PackageManager.PERMISSION_GRANTED;
3140                }
3141            }
3142        }
3143
3144        return PackageManager.PERMISSION_DENIED;
3145    }
3146
3147    @Override
3148    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3149        if (UserHandle.getCallingUserId() != userId) {
3150            mContext.enforceCallingPermission(
3151                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3152                    "isPermissionRevokedByPolicy for user " + userId);
3153        }
3154
3155        if (checkPermission(permission, packageName, userId)
3156                == PackageManager.PERMISSION_GRANTED) {
3157            return false;
3158        }
3159
3160        final long identity = Binder.clearCallingIdentity();
3161        try {
3162            final int flags = getPermissionFlags(permission, packageName, userId);
3163            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3164        } finally {
3165            Binder.restoreCallingIdentity(identity);
3166        }
3167    }
3168
3169    /**
3170     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3171     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3172     * @param checkShell TODO(yamasani):
3173     * @param message the message to log on security exception
3174     */
3175    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3176            boolean checkShell, String message) {
3177        if (userId < 0) {
3178            throw new IllegalArgumentException("Invalid userId " + userId);
3179        }
3180        if (checkShell) {
3181            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3182        }
3183        if (userId == UserHandle.getUserId(callingUid)) return;
3184        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3185            if (requireFullPermission) {
3186                mContext.enforceCallingOrSelfPermission(
3187                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3188            } else {
3189                try {
3190                    mContext.enforceCallingOrSelfPermission(
3191                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3192                } catch (SecurityException se) {
3193                    mContext.enforceCallingOrSelfPermission(
3194                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3195                }
3196            }
3197        }
3198    }
3199
3200    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3201        if (callingUid == Process.SHELL_UID) {
3202            if (userHandle >= 0
3203                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3204                throw new SecurityException("Shell does not have permission to access user "
3205                        + userHandle);
3206            } else if (userHandle < 0) {
3207                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3208                        + Debug.getCallers(3));
3209            }
3210        }
3211    }
3212
3213    private BasePermission findPermissionTreeLP(String permName) {
3214        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3215            if (permName.startsWith(bp.name) &&
3216                    permName.length() > bp.name.length() &&
3217                    permName.charAt(bp.name.length()) == '.') {
3218                return bp;
3219            }
3220        }
3221        return null;
3222    }
3223
3224    private BasePermission checkPermissionTreeLP(String permName) {
3225        if (permName != null) {
3226            BasePermission bp = findPermissionTreeLP(permName);
3227            if (bp != null) {
3228                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3229                    return bp;
3230                }
3231                throw new SecurityException("Calling uid "
3232                        + Binder.getCallingUid()
3233                        + " is not allowed to add to permission tree "
3234                        + bp.name + " owned by uid " + bp.uid);
3235            }
3236        }
3237        throw new SecurityException("No permission tree found for " + permName);
3238    }
3239
3240    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3241        if (s1 == null) {
3242            return s2 == null;
3243        }
3244        if (s2 == null) {
3245            return false;
3246        }
3247        if (s1.getClass() != s2.getClass()) {
3248            return false;
3249        }
3250        return s1.equals(s2);
3251    }
3252
3253    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3254        if (pi1.icon != pi2.icon) return false;
3255        if (pi1.logo != pi2.logo) return false;
3256        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3257        if (!compareStrings(pi1.name, pi2.name)) return false;
3258        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3259        // We'll take care of setting this one.
3260        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3261        // These are not currently stored in settings.
3262        //if (!compareStrings(pi1.group, pi2.group)) return false;
3263        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3264        //if (pi1.labelRes != pi2.labelRes) return false;
3265        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3266        return true;
3267    }
3268
3269    int permissionInfoFootprint(PermissionInfo info) {
3270        int size = info.name.length();
3271        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3272        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3273        return size;
3274    }
3275
3276    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3277        int size = 0;
3278        for (BasePermission perm : mSettings.mPermissions.values()) {
3279            if (perm.uid == tree.uid) {
3280                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3281            }
3282        }
3283        return size;
3284    }
3285
3286    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3287        // We calculate the max size of permissions defined by this uid and throw
3288        // if that plus the size of 'info' would exceed our stated maximum.
3289        if (tree.uid != Process.SYSTEM_UID) {
3290            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3291            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3292                throw new SecurityException("Permission tree size cap exceeded");
3293            }
3294        }
3295    }
3296
3297    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3298        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3299            throw new SecurityException("Label must be specified in permission");
3300        }
3301        BasePermission tree = checkPermissionTreeLP(info.name);
3302        BasePermission bp = mSettings.mPermissions.get(info.name);
3303        boolean added = bp == null;
3304        boolean changed = true;
3305        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3306        if (added) {
3307            enforcePermissionCapLocked(info, tree);
3308            bp = new BasePermission(info.name, tree.sourcePackage,
3309                    BasePermission.TYPE_DYNAMIC);
3310        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3311            throw new SecurityException(
3312                    "Not allowed to modify non-dynamic permission "
3313                    + info.name);
3314        } else {
3315            if (bp.protectionLevel == fixedLevel
3316                    && bp.perm.owner.equals(tree.perm.owner)
3317                    && bp.uid == tree.uid
3318                    && comparePermissionInfos(bp.perm.info, info)) {
3319                changed = false;
3320            }
3321        }
3322        bp.protectionLevel = fixedLevel;
3323        info = new PermissionInfo(info);
3324        info.protectionLevel = fixedLevel;
3325        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3326        bp.perm.info.packageName = tree.perm.info.packageName;
3327        bp.uid = tree.uid;
3328        if (added) {
3329            mSettings.mPermissions.put(info.name, bp);
3330        }
3331        if (changed) {
3332            if (!async) {
3333                mSettings.writeLPr();
3334            } else {
3335                scheduleWriteSettingsLocked();
3336            }
3337        }
3338        return added;
3339    }
3340
3341    @Override
3342    public boolean addPermission(PermissionInfo info) {
3343        synchronized (mPackages) {
3344            return addPermissionLocked(info, false);
3345        }
3346    }
3347
3348    @Override
3349    public boolean addPermissionAsync(PermissionInfo info) {
3350        synchronized (mPackages) {
3351            return addPermissionLocked(info, true);
3352        }
3353    }
3354
3355    @Override
3356    public void removePermission(String name) {
3357        synchronized (mPackages) {
3358            checkPermissionTreeLP(name);
3359            BasePermission bp = mSettings.mPermissions.get(name);
3360            if (bp != null) {
3361                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3362                    throw new SecurityException(
3363                            "Not allowed to modify non-dynamic permission "
3364                            + name);
3365                }
3366                mSettings.mPermissions.remove(name);
3367                mSettings.writeLPr();
3368            }
3369        }
3370    }
3371
3372    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3373            BasePermission bp) {
3374        int index = pkg.requestedPermissions.indexOf(bp.name);
3375        if (index == -1) {
3376            throw new SecurityException("Package " + pkg.packageName
3377                    + " has not requested permission " + bp.name);
3378        }
3379        if (!bp.isRuntime()) {
3380            throw new SecurityException("Permission " + bp.name
3381                    + " is not a changeable permission type");
3382        }
3383    }
3384
3385    @Override
3386    public void grantRuntimePermission(String packageName, String name, final int userId) {
3387        if (!sUserManager.exists(userId)) {
3388            Log.e(TAG, "No such user:" + userId);
3389            return;
3390        }
3391
3392        mContext.enforceCallingOrSelfPermission(
3393                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3394                "grantRuntimePermission");
3395
3396        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3397                "grantRuntimePermission");
3398
3399        final int uid;
3400        final SettingBase sb;
3401
3402        synchronized (mPackages) {
3403            final PackageParser.Package pkg = mPackages.get(packageName);
3404            if (pkg == null) {
3405                throw new IllegalArgumentException("Unknown package: " + packageName);
3406            }
3407
3408            final BasePermission bp = mSettings.mPermissions.get(name);
3409            if (bp == null) {
3410                throw new IllegalArgumentException("Unknown permission: " + name);
3411            }
3412
3413            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3414
3415            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3416            sb = (SettingBase) pkg.mExtras;
3417            if (sb == null) {
3418                throw new IllegalArgumentException("Unknown package: " + packageName);
3419            }
3420
3421            final PermissionsState permissionsState = sb.getPermissionsState();
3422
3423            final int flags = permissionsState.getPermissionFlags(name, userId);
3424            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3425                throw new SecurityException("Cannot grant system fixed permission: "
3426                        + name + " for package: " + packageName);
3427            }
3428
3429            final int result = permissionsState.grantRuntimePermission(bp, userId);
3430            switch (result) {
3431                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3432                    return;
3433                }
3434
3435                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3436                    mHandler.post(new Runnable() {
3437                        @Override
3438                        public void run() {
3439                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3440                        }
3441                    });
3442                } break;
3443            }
3444
3445            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3446
3447            // Not critical if that is lost - app has to request again.
3448            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3449        }
3450
3451        // Only need to do this if user is initialized. Otherwise it's a new user
3452        // and there are no processes running as the user yet and there's no need
3453        // to make an expensive call to remount processes for the changed permissions.
3454        if (READ_EXTERNAL_STORAGE.equals(name)
3455                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3456            final long token = Binder.clearCallingIdentity();
3457            try {
3458                if (sUserManager.isInitialized(userId)) {
3459                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3460                            MountServiceInternal.class);
3461                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3462                }
3463            } finally {
3464                Binder.restoreCallingIdentity(token);
3465            }
3466        }
3467    }
3468
3469    @Override
3470    public void revokeRuntimePermission(String packageName, String name, int userId) {
3471        if (!sUserManager.exists(userId)) {
3472            Log.e(TAG, "No such user:" + userId);
3473            return;
3474        }
3475
3476        mContext.enforceCallingOrSelfPermission(
3477                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3478                "revokeRuntimePermission");
3479
3480        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3481                "revokeRuntimePermission");
3482
3483        final SettingBase sb;
3484
3485        synchronized (mPackages) {
3486            final PackageParser.Package pkg = mPackages.get(packageName);
3487            if (pkg == null) {
3488                throw new IllegalArgumentException("Unknown package: " + packageName);
3489            }
3490
3491            final BasePermission bp = mSettings.mPermissions.get(name);
3492            if (bp == null) {
3493                throw new IllegalArgumentException("Unknown permission: " + name);
3494            }
3495
3496            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3497
3498            sb = (SettingBase) pkg.mExtras;
3499            if (sb == null) {
3500                throw new IllegalArgumentException("Unknown package: " + packageName);
3501            }
3502
3503            final PermissionsState permissionsState = sb.getPermissionsState();
3504
3505            final int flags = permissionsState.getPermissionFlags(name, userId);
3506            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3507                throw new SecurityException("Cannot revoke system fixed permission: "
3508                        + name + " for package: " + packageName);
3509            }
3510
3511            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3512                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3513                return;
3514            }
3515
3516            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3517
3518            // Critical, after this call app should never have the permission.
3519            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3520        }
3521
3522        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3523    }
3524
3525    @Override
3526    public void resetRuntimePermissions() {
3527        mContext.enforceCallingOrSelfPermission(
3528                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3529                "revokeRuntimePermission");
3530
3531        int callingUid = Binder.getCallingUid();
3532        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3533            mContext.enforceCallingOrSelfPermission(
3534                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3535                    "resetRuntimePermissions");
3536        }
3537
3538        synchronized (mPackages) {
3539            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3540            for (int userId : UserManagerService.getInstance().getUserIds()) {
3541                final int packageCount = mPackages.size();
3542                for (int i = 0; i < packageCount; i++) {
3543                    PackageParser.Package pkg = mPackages.valueAt(i);
3544                    if (!(pkg.mExtras instanceof PackageSetting)) {
3545                        continue;
3546                    }
3547                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3548                    resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
3549                }
3550            }
3551        }
3552    }
3553
3554    @Override
3555    public int getPermissionFlags(String name, String packageName, int userId) {
3556        if (!sUserManager.exists(userId)) {
3557            return 0;
3558        }
3559
3560        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3561
3562        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3563                "getPermissionFlags");
3564
3565        synchronized (mPackages) {
3566            final PackageParser.Package pkg = mPackages.get(packageName);
3567            if (pkg == null) {
3568                throw new IllegalArgumentException("Unknown package: " + packageName);
3569            }
3570
3571            final BasePermission bp = mSettings.mPermissions.get(name);
3572            if (bp == null) {
3573                throw new IllegalArgumentException("Unknown permission: " + name);
3574            }
3575
3576            SettingBase sb = (SettingBase) pkg.mExtras;
3577            if (sb == null) {
3578                throw new IllegalArgumentException("Unknown package: " + packageName);
3579            }
3580
3581            PermissionsState permissionsState = sb.getPermissionsState();
3582            return permissionsState.getPermissionFlags(name, userId);
3583        }
3584    }
3585
3586    @Override
3587    public void updatePermissionFlags(String name, String packageName, int flagMask,
3588            int flagValues, int userId) {
3589        if (!sUserManager.exists(userId)) {
3590            return;
3591        }
3592
3593        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3594
3595        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3596                "updatePermissionFlags");
3597
3598        // Only the system can change system fixed flags.
3599        if (getCallingUid() != Process.SYSTEM_UID) {
3600            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3601            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3602        }
3603
3604        synchronized (mPackages) {
3605            final PackageParser.Package pkg = mPackages.get(packageName);
3606            if (pkg == null) {
3607                throw new IllegalArgumentException("Unknown package: " + packageName);
3608            }
3609
3610            final BasePermission bp = mSettings.mPermissions.get(name);
3611            if (bp == null) {
3612                throw new IllegalArgumentException("Unknown permission: " + name);
3613            }
3614
3615            SettingBase sb = (SettingBase) pkg.mExtras;
3616            if (sb == null) {
3617                throw new IllegalArgumentException("Unknown package: " + packageName);
3618            }
3619
3620            PermissionsState permissionsState = sb.getPermissionsState();
3621
3622            // Only the package manager can change flags for system component permissions.
3623            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3624            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3625                return;
3626            }
3627
3628            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3629
3630            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3631                // Install and runtime permissions are stored in different places,
3632                // so figure out what permission changed and persist the change.
3633                if (permissionsState.getInstallPermissionState(name) != null) {
3634                    scheduleWriteSettingsLocked();
3635                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3636                        || hadState) {
3637                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3638                }
3639            }
3640        }
3641    }
3642
3643    /**
3644     * Update the permission flags for all packages and runtime permissions of a user in order
3645     * to allow device or profile owner to remove POLICY_FIXED.
3646     */
3647    @Override
3648    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3649        if (!sUserManager.exists(userId)) {
3650            return;
3651        }
3652
3653        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3654
3655        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3656                "updatePermissionFlagsForAllApps");
3657
3658        // Only the system can change system fixed flags.
3659        if (getCallingUid() != Process.SYSTEM_UID) {
3660            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3661            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3662        }
3663
3664        synchronized (mPackages) {
3665            boolean changed = false;
3666            final int packageCount = mPackages.size();
3667            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3668                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3669                SettingBase sb = (SettingBase) pkg.mExtras;
3670                if (sb == null) {
3671                    continue;
3672                }
3673                PermissionsState permissionsState = sb.getPermissionsState();
3674                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3675                        userId, flagMask, flagValues);
3676            }
3677            if (changed) {
3678                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3679            }
3680        }
3681    }
3682
3683    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3684        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3685                != PackageManager.PERMISSION_GRANTED
3686            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3687                != PackageManager.PERMISSION_GRANTED) {
3688            throw new SecurityException(message + " requires "
3689                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3690                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3691        }
3692    }
3693
3694    @Override
3695    public boolean shouldShowRequestPermissionRationale(String permissionName,
3696            String packageName, int userId) {
3697        if (UserHandle.getCallingUserId() != userId) {
3698            mContext.enforceCallingPermission(
3699                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3700                    "canShowRequestPermissionRationale for user " + userId);
3701        }
3702
3703        final int uid = getPackageUid(packageName, userId);
3704        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3705            return false;
3706        }
3707
3708        if (checkPermission(permissionName, packageName, userId)
3709                == PackageManager.PERMISSION_GRANTED) {
3710            return false;
3711        }
3712
3713        final int flags;
3714
3715        final long identity = Binder.clearCallingIdentity();
3716        try {
3717            flags = getPermissionFlags(permissionName,
3718                    packageName, userId);
3719        } finally {
3720            Binder.restoreCallingIdentity(identity);
3721        }
3722
3723        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3724                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3725                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3726
3727        if ((flags & fixedFlags) != 0) {
3728            return false;
3729        }
3730
3731        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3732    }
3733
3734    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3735        BasePermission bp = mSettings.mPermissions.get(permission);
3736        if (bp == null) {
3737            throw new SecurityException("Missing " + permission + " permission");
3738        }
3739
3740        SettingBase sb = (SettingBase) pkg.mExtras;
3741        PermissionsState permissionsState = sb.getPermissionsState();
3742
3743        if (permissionsState.grantInstallPermission(bp) !=
3744                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3745            scheduleWriteSettingsLocked();
3746        }
3747    }
3748
3749    @Override
3750    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3751        mContext.enforceCallingOrSelfPermission(
3752                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3753                "addOnPermissionsChangeListener");
3754
3755        synchronized (mPackages) {
3756            mOnPermissionChangeListeners.addListenerLocked(listener);
3757        }
3758    }
3759
3760    @Override
3761    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3762        synchronized (mPackages) {
3763            mOnPermissionChangeListeners.removeListenerLocked(listener);
3764        }
3765    }
3766
3767    @Override
3768    public boolean isProtectedBroadcast(String actionName) {
3769        synchronized (mPackages) {
3770            return mProtectedBroadcasts.contains(actionName);
3771        }
3772    }
3773
3774    @Override
3775    public int checkSignatures(String pkg1, String pkg2) {
3776        synchronized (mPackages) {
3777            final PackageParser.Package p1 = mPackages.get(pkg1);
3778            final PackageParser.Package p2 = mPackages.get(pkg2);
3779            if (p1 == null || p1.mExtras == null
3780                    || p2 == null || p2.mExtras == null) {
3781                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3782            }
3783            return compareSignatures(p1.mSignatures, p2.mSignatures);
3784        }
3785    }
3786
3787    @Override
3788    public int checkUidSignatures(int uid1, int uid2) {
3789        // Map to base uids.
3790        uid1 = UserHandle.getAppId(uid1);
3791        uid2 = UserHandle.getAppId(uid2);
3792        // reader
3793        synchronized (mPackages) {
3794            Signature[] s1;
3795            Signature[] s2;
3796            Object obj = mSettings.getUserIdLPr(uid1);
3797            if (obj != null) {
3798                if (obj instanceof SharedUserSetting) {
3799                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3800                } else if (obj instanceof PackageSetting) {
3801                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3802                } else {
3803                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3804                }
3805            } else {
3806                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3807            }
3808            obj = mSettings.getUserIdLPr(uid2);
3809            if (obj != null) {
3810                if (obj instanceof SharedUserSetting) {
3811                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3812                } else if (obj instanceof PackageSetting) {
3813                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3814                } else {
3815                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3816                }
3817            } else {
3818                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3819            }
3820            return compareSignatures(s1, s2);
3821        }
3822    }
3823
3824    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3825        final long identity = Binder.clearCallingIdentity();
3826        try {
3827            if (sb instanceof SharedUserSetting) {
3828                SharedUserSetting sus = (SharedUserSetting) sb;
3829                final int packageCount = sus.packages.size();
3830                for (int i = 0; i < packageCount; i++) {
3831                    PackageSetting susPs = sus.packages.valueAt(i);
3832                    if (userId == UserHandle.USER_ALL) {
3833                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3834                    } else {
3835                        final int uid = UserHandle.getUid(userId, susPs.appId);
3836                        killUid(uid, reason);
3837                    }
3838                }
3839            } else if (sb instanceof PackageSetting) {
3840                PackageSetting ps = (PackageSetting) sb;
3841                if (userId == UserHandle.USER_ALL) {
3842                    killApplication(ps.pkg.packageName, ps.appId, reason);
3843                } else {
3844                    final int uid = UserHandle.getUid(userId, ps.appId);
3845                    killUid(uid, reason);
3846                }
3847            }
3848        } finally {
3849            Binder.restoreCallingIdentity(identity);
3850        }
3851    }
3852
3853    private static void killUid(int uid, String reason) {
3854        IActivityManager am = ActivityManagerNative.getDefault();
3855        if (am != null) {
3856            try {
3857                am.killUid(uid, reason);
3858            } catch (RemoteException e) {
3859                /* ignore - same process */
3860            }
3861        }
3862    }
3863
3864    /**
3865     * Compares two sets of signatures. Returns:
3866     * <br />
3867     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3868     * <br />
3869     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3870     * <br />
3871     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3872     * <br />
3873     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3874     * <br />
3875     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3876     */
3877    static int compareSignatures(Signature[] s1, Signature[] s2) {
3878        if (s1 == null) {
3879            return s2 == null
3880                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3881                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3882        }
3883
3884        if (s2 == null) {
3885            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3886        }
3887
3888        if (s1.length != s2.length) {
3889            return PackageManager.SIGNATURE_NO_MATCH;
3890        }
3891
3892        // Since both signature sets are of size 1, we can compare without HashSets.
3893        if (s1.length == 1) {
3894            return s1[0].equals(s2[0]) ?
3895                    PackageManager.SIGNATURE_MATCH :
3896                    PackageManager.SIGNATURE_NO_MATCH;
3897        }
3898
3899        ArraySet<Signature> set1 = new ArraySet<Signature>();
3900        for (Signature sig : s1) {
3901            set1.add(sig);
3902        }
3903        ArraySet<Signature> set2 = new ArraySet<Signature>();
3904        for (Signature sig : s2) {
3905            set2.add(sig);
3906        }
3907        // Make sure s2 contains all signatures in s1.
3908        if (set1.equals(set2)) {
3909            return PackageManager.SIGNATURE_MATCH;
3910        }
3911        return PackageManager.SIGNATURE_NO_MATCH;
3912    }
3913
3914    /**
3915     * If the database version for this type of package (internal storage or
3916     * external storage) is less than the version where package signatures
3917     * were updated, return true.
3918     */
3919    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3920        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3921                DatabaseVersion.SIGNATURE_END_ENTITY))
3922                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3923                        DatabaseVersion.SIGNATURE_END_ENTITY));
3924    }
3925
3926    /**
3927     * Used for backward compatibility to make sure any packages with
3928     * certificate chains get upgraded to the new style. {@code existingSigs}
3929     * will be in the old format (since they were stored on disk from before the
3930     * system upgrade) and {@code scannedSigs} will be in the newer format.
3931     */
3932    private int compareSignaturesCompat(PackageSignatures existingSigs,
3933            PackageParser.Package scannedPkg) {
3934        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3935            return PackageManager.SIGNATURE_NO_MATCH;
3936        }
3937
3938        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3939        for (Signature sig : existingSigs.mSignatures) {
3940            existingSet.add(sig);
3941        }
3942        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3943        for (Signature sig : scannedPkg.mSignatures) {
3944            try {
3945                Signature[] chainSignatures = sig.getChainSignatures();
3946                for (Signature chainSig : chainSignatures) {
3947                    scannedCompatSet.add(chainSig);
3948                }
3949            } catch (CertificateEncodingException e) {
3950                scannedCompatSet.add(sig);
3951            }
3952        }
3953        /*
3954         * Make sure the expanded scanned set contains all signatures in the
3955         * existing one.
3956         */
3957        if (scannedCompatSet.equals(existingSet)) {
3958            // Migrate the old signatures to the new scheme.
3959            existingSigs.assignSignatures(scannedPkg.mSignatures);
3960            // The new KeySets will be re-added later in the scanning process.
3961            synchronized (mPackages) {
3962                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3963            }
3964            return PackageManager.SIGNATURE_MATCH;
3965        }
3966        return PackageManager.SIGNATURE_NO_MATCH;
3967    }
3968
3969    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3970        if (isExternal(scannedPkg)) {
3971            return mSettings.isExternalDatabaseVersionOlderThan(
3972                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3973        } else {
3974            return mSettings.isInternalDatabaseVersionOlderThan(
3975                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3976        }
3977    }
3978
3979    private int compareSignaturesRecover(PackageSignatures existingSigs,
3980            PackageParser.Package scannedPkg) {
3981        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3982            return PackageManager.SIGNATURE_NO_MATCH;
3983        }
3984
3985        String msg = null;
3986        try {
3987            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3988                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3989                        + scannedPkg.packageName);
3990                return PackageManager.SIGNATURE_MATCH;
3991            }
3992        } catch (CertificateException e) {
3993            msg = e.getMessage();
3994        }
3995
3996        logCriticalInfo(Log.INFO,
3997                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3998        return PackageManager.SIGNATURE_NO_MATCH;
3999    }
4000
4001    @Override
4002    public String[] getPackagesForUid(int uid) {
4003        uid = UserHandle.getAppId(uid);
4004        // reader
4005        synchronized (mPackages) {
4006            Object obj = mSettings.getUserIdLPr(uid);
4007            if (obj instanceof SharedUserSetting) {
4008                final SharedUserSetting sus = (SharedUserSetting) obj;
4009                final int N = sus.packages.size();
4010                final String[] res = new String[N];
4011                final Iterator<PackageSetting> it = sus.packages.iterator();
4012                int i = 0;
4013                while (it.hasNext()) {
4014                    res[i++] = it.next().name;
4015                }
4016                return res;
4017            } else if (obj instanceof PackageSetting) {
4018                final PackageSetting ps = (PackageSetting) obj;
4019                return new String[] { ps.name };
4020            }
4021        }
4022        return null;
4023    }
4024
4025    @Override
4026    public String getNameForUid(int uid) {
4027        // reader
4028        synchronized (mPackages) {
4029            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4030            if (obj instanceof SharedUserSetting) {
4031                final SharedUserSetting sus = (SharedUserSetting) obj;
4032                return sus.name + ":" + sus.userId;
4033            } else if (obj instanceof PackageSetting) {
4034                final PackageSetting ps = (PackageSetting) obj;
4035                return ps.name;
4036            }
4037        }
4038        return null;
4039    }
4040
4041    @Override
4042    public int getUidForSharedUser(String sharedUserName) {
4043        if(sharedUserName == null) {
4044            return -1;
4045        }
4046        // reader
4047        synchronized (mPackages) {
4048            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4049            if (suid == null) {
4050                return -1;
4051            }
4052            return suid.userId;
4053        }
4054    }
4055
4056    @Override
4057    public int getFlagsForUid(int uid) {
4058        synchronized (mPackages) {
4059            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4060            if (obj instanceof SharedUserSetting) {
4061                final SharedUserSetting sus = (SharedUserSetting) obj;
4062                return sus.pkgFlags;
4063            } else if (obj instanceof PackageSetting) {
4064                final PackageSetting ps = (PackageSetting) obj;
4065                return ps.pkgFlags;
4066            }
4067        }
4068        return 0;
4069    }
4070
4071    @Override
4072    public int getPrivateFlagsForUid(int uid) {
4073        synchronized (mPackages) {
4074            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4075            if (obj instanceof SharedUserSetting) {
4076                final SharedUserSetting sus = (SharedUserSetting) obj;
4077                return sus.pkgPrivateFlags;
4078            } else if (obj instanceof PackageSetting) {
4079                final PackageSetting ps = (PackageSetting) obj;
4080                return ps.pkgPrivateFlags;
4081            }
4082        }
4083        return 0;
4084    }
4085
4086    @Override
4087    public boolean isUidPrivileged(int uid) {
4088        uid = UserHandle.getAppId(uid);
4089        // reader
4090        synchronized (mPackages) {
4091            Object obj = mSettings.getUserIdLPr(uid);
4092            if (obj instanceof SharedUserSetting) {
4093                final SharedUserSetting sus = (SharedUserSetting) obj;
4094                final Iterator<PackageSetting> it = sus.packages.iterator();
4095                while (it.hasNext()) {
4096                    if (it.next().isPrivileged()) {
4097                        return true;
4098                    }
4099                }
4100            } else if (obj instanceof PackageSetting) {
4101                final PackageSetting ps = (PackageSetting) obj;
4102                return ps.isPrivileged();
4103            }
4104        }
4105        return false;
4106    }
4107
4108    @Override
4109    public String[] getAppOpPermissionPackages(String permissionName) {
4110        synchronized (mPackages) {
4111            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4112            if (pkgs == null) {
4113                return null;
4114            }
4115            return pkgs.toArray(new String[pkgs.size()]);
4116        }
4117    }
4118
4119    @Override
4120    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4121            int flags, int userId) {
4122        if (!sUserManager.exists(userId)) return null;
4123        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4124        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4125        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4126    }
4127
4128    @Override
4129    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4130            IntentFilter filter, int match, ComponentName activity) {
4131        final int userId = UserHandle.getCallingUserId();
4132        if (DEBUG_PREFERRED) {
4133            Log.v(TAG, "setLastChosenActivity intent=" + intent
4134                + " resolvedType=" + resolvedType
4135                + " flags=" + flags
4136                + " filter=" + filter
4137                + " match=" + match
4138                + " activity=" + activity);
4139            filter.dump(new PrintStreamPrinter(System.out), "    ");
4140        }
4141        intent.setComponent(null);
4142        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4143        // Find any earlier preferred or last chosen entries and nuke them
4144        findPreferredActivity(intent, resolvedType,
4145                flags, query, 0, false, true, false, userId);
4146        // Add the new activity as the last chosen for this filter
4147        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4148                "Setting last chosen");
4149    }
4150
4151    @Override
4152    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4153        final int userId = UserHandle.getCallingUserId();
4154        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4155        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4156        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4157                false, false, false, userId);
4158    }
4159
4160    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4161            int flags, List<ResolveInfo> query, int userId) {
4162        if (query != null) {
4163            final int N = query.size();
4164            if (N == 1) {
4165                return query.get(0);
4166            } else if (N > 1) {
4167                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4168                // If there is more than one activity with the same priority,
4169                // then let the user decide between them.
4170                ResolveInfo r0 = query.get(0);
4171                ResolveInfo r1 = query.get(1);
4172                if (DEBUG_INTENT_MATCHING || debug) {
4173                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4174                            + r1.activityInfo.name + "=" + r1.priority);
4175                }
4176                // If the first activity has a higher priority, or a different
4177                // default, then it is always desireable to pick it.
4178                if (r0.priority != r1.priority
4179                        || r0.preferredOrder != r1.preferredOrder
4180                        || r0.isDefault != r1.isDefault) {
4181                    return query.get(0);
4182                }
4183                // If we have saved a preference for a preferred activity for
4184                // this Intent, use that.
4185                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4186                        flags, query, r0.priority, true, false, debug, userId);
4187                if (ri != null) {
4188                    return ri;
4189                }
4190                if (userId != 0) {
4191                    ri = new ResolveInfo(mResolveInfo);
4192                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4193                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4194                            ri.activityInfo.applicationInfo);
4195                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4196                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4197                    return ri;
4198                }
4199                return mResolveInfo;
4200            }
4201        }
4202        return null;
4203    }
4204
4205    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4206            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4207        final int N = query.size();
4208        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4209                .get(userId);
4210        // Get the list of persistent preferred activities that handle the intent
4211        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4212        List<PersistentPreferredActivity> pprefs = ppir != null
4213                ? ppir.queryIntent(intent, resolvedType,
4214                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4215                : null;
4216        if (pprefs != null && pprefs.size() > 0) {
4217            final int M = pprefs.size();
4218            for (int i=0; i<M; i++) {
4219                final PersistentPreferredActivity ppa = pprefs.get(i);
4220                if (DEBUG_PREFERRED || debug) {
4221                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4222                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4223                            + "\n  component=" + ppa.mComponent);
4224                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4225                }
4226                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4227                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4228                if (DEBUG_PREFERRED || debug) {
4229                    Slog.v(TAG, "Found persistent preferred activity:");
4230                    if (ai != null) {
4231                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4232                    } else {
4233                        Slog.v(TAG, "  null");
4234                    }
4235                }
4236                if (ai == null) {
4237                    // This previously registered persistent preferred activity
4238                    // component is no longer known. Ignore it and do NOT remove it.
4239                    continue;
4240                }
4241                for (int j=0; j<N; j++) {
4242                    final ResolveInfo ri = query.get(j);
4243                    if (!ri.activityInfo.applicationInfo.packageName
4244                            .equals(ai.applicationInfo.packageName)) {
4245                        continue;
4246                    }
4247                    if (!ri.activityInfo.name.equals(ai.name)) {
4248                        continue;
4249                    }
4250                    //  Found a persistent preference that can handle the intent.
4251                    if (DEBUG_PREFERRED || debug) {
4252                        Slog.v(TAG, "Returning persistent preferred activity: " +
4253                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4254                    }
4255                    return ri;
4256                }
4257            }
4258        }
4259        return null;
4260    }
4261
4262    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4263            List<ResolveInfo> query, int priority, boolean always,
4264            boolean removeMatches, boolean debug, int userId) {
4265        if (!sUserManager.exists(userId)) return null;
4266        // writer
4267        synchronized (mPackages) {
4268            if (intent.getSelector() != null) {
4269                intent = intent.getSelector();
4270            }
4271            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4272
4273            // Try to find a matching persistent preferred activity.
4274            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4275                    debug, userId);
4276
4277            // If a persistent preferred activity matched, use it.
4278            if (pri != null) {
4279                return pri;
4280            }
4281
4282            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4283            // Get the list of preferred activities that handle the intent
4284            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4285            List<PreferredActivity> prefs = pir != null
4286                    ? pir.queryIntent(intent, resolvedType,
4287                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4288                    : null;
4289            if (prefs != null && prefs.size() > 0) {
4290                boolean changed = false;
4291                try {
4292                    // First figure out how good the original match set is.
4293                    // We will only allow preferred activities that came
4294                    // from the same match quality.
4295                    int match = 0;
4296
4297                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4298
4299                    final int N = query.size();
4300                    for (int j=0; j<N; j++) {
4301                        final ResolveInfo ri = query.get(j);
4302                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4303                                + ": 0x" + Integer.toHexString(match));
4304                        if (ri.match > match) {
4305                            match = ri.match;
4306                        }
4307                    }
4308
4309                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4310                            + Integer.toHexString(match));
4311
4312                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4313                    final int M = prefs.size();
4314                    for (int i=0; i<M; i++) {
4315                        final PreferredActivity pa = prefs.get(i);
4316                        if (DEBUG_PREFERRED || debug) {
4317                            Slog.v(TAG, "Checking PreferredActivity ds="
4318                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4319                                    + "\n  component=" + pa.mPref.mComponent);
4320                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4321                        }
4322                        if (pa.mPref.mMatch != match) {
4323                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4324                                    + Integer.toHexString(pa.mPref.mMatch));
4325                            continue;
4326                        }
4327                        // If it's not an "always" type preferred activity and that's what we're
4328                        // looking for, skip it.
4329                        if (always && !pa.mPref.mAlways) {
4330                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4331                            continue;
4332                        }
4333                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4334                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4335                        if (DEBUG_PREFERRED || debug) {
4336                            Slog.v(TAG, "Found preferred activity:");
4337                            if (ai != null) {
4338                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4339                            } else {
4340                                Slog.v(TAG, "  null");
4341                            }
4342                        }
4343                        if (ai == null) {
4344                            // This previously registered preferred activity
4345                            // component is no longer known.  Most likely an update
4346                            // to the app was installed and in the new version this
4347                            // component no longer exists.  Clean it up by removing
4348                            // it from the preferred activities list, and skip it.
4349                            Slog.w(TAG, "Removing dangling preferred activity: "
4350                                    + pa.mPref.mComponent);
4351                            pir.removeFilter(pa);
4352                            changed = true;
4353                            continue;
4354                        }
4355                        for (int j=0; j<N; j++) {
4356                            final ResolveInfo ri = query.get(j);
4357                            if (!ri.activityInfo.applicationInfo.packageName
4358                                    .equals(ai.applicationInfo.packageName)) {
4359                                continue;
4360                            }
4361                            if (!ri.activityInfo.name.equals(ai.name)) {
4362                                continue;
4363                            }
4364
4365                            if (removeMatches) {
4366                                pir.removeFilter(pa);
4367                                changed = true;
4368                                if (DEBUG_PREFERRED) {
4369                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4370                                }
4371                                break;
4372                            }
4373
4374                            // Okay we found a previously set preferred or last chosen app.
4375                            // If the result set is different from when this
4376                            // was created, we need to clear it and re-ask the
4377                            // user their preference, if we're looking for an "always" type entry.
4378                            if (always && !pa.mPref.sameSet(query)) {
4379                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4380                                        + intent + " type " + resolvedType);
4381                                if (DEBUG_PREFERRED) {
4382                                    Slog.v(TAG, "Removing preferred activity since set changed "
4383                                            + pa.mPref.mComponent);
4384                                }
4385                                pir.removeFilter(pa);
4386                                // Re-add the filter as a "last chosen" entry (!always)
4387                                PreferredActivity lastChosen = new PreferredActivity(
4388                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4389                                pir.addFilter(lastChosen);
4390                                changed = true;
4391                                return null;
4392                            }
4393
4394                            // Yay! Either the set matched or we're looking for the last chosen
4395                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4396                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4397                            return ri;
4398                        }
4399                    }
4400                } finally {
4401                    if (changed) {
4402                        if (DEBUG_PREFERRED) {
4403                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4404                        }
4405                        scheduleWritePackageRestrictionsLocked(userId);
4406                    }
4407                }
4408            }
4409        }
4410        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4411        return null;
4412    }
4413
4414    /*
4415     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4416     */
4417    @Override
4418    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4419            int targetUserId) {
4420        mContext.enforceCallingOrSelfPermission(
4421                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4422        List<CrossProfileIntentFilter> matches =
4423                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4424        if (matches != null) {
4425            int size = matches.size();
4426            for (int i = 0; i < size; i++) {
4427                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4428            }
4429        }
4430        if (hasWebURI(intent)) {
4431            // cross-profile app linking works only towards the parent.
4432            final UserInfo parent = getProfileParent(sourceUserId);
4433            synchronized(mPackages) {
4434                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4435                        intent, resolvedType, 0, sourceUserId, parent.id);
4436                return xpDomainInfo != null;
4437            }
4438        }
4439        return false;
4440    }
4441
4442    private UserInfo getProfileParent(int userId) {
4443        final long identity = Binder.clearCallingIdentity();
4444        try {
4445            return sUserManager.getProfileParent(userId);
4446        } finally {
4447            Binder.restoreCallingIdentity(identity);
4448        }
4449    }
4450
4451    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4452            String resolvedType, int userId) {
4453        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4454        if (resolver != null) {
4455            return resolver.queryIntent(intent, resolvedType, false, userId);
4456        }
4457        return null;
4458    }
4459
4460    @Override
4461    public List<ResolveInfo> queryIntentActivities(Intent intent,
4462            String resolvedType, int flags, int userId) {
4463        if (!sUserManager.exists(userId)) return Collections.emptyList();
4464        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4465        ComponentName comp = intent.getComponent();
4466        if (comp == null) {
4467            if (intent.getSelector() != null) {
4468                intent = intent.getSelector();
4469                comp = intent.getComponent();
4470            }
4471        }
4472
4473        if (comp != null) {
4474            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4475            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4476            if (ai != null) {
4477                final ResolveInfo ri = new ResolveInfo();
4478                ri.activityInfo = ai;
4479                list.add(ri);
4480            }
4481            return list;
4482        }
4483
4484        // reader
4485        synchronized (mPackages) {
4486            final String pkgName = intent.getPackage();
4487            if (pkgName == null) {
4488                List<CrossProfileIntentFilter> matchingFilters =
4489                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4490                // Check for results that need to skip the current profile.
4491                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4492                        resolvedType, flags, userId);
4493                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4494                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4495                    result.add(xpResolveInfo);
4496                    return filterIfNotPrimaryUser(result, userId);
4497                }
4498
4499                // Check for results in the current profile.
4500                List<ResolveInfo> result = mActivities.queryIntent(
4501                        intent, resolvedType, flags, userId);
4502
4503                // Check for cross profile results.
4504                xpResolveInfo = queryCrossProfileIntents(
4505                        matchingFilters, intent, resolvedType, flags, userId);
4506                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4507                    result.add(xpResolveInfo);
4508                    Collections.sort(result, mResolvePrioritySorter);
4509                }
4510                result = filterIfNotPrimaryUser(result, userId);
4511                if (hasWebURI(intent)) {
4512                    CrossProfileDomainInfo xpDomainInfo = null;
4513                    final UserInfo parent = getProfileParent(userId);
4514                    if (parent != null) {
4515                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4516                                flags, userId, parent.id);
4517                    }
4518                    if (xpDomainInfo != null) {
4519                        if (xpResolveInfo != null) {
4520                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4521                            // in the result.
4522                            result.remove(xpResolveInfo);
4523                        }
4524                        if (result.size() == 0) {
4525                            result.add(xpDomainInfo.resolveInfo);
4526                            return result;
4527                        }
4528                    } else if (result.size() <= 1) {
4529                        return result;
4530                    }
4531                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4532                            xpDomainInfo, userId);
4533                    Collections.sort(result, mResolvePrioritySorter);
4534                }
4535                return result;
4536            }
4537            final PackageParser.Package pkg = mPackages.get(pkgName);
4538            if (pkg != null) {
4539                return filterIfNotPrimaryUser(
4540                        mActivities.queryIntentForPackage(
4541                                intent, resolvedType, flags, pkg.activities, userId),
4542                        userId);
4543            }
4544            return new ArrayList<ResolveInfo>();
4545        }
4546    }
4547
4548    private static class CrossProfileDomainInfo {
4549        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4550        ResolveInfo resolveInfo;
4551        /* Best domain verification status of the activities found in the other profile */
4552        int bestDomainVerificationStatus;
4553    }
4554
4555    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4556            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4557        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4558                sourceUserId)) {
4559            return null;
4560        }
4561        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4562                resolvedType, flags, parentUserId);
4563
4564        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4565            return null;
4566        }
4567        CrossProfileDomainInfo result = null;
4568        int size = resultTargetUser.size();
4569        for (int i = 0; i < size; i++) {
4570            ResolveInfo riTargetUser = resultTargetUser.get(i);
4571            // Intent filter verification is only for filters that specify a host. So don't return
4572            // those that handle all web uris.
4573            if (riTargetUser.handleAllWebDataURI) {
4574                continue;
4575            }
4576            String packageName = riTargetUser.activityInfo.packageName;
4577            PackageSetting ps = mSettings.mPackages.get(packageName);
4578            if (ps == null) {
4579                continue;
4580            }
4581            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4582            int status = (int)(verificationState >> 32);
4583            if (result == null) {
4584                result = new CrossProfileDomainInfo();
4585                result.resolveInfo =
4586                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4587                result.bestDomainVerificationStatus = status;
4588            } else {
4589                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4590                        result.bestDomainVerificationStatus);
4591            }
4592        }
4593        // Don't consider matches with status NEVER across profiles.
4594        if (result != null && result.bestDomainVerificationStatus
4595                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4596            return null;
4597        }
4598        return result;
4599    }
4600
4601    /**
4602     * Verification statuses are ordered from the worse to the best, except for
4603     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4604     */
4605    private int bestDomainVerificationStatus(int status1, int status2) {
4606        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4607            return status2;
4608        }
4609        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4610            return status1;
4611        }
4612        return (int) MathUtils.max(status1, status2);
4613    }
4614
4615    private boolean isUserEnabled(int userId) {
4616        long callingId = Binder.clearCallingIdentity();
4617        try {
4618            UserInfo userInfo = sUserManager.getUserInfo(userId);
4619            return userInfo != null && userInfo.isEnabled();
4620        } finally {
4621            Binder.restoreCallingIdentity(callingId);
4622        }
4623    }
4624
4625    /**
4626     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4627     *
4628     * @return filtered list
4629     */
4630    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4631        if (userId == UserHandle.USER_OWNER) {
4632            return resolveInfos;
4633        }
4634        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4635            ResolveInfo info = resolveInfos.get(i);
4636            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4637                resolveInfos.remove(i);
4638            }
4639        }
4640        return resolveInfos;
4641    }
4642
4643    private static boolean hasWebURI(Intent intent) {
4644        if (intent.getData() == null) {
4645            return false;
4646        }
4647        final String scheme = intent.getScheme();
4648        if (TextUtils.isEmpty(scheme)) {
4649            return false;
4650        }
4651        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4652    }
4653
4654    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4655            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4656            int userId) {
4657        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4658
4659        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4660            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4661                    candidates.size());
4662        }
4663
4664        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4665        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4666        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4667        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4668        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4669
4670        synchronized (mPackages) {
4671            final int count = candidates.size();
4672            // First, try to use linked apps. Partition the candidates into four lists:
4673            // one for the final results, one for the "do not use ever", one for "undefined status"
4674            // and finally one for "browser app type".
4675            for (int n=0; n<count; n++) {
4676                ResolveInfo info = candidates.get(n);
4677                String packageName = info.activityInfo.packageName;
4678                PackageSetting ps = mSettings.mPackages.get(packageName);
4679                if (ps != null) {
4680                    // Add to the special match all list (Browser use case)
4681                    if (info.handleAllWebDataURI) {
4682                        matchAllList.add(info);
4683                        continue;
4684                    }
4685                    // Try to get the status from User settings first
4686                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4687                    int status = (int)(packedStatus >> 32);
4688                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4689                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4690                        if (DEBUG_DOMAIN_VERIFICATION) {
4691                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4692                                    + " : linkgen=" + linkGeneration);
4693                        }
4694                        // Use link-enabled generation as preferredOrder, i.e.
4695                        // prefer newly-enabled over earlier-enabled.
4696                        info.preferredOrder = linkGeneration;
4697                        alwaysList.add(info);
4698                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4699                        if (DEBUG_DOMAIN_VERIFICATION) {
4700                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4701                        }
4702                        neverList.add(info);
4703                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4704                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4705                        if (DEBUG_DOMAIN_VERIFICATION) {
4706                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4707                        }
4708                        undefinedList.add(info);
4709                    }
4710                }
4711            }
4712            // First try to add the "always" resolution(s) for the current user, if any
4713            if (alwaysList.size() > 0) {
4714                result.addAll(alwaysList);
4715            // if there is an "always" for the parent user, add it.
4716            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4717                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4718                result.add(xpDomainInfo.resolveInfo);
4719            } else {
4720                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4721                result.addAll(undefinedList);
4722                if (xpDomainInfo != null && (
4723                        xpDomainInfo.bestDomainVerificationStatus
4724                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4725                        || xpDomainInfo.bestDomainVerificationStatus
4726                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4727                    result.add(xpDomainInfo.resolveInfo);
4728                }
4729                // Also add Browsers (all of them or only the default one)
4730                if ((matchFlags & MATCH_ALL) != 0) {
4731                    result.addAll(matchAllList);
4732                } else {
4733                    // Browser/generic handling case.  If there's a default browser, go straight
4734                    // to that (but only if there is no other higher-priority match).
4735                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4736                    int maxMatchPrio = 0;
4737                    ResolveInfo defaultBrowserMatch = null;
4738                    final int numCandidates = matchAllList.size();
4739                    for (int n = 0; n < numCandidates; n++) {
4740                        ResolveInfo info = matchAllList.get(n);
4741                        // track the highest overall match priority...
4742                        if (info.priority > maxMatchPrio) {
4743                            maxMatchPrio = info.priority;
4744                        }
4745                        // ...and the highest-priority default browser match
4746                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4747                            if (defaultBrowserMatch == null
4748                                    || (defaultBrowserMatch.priority < info.priority)) {
4749                                if (debug) {
4750                                    Slog.v(TAG, "Considering default browser match " + info);
4751                                }
4752                                defaultBrowserMatch = info;
4753                            }
4754                        }
4755                    }
4756                    if (defaultBrowserMatch != null
4757                            && defaultBrowserMatch.priority >= maxMatchPrio
4758                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4759                    {
4760                        if (debug) {
4761                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4762                        }
4763                        result.add(defaultBrowserMatch);
4764                    } else {
4765                        result.addAll(matchAllList);
4766                    }
4767                }
4768
4769                // If there is nothing selected, add all candidates and remove the ones that the user
4770                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4771                if (result.size() == 0) {
4772                    result.addAll(candidates);
4773                    result.removeAll(neverList);
4774                }
4775            }
4776        }
4777        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4778            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4779                    result.size());
4780            for (ResolveInfo info : result) {
4781                Slog.v(TAG, "  + " + info.activityInfo);
4782            }
4783        }
4784        return result;
4785    }
4786
4787    // Returns a packed value as a long:
4788    //
4789    // high 'int'-sized word: link status: undefined/ask/never/always.
4790    // low 'int'-sized word: relative priority among 'always' results.
4791    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4792        long result = ps.getDomainVerificationStatusForUser(userId);
4793        // if none available, get the master status
4794        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4795            if (ps.getIntentFilterVerificationInfo() != null) {
4796                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4797            }
4798        }
4799        return result;
4800    }
4801
4802    private ResolveInfo querySkipCurrentProfileIntents(
4803            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4804            int flags, int sourceUserId) {
4805        if (matchingFilters != null) {
4806            int size = matchingFilters.size();
4807            for (int i = 0; i < size; i ++) {
4808                CrossProfileIntentFilter filter = matchingFilters.get(i);
4809                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4810                    // Checking if there are activities in the target user that can handle the
4811                    // intent.
4812                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4813                            flags, sourceUserId);
4814                    if (resolveInfo != null) {
4815                        return resolveInfo;
4816                    }
4817                }
4818            }
4819        }
4820        return null;
4821    }
4822
4823    // Return matching ResolveInfo if any for skip current profile intent filters.
4824    private ResolveInfo queryCrossProfileIntents(
4825            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4826            int flags, int sourceUserId) {
4827        if (matchingFilters != null) {
4828            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4829            // match the same intent. For performance reasons, it is better not to
4830            // run queryIntent twice for the same userId
4831            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4832            int size = matchingFilters.size();
4833            for (int i = 0; i < size; i++) {
4834                CrossProfileIntentFilter filter = matchingFilters.get(i);
4835                int targetUserId = filter.getTargetUserId();
4836                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4837                        && !alreadyTriedUserIds.get(targetUserId)) {
4838                    // Checking if there are activities in the target user that can handle the
4839                    // intent.
4840                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4841                            flags, sourceUserId);
4842                    if (resolveInfo != null) return resolveInfo;
4843                    alreadyTriedUserIds.put(targetUserId, true);
4844                }
4845            }
4846        }
4847        return null;
4848    }
4849
4850    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4851            String resolvedType, int flags, int sourceUserId) {
4852        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4853                resolvedType, flags, filter.getTargetUserId());
4854        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4855            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4856        }
4857        return null;
4858    }
4859
4860    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4861            int sourceUserId, int targetUserId) {
4862        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4863        String className;
4864        if (targetUserId == UserHandle.USER_OWNER) {
4865            className = FORWARD_INTENT_TO_USER_OWNER;
4866        } else {
4867            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4868        }
4869        ComponentName forwardingActivityComponentName = new ComponentName(
4870                mAndroidApplication.packageName, className);
4871        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4872                sourceUserId);
4873        if (targetUserId == UserHandle.USER_OWNER) {
4874            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4875            forwardingResolveInfo.noResourceId = true;
4876        }
4877        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4878        forwardingResolveInfo.priority = 0;
4879        forwardingResolveInfo.preferredOrder = 0;
4880        forwardingResolveInfo.match = 0;
4881        forwardingResolveInfo.isDefault = true;
4882        forwardingResolveInfo.filter = filter;
4883        forwardingResolveInfo.targetUserId = targetUserId;
4884        return forwardingResolveInfo;
4885    }
4886
4887    @Override
4888    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4889            Intent[] specifics, String[] specificTypes, Intent intent,
4890            String resolvedType, int flags, int userId) {
4891        if (!sUserManager.exists(userId)) return Collections.emptyList();
4892        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4893                false, "query intent activity options");
4894        final String resultsAction = intent.getAction();
4895
4896        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4897                | PackageManager.GET_RESOLVED_FILTER, userId);
4898
4899        if (DEBUG_INTENT_MATCHING) {
4900            Log.v(TAG, "Query " + intent + ": " + results);
4901        }
4902
4903        int specificsPos = 0;
4904        int N;
4905
4906        // todo: note that the algorithm used here is O(N^2).  This
4907        // isn't a problem in our current environment, but if we start running
4908        // into situations where we have more than 5 or 10 matches then this
4909        // should probably be changed to something smarter...
4910
4911        // First we go through and resolve each of the specific items
4912        // that were supplied, taking care of removing any corresponding
4913        // duplicate items in the generic resolve list.
4914        if (specifics != null) {
4915            for (int i=0; i<specifics.length; i++) {
4916                final Intent sintent = specifics[i];
4917                if (sintent == null) {
4918                    continue;
4919                }
4920
4921                if (DEBUG_INTENT_MATCHING) {
4922                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4923                }
4924
4925                String action = sintent.getAction();
4926                if (resultsAction != null && resultsAction.equals(action)) {
4927                    // If this action was explicitly requested, then don't
4928                    // remove things that have it.
4929                    action = null;
4930                }
4931
4932                ResolveInfo ri = null;
4933                ActivityInfo ai = null;
4934
4935                ComponentName comp = sintent.getComponent();
4936                if (comp == null) {
4937                    ri = resolveIntent(
4938                        sintent,
4939                        specificTypes != null ? specificTypes[i] : null,
4940                            flags, userId);
4941                    if (ri == null) {
4942                        continue;
4943                    }
4944                    if (ri == mResolveInfo) {
4945                        // ACK!  Must do something better with this.
4946                    }
4947                    ai = ri.activityInfo;
4948                    comp = new ComponentName(ai.applicationInfo.packageName,
4949                            ai.name);
4950                } else {
4951                    ai = getActivityInfo(comp, flags, userId);
4952                    if (ai == null) {
4953                        continue;
4954                    }
4955                }
4956
4957                // Look for any generic query activities that are duplicates
4958                // of this specific one, and remove them from the results.
4959                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4960                N = results.size();
4961                int j;
4962                for (j=specificsPos; j<N; j++) {
4963                    ResolveInfo sri = results.get(j);
4964                    if ((sri.activityInfo.name.equals(comp.getClassName())
4965                            && sri.activityInfo.applicationInfo.packageName.equals(
4966                                    comp.getPackageName()))
4967                        || (action != null && sri.filter.matchAction(action))) {
4968                        results.remove(j);
4969                        if (DEBUG_INTENT_MATCHING) Log.v(
4970                            TAG, "Removing duplicate item from " + j
4971                            + " due to specific " + specificsPos);
4972                        if (ri == null) {
4973                            ri = sri;
4974                        }
4975                        j--;
4976                        N--;
4977                    }
4978                }
4979
4980                // Add this specific item to its proper place.
4981                if (ri == null) {
4982                    ri = new ResolveInfo();
4983                    ri.activityInfo = ai;
4984                }
4985                results.add(specificsPos, ri);
4986                ri.specificIndex = i;
4987                specificsPos++;
4988            }
4989        }
4990
4991        // Now we go through the remaining generic results and remove any
4992        // duplicate actions that are found here.
4993        N = results.size();
4994        for (int i=specificsPos; i<N-1; i++) {
4995            final ResolveInfo rii = results.get(i);
4996            if (rii.filter == null) {
4997                continue;
4998            }
4999
5000            // Iterate over all of the actions of this result's intent
5001            // filter...  typically this should be just one.
5002            final Iterator<String> it = rii.filter.actionsIterator();
5003            if (it == null) {
5004                continue;
5005            }
5006            while (it.hasNext()) {
5007                final String action = it.next();
5008                if (resultsAction != null && resultsAction.equals(action)) {
5009                    // If this action was explicitly requested, then don't
5010                    // remove things that have it.
5011                    continue;
5012                }
5013                for (int j=i+1; j<N; j++) {
5014                    final ResolveInfo rij = results.get(j);
5015                    if (rij.filter != null && rij.filter.hasAction(action)) {
5016                        results.remove(j);
5017                        if (DEBUG_INTENT_MATCHING) Log.v(
5018                            TAG, "Removing duplicate item from " + j
5019                            + " due to action " + action + " at " + i);
5020                        j--;
5021                        N--;
5022                    }
5023                }
5024            }
5025
5026            // If the caller didn't request filter information, drop it now
5027            // so we don't have to marshall/unmarshall it.
5028            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5029                rii.filter = null;
5030            }
5031        }
5032
5033        // Filter out the caller activity if so requested.
5034        if (caller != null) {
5035            N = results.size();
5036            for (int i=0; i<N; i++) {
5037                ActivityInfo ainfo = results.get(i).activityInfo;
5038                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5039                        && caller.getClassName().equals(ainfo.name)) {
5040                    results.remove(i);
5041                    break;
5042                }
5043            }
5044        }
5045
5046        // If the caller didn't request filter information,
5047        // drop them now so we don't have to
5048        // marshall/unmarshall it.
5049        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5050            N = results.size();
5051            for (int i=0; i<N; i++) {
5052                results.get(i).filter = null;
5053            }
5054        }
5055
5056        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5057        return results;
5058    }
5059
5060    @Override
5061    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5062            int userId) {
5063        if (!sUserManager.exists(userId)) return Collections.emptyList();
5064        ComponentName comp = intent.getComponent();
5065        if (comp == null) {
5066            if (intent.getSelector() != null) {
5067                intent = intent.getSelector();
5068                comp = intent.getComponent();
5069            }
5070        }
5071        if (comp != null) {
5072            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5073            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5074            if (ai != null) {
5075                ResolveInfo ri = new ResolveInfo();
5076                ri.activityInfo = ai;
5077                list.add(ri);
5078            }
5079            return list;
5080        }
5081
5082        // reader
5083        synchronized (mPackages) {
5084            String pkgName = intent.getPackage();
5085            if (pkgName == null) {
5086                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5087            }
5088            final PackageParser.Package pkg = mPackages.get(pkgName);
5089            if (pkg != null) {
5090                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5091                        userId);
5092            }
5093            return null;
5094        }
5095    }
5096
5097    @Override
5098    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5099        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5100        if (!sUserManager.exists(userId)) return null;
5101        if (query != null) {
5102            if (query.size() >= 1) {
5103                // If there is more than one service with the same priority,
5104                // just arbitrarily pick the first one.
5105                return query.get(0);
5106            }
5107        }
5108        return null;
5109    }
5110
5111    @Override
5112    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5113            int userId) {
5114        if (!sUserManager.exists(userId)) return Collections.emptyList();
5115        ComponentName comp = intent.getComponent();
5116        if (comp == null) {
5117            if (intent.getSelector() != null) {
5118                intent = intent.getSelector();
5119                comp = intent.getComponent();
5120            }
5121        }
5122        if (comp != null) {
5123            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5124            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5125            if (si != null) {
5126                final ResolveInfo ri = new ResolveInfo();
5127                ri.serviceInfo = si;
5128                list.add(ri);
5129            }
5130            return list;
5131        }
5132
5133        // reader
5134        synchronized (mPackages) {
5135            String pkgName = intent.getPackage();
5136            if (pkgName == null) {
5137                return mServices.queryIntent(intent, resolvedType, flags, userId);
5138            }
5139            final PackageParser.Package pkg = mPackages.get(pkgName);
5140            if (pkg != null) {
5141                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5142                        userId);
5143            }
5144            return null;
5145        }
5146    }
5147
5148    @Override
5149    public List<ResolveInfo> queryIntentContentProviders(
5150            Intent intent, String resolvedType, int flags, int userId) {
5151        if (!sUserManager.exists(userId)) return Collections.emptyList();
5152        ComponentName comp = intent.getComponent();
5153        if (comp == null) {
5154            if (intent.getSelector() != null) {
5155                intent = intent.getSelector();
5156                comp = intent.getComponent();
5157            }
5158        }
5159        if (comp != null) {
5160            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5161            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5162            if (pi != null) {
5163                final ResolveInfo ri = new ResolveInfo();
5164                ri.providerInfo = pi;
5165                list.add(ri);
5166            }
5167            return list;
5168        }
5169
5170        // reader
5171        synchronized (mPackages) {
5172            String pkgName = intent.getPackage();
5173            if (pkgName == null) {
5174                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5175            }
5176            final PackageParser.Package pkg = mPackages.get(pkgName);
5177            if (pkg != null) {
5178                return mProviders.queryIntentForPackage(
5179                        intent, resolvedType, flags, pkg.providers, userId);
5180            }
5181            return null;
5182        }
5183    }
5184
5185    @Override
5186    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5187        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5188
5189        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5190
5191        // writer
5192        synchronized (mPackages) {
5193            ArrayList<PackageInfo> list;
5194            if (listUninstalled) {
5195                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5196                for (PackageSetting ps : mSettings.mPackages.values()) {
5197                    PackageInfo pi;
5198                    if (ps.pkg != null) {
5199                        pi = generatePackageInfo(ps.pkg, flags, userId);
5200                    } else {
5201                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5202                    }
5203                    if (pi != null) {
5204                        list.add(pi);
5205                    }
5206                }
5207            } else {
5208                list = new ArrayList<PackageInfo>(mPackages.size());
5209                for (PackageParser.Package p : mPackages.values()) {
5210                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5211                    if (pi != null) {
5212                        list.add(pi);
5213                    }
5214                }
5215            }
5216
5217            return new ParceledListSlice<PackageInfo>(list);
5218        }
5219    }
5220
5221    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5222            String[] permissions, boolean[] tmp, int flags, int userId) {
5223        int numMatch = 0;
5224        final PermissionsState permissionsState = ps.getPermissionsState();
5225        for (int i=0; i<permissions.length; i++) {
5226            final String permission = permissions[i];
5227            if (permissionsState.hasPermission(permission, userId)) {
5228                tmp[i] = true;
5229                numMatch++;
5230            } else {
5231                tmp[i] = false;
5232            }
5233        }
5234        if (numMatch == 0) {
5235            return;
5236        }
5237        PackageInfo pi;
5238        if (ps.pkg != null) {
5239            pi = generatePackageInfo(ps.pkg, flags, userId);
5240        } else {
5241            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5242        }
5243        // The above might return null in cases of uninstalled apps or install-state
5244        // skew across users/profiles.
5245        if (pi != null) {
5246            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5247                if (numMatch == permissions.length) {
5248                    pi.requestedPermissions = permissions;
5249                } else {
5250                    pi.requestedPermissions = new String[numMatch];
5251                    numMatch = 0;
5252                    for (int i=0; i<permissions.length; i++) {
5253                        if (tmp[i]) {
5254                            pi.requestedPermissions[numMatch] = permissions[i];
5255                            numMatch++;
5256                        }
5257                    }
5258                }
5259            }
5260            list.add(pi);
5261        }
5262    }
5263
5264    @Override
5265    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5266            String[] permissions, int flags, int userId) {
5267        if (!sUserManager.exists(userId)) return null;
5268        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5269
5270        // writer
5271        synchronized (mPackages) {
5272            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5273            boolean[] tmpBools = new boolean[permissions.length];
5274            if (listUninstalled) {
5275                for (PackageSetting ps : mSettings.mPackages.values()) {
5276                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5277                }
5278            } else {
5279                for (PackageParser.Package pkg : mPackages.values()) {
5280                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5281                    if (ps != null) {
5282                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5283                                userId);
5284                    }
5285                }
5286            }
5287
5288            return new ParceledListSlice<PackageInfo>(list);
5289        }
5290    }
5291
5292    @Override
5293    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5294        if (!sUserManager.exists(userId)) return null;
5295        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5296
5297        // writer
5298        synchronized (mPackages) {
5299            ArrayList<ApplicationInfo> list;
5300            if (listUninstalled) {
5301                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5302                for (PackageSetting ps : mSettings.mPackages.values()) {
5303                    ApplicationInfo ai;
5304                    if (ps.pkg != null) {
5305                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5306                                ps.readUserState(userId), userId);
5307                    } else {
5308                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5309                    }
5310                    if (ai != null) {
5311                        list.add(ai);
5312                    }
5313                }
5314            } else {
5315                list = new ArrayList<ApplicationInfo>(mPackages.size());
5316                for (PackageParser.Package p : mPackages.values()) {
5317                    if (p.mExtras != null) {
5318                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5319                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5320                        if (ai != null) {
5321                            list.add(ai);
5322                        }
5323                    }
5324                }
5325            }
5326
5327            return new ParceledListSlice<ApplicationInfo>(list);
5328        }
5329    }
5330
5331    public List<ApplicationInfo> getPersistentApplications(int flags) {
5332        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5333
5334        // reader
5335        synchronized (mPackages) {
5336            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5337            final int userId = UserHandle.getCallingUserId();
5338            while (i.hasNext()) {
5339                final PackageParser.Package p = i.next();
5340                if (p.applicationInfo != null
5341                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5342                        && (!mSafeMode || isSystemApp(p))) {
5343                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5344                    if (ps != null) {
5345                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5346                                ps.readUserState(userId), userId);
5347                        if (ai != null) {
5348                            finalList.add(ai);
5349                        }
5350                    }
5351                }
5352            }
5353        }
5354
5355        return finalList;
5356    }
5357
5358    @Override
5359    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5360        if (!sUserManager.exists(userId)) return null;
5361        // reader
5362        synchronized (mPackages) {
5363            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5364            PackageSetting ps = provider != null
5365                    ? mSettings.mPackages.get(provider.owner.packageName)
5366                    : null;
5367            return ps != null
5368                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5369                    && (!mSafeMode || (provider.info.applicationInfo.flags
5370                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5371                    ? PackageParser.generateProviderInfo(provider, flags,
5372                            ps.readUserState(userId), userId)
5373                    : null;
5374        }
5375    }
5376
5377    /**
5378     * @deprecated
5379     */
5380    @Deprecated
5381    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5382        // reader
5383        synchronized (mPackages) {
5384            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5385                    .entrySet().iterator();
5386            final int userId = UserHandle.getCallingUserId();
5387            while (i.hasNext()) {
5388                Map.Entry<String, PackageParser.Provider> entry = i.next();
5389                PackageParser.Provider p = entry.getValue();
5390                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5391
5392                if (ps != null && p.syncable
5393                        && (!mSafeMode || (p.info.applicationInfo.flags
5394                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5395                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5396                            ps.readUserState(userId), userId);
5397                    if (info != null) {
5398                        outNames.add(entry.getKey());
5399                        outInfo.add(info);
5400                    }
5401                }
5402            }
5403        }
5404    }
5405
5406    @Override
5407    public List<ProviderInfo> queryContentProviders(String processName,
5408            int uid, int flags) {
5409        ArrayList<ProviderInfo> finalList = null;
5410        // reader
5411        synchronized (mPackages) {
5412            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5413            final int userId = processName != null ?
5414                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5415            while (i.hasNext()) {
5416                final PackageParser.Provider p = i.next();
5417                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5418                if (ps != null && p.info.authority != null
5419                        && (processName == null
5420                                || (p.info.processName.equals(processName)
5421                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5422                        && mSettings.isEnabledLPr(p.info, flags, userId)
5423                        && (!mSafeMode
5424                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5425                    if (finalList == null) {
5426                        finalList = new ArrayList<ProviderInfo>(3);
5427                    }
5428                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5429                            ps.readUserState(userId), userId);
5430                    if (info != null) {
5431                        finalList.add(info);
5432                    }
5433                }
5434            }
5435        }
5436
5437        if (finalList != null) {
5438            Collections.sort(finalList, mProviderInitOrderSorter);
5439        }
5440
5441        return finalList;
5442    }
5443
5444    @Override
5445    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5446            int flags) {
5447        // reader
5448        synchronized (mPackages) {
5449            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5450            return PackageParser.generateInstrumentationInfo(i, flags);
5451        }
5452    }
5453
5454    @Override
5455    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5456            int flags) {
5457        ArrayList<InstrumentationInfo> finalList =
5458            new ArrayList<InstrumentationInfo>();
5459
5460        // reader
5461        synchronized (mPackages) {
5462            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5463            while (i.hasNext()) {
5464                final PackageParser.Instrumentation p = i.next();
5465                if (targetPackage == null
5466                        || targetPackage.equals(p.info.targetPackage)) {
5467                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5468                            flags);
5469                    if (ii != null) {
5470                        finalList.add(ii);
5471                    }
5472                }
5473            }
5474        }
5475
5476        return finalList;
5477    }
5478
5479    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5480        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5481        if (overlays == null) {
5482            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5483            return;
5484        }
5485        for (PackageParser.Package opkg : overlays.values()) {
5486            // Not much to do if idmap fails: we already logged the error
5487            // and we certainly don't want to abort installation of pkg simply
5488            // because an overlay didn't fit properly. For these reasons,
5489            // ignore the return value of createIdmapForPackagePairLI.
5490            createIdmapForPackagePairLI(pkg, opkg);
5491        }
5492    }
5493
5494    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5495            PackageParser.Package opkg) {
5496        if (!opkg.mTrustedOverlay) {
5497            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5498                    opkg.baseCodePath + ": overlay not trusted");
5499            return false;
5500        }
5501        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5502        if (overlaySet == null) {
5503            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5504                    opkg.baseCodePath + " but target package has no known overlays");
5505            return false;
5506        }
5507        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5508        // TODO: generate idmap for split APKs
5509        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5510            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5511                    + opkg.baseCodePath);
5512            return false;
5513        }
5514        PackageParser.Package[] overlayArray =
5515            overlaySet.values().toArray(new PackageParser.Package[0]);
5516        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5517            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5518                return p1.mOverlayPriority - p2.mOverlayPriority;
5519            }
5520        };
5521        Arrays.sort(overlayArray, cmp);
5522
5523        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5524        int i = 0;
5525        for (PackageParser.Package p : overlayArray) {
5526            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5527        }
5528        return true;
5529    }
5530
5531    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5532        final File[] files = dir.listFiles();
5533        if (ArrayUtils.isEmpty(files)) {
5534            Log.d(TAG, "No files in app dir " + dir);
5535            return;
5536        }
5537
5538        if (DEBUG_PACKAGE_SCANNING) {
5539            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5540                    + " flags=0x" + Integer.toHexString(parseFlags));
5541        }
5542
5543        for (File file : files) {
5544            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5545                    && !PackageInstallerService.isStageName(file.getName());
5546            if (!isPackage) {
5547                // Ignore entries which are not packages
5548                continue;
5549            }
5550            try {
5551                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5552                        scanFlags, currentTime, null);
5553            } catch (PackageManagerException e) {
5554                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5555
5556                // Delete invalid userdata apps
5557                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5558                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5559                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5560                    if (file.isDirectory()) {
5561                        mInstaller.rmPackageDir(file.getAbsolutePath());
5562                    } else {
5563                        file.delete();
5564                    }
5565                }
5566            }
5567        }
5568    }
5569
5570    private static File getSettingsProblemFile() {
5571        File dataDir = Environment.getDataDirectory();
5572        File systemDir = new File(dataDir, "system");
5573        File fname = new File(systemDir, "uiderrors.txt");
5574        return fname;
5575    }
5576
5577    static void reportSettingsProblem(int priority, String msg) {
5578        logCriticalInfo(priority, msg);
5579    }
5580
5581    static void logCriticalInfo(int priority, String msg) {
5582        Slog.println(priority, TAG, msg);
5583        EventLogTags.writePmCriticalInfo(msg);
5584        try {
5585            File fname = getSettingsProblemFile();
5586            FileOutputStream out = new FileOutputStream(fname, true);
5587            PrintWriter pw = new FastPrintWriter(out);
5588            SimpleDateFormat formatter = new SimpleDateFormat();
5589            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5590            pw.println(dateString + ": " + msg);
5591            pw.close();
5592            FileUtils.setPermissions(
5593                    fname.toString(),
5594                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5595                    -1, -1);
5596        } catch (java.io.IOException e) {
5597        }
5598    }
5599
5600    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5601            PackageParser.Package pkg, File srcFile, int parseFlags)
5602            throws PackageManagerException {
5603        if (ps != null
5604                && ps.codePath.equals(srcFile)
5605                && ps.timeStamp == srcFile.lastModified()
5606                && !isCompatSignatureUpdateNeeded(pkg)
5607                && !isRecoverSignatureUpdateNeeded(pkg)) {
5608            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5609            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5610            ArraySet<PublicKey> signingKs;
5611            synchronized (mPackages) {
5612                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5613            }
5614            if (ps.signatures.mSignatures != null
5615                    && ps.signatures.mSignatures.length != 0
5616                    && signingKs != null) {
5617                // Optimization: reuse the existing cached certificates
5618                // if the package appears to be unchanged.
5619                pkg.mSignatures = ps.signatures.mSignatures;
5620                pkg.mSigningKeys = signingKs;
5621                return;
5622            }
5623
5624            Slog.w(TAG, "PackageSetting for " + ps.name
5625                    + " is missing signatures.  Collecting certs again to recover them.");
5626        } else {
5627            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5628        }
5629
5630        try {
5631            pp.collectCertificates(pkg, parseFlags);
5632            pp.collectManifestDigest(pkg);
5633        } catch (PackageParserException e) {
5634            throw PackageManagerException.from(e);
5635        }
5636    }
5637
5638    /*
5639     *  Scan a package and return the newly parsed package.
5640     *  Returns null in case of errors and the error code is stored in mLastScanError
5641     */
5642    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5643            long currentTime, UserHandle user) throws PackageManagerException {
5644        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5645        parseFlags |= mDefParseFlags;
5646        PackageParser pp = new PackageParser();
5647        pp.setSeparateProcesses(mSeparateProcesses);
5648        pp.setOnlyCoreApps(mOnlyCore);
5649        pp.setDisplayMetrics(mMetrics);
5650
5651        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5652            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5653        }
5654
5655        final PackageParser.Package pkg;
5656        try {
5657            pkg = pp.parsePackage(scanFile, parseFlags);
5658        } catch (PackageParserException e) {
5659            throw PackageManagerException.from(e);
5660        }
5661
5662        PackageSetting ps = null;
5663        PackageSetting updatedPkg;
5664        // reader
5665        synchronized (mPackages) {
5666            // Look to see if we already know about this package.
5667            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5668            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5669                // This package has been renamed to its original name.  Let's
5670                // use that.
5671                ps = mSettings.peekPackageLPr(oldName);
5672            }
5673            // If there was no original package, see one for the real package name.
5674            if (ps == null) {
5675                ps = mSettings.peekPackageLPr(pkg.packageName);
5676            }
5677            // Check to see if this package could be hiding/updating a system
5678            // package.  Must look for it either under the original or real
5679            // package name depending on our state.
5680            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5681            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5682        }
5683        boolean updatedPkgBetter = false;
5684        // First check if this is a system package that may involve an update
5685        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5686            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5687            // it needs to drop FLAG_PRIVILEGED.
5688            if (locationIsPrivileged(scanFile)) {
5689                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5690            } else {
5691                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5692            }
5693
5694            if (ps != null && !ps.codePath.equals(scanFile)) {
5695                // The path has changed from what was last scanned...  check the
5696                // version of the new path against what we have stored to determine
5697                // what to do.
5698                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5699                if (pkg.mVersionCode <= ps.versionCode) {
5700                    // The system package has been updated and the code path does not match
5701                    // Ignore entry. Skip it.
5702                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5703                            + " ignored: updated version " + ps.versionCode
5704                            + " better than this " + pkg.mVersionCode);
5705                    if (!updatedPkg.codePath.equals(scanFile)) {
5706                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5707                                + ps.name + " changing from " + updatedPkg.codePathString
5708                                + " to " + scanFile);
5709                        updatedPkg.codePath = scanFile;
5710                        updatedPkg.codePathString = scanFile.toString();
5711                        updatedPkg.resourcePath = scanFile;
5712                        updatedPkg.resourcePathString = scanFile.toString();
5713                    }
5714                    updatedPkg.pkg = pkg;
5715                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5716                            "Package " + ps.name + " at " + scanFile
5717                                    + " ignored: updated version " + ps.versionCode
5718                                    + " better than this " + pkg.mVersionCode);
5719                } else {
5720                    // The current app on the system partition is better than
5721                    // what we have updated to on the data partition; switch
5722                    // back to the system partition version.
5723                    // At this point, its safely assumed that package installation for
5724                    // apps in system partition will go through. If not there won't be a working
5725                    // version of the app
5726                    // writer
5727                    synchronized (mPackages) {
5728                        // Just remove the loaded entries from package lists.
5729                        mPackages.remove(ps.name);
5730                    }
5731
5732                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5733                            + " reverting from " + ps.codePathString
5734                            + ": new version " + pkg.mVersionCode
5735                            + " better than installed " + ps.versionCode);
5736
5737                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5738                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5739                    synchronized (mInstallLock) {
5740                        args.cleanUpResourcesLI();
5741                    }
5742                    synchronized (mPackages) {
5743                        mSettings.enableSystemPackageLPw(ps.name);
5744                    }
5745                    updatedPkgBetter = true;
5746                }
5747            }
5748        }
5749
5750        if (updatedPkg != null) {
5751            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5752            // initially
5753            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5754
5755            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5756            // flag set initially
5757            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5758                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5759            }
5760        }
5761
5762        // Verify certificates against what was last scanned
5763        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5764
5765        /*
5766         * A new system app appeared, but we already had a non-system one of the
5767         * same name installed earlier.
5768         */
5769        boolean shouldHideSystemApp = false;
5770        if (updatedPkg == null && ps != null
5771                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5772            /*
5773             * Check to make sure the signatures match first. If they don't,
5774             * wipe the installed application and its data.
5775             */
5776            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5777                    != PackageManager.SIGNATURE_MATCH) {
5778                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5779                        + " signatures don't match existing userdata copy; removing");
5780                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5781                ps = null;
5782            } else {
5783                /*
5784                 * If the newly-added system app is an older version than the
5785                 * already installed version, hide it. It will be scanned later
5786                 * and re-added like an update.
5787                 */
5788                if (pkg.mVersionCode <= ps.versionCode) {
5789                    shouldHideSystemApp = true;
5790                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5791                            + " but new version " + pkg.mVersionCode + " better than installed "
5792                            + ps.versionCode + "; hiding system");
5793                } else {
5794                    /*
5795                     * The newly found system app is a newer version that the
5796                     * one previously installed. Simply remove the
5797                     * already-installed application and replace it with our own
5798                     * while keeping the application data.
5799                     */
5800                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5801                            + " reverting from " + ps.codePathString + ": new version "
5802                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5803                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5804                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5805                    synchronized (mInstallLock) {
5806                        args.cleanUpResourcesLI();
5807                    }
5808                }
5809            }
5810        }
5811
5812        // The apk is forward locked (not public) if its code and resources
5813        // are kept in different files. (except for app in either system or
5814        // vendor path).
5815        // TODO grab this value from PackageSettings
5816        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5817            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5818                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5819            }
5820        }
5821
5822        // TODO: extend to support forward-locked splits
5823        String resourcePath = null;
5824        String baseResourcePath = null;
5825        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5826            if (ps != null && ps.resourcePathString != null) {
5827                resourcePath = ps.resourcePathString;
5828                baseResourcePath = ps.resourcePathString;
5829            } else {
5830                // Should not happen at all. Just log an error.
5831                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5832            }
5833        } else {
5834            resourcePath = pkg.codePath;
5835            baseResourcePath = pkg.baseCodePath;
5836        }
5837
5838        // Set application objects path explicitly.
5839        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5840        pkg.applicationInfo.setCodePath(pkg.codePath);
5841        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5842        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5843        pkg.applicationInfo.setResourcePath(resourcePath);
5844        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5845        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5846
5847        // Note that we invoke the following method only if we are about to unpack an application
5848        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5849                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5850
5851        /*
5852         * If the system app should be overridden by a previously installed
5853         * data, hide the system app now and let the /data/app scan pick it up
5854         * again.
5855         */
5856        if (shouldHideSystemApp) {
5857            synchronized (mPackages) {
5858                /*
5859                 * We have to grant systems permissions before we hide, because
5860                 * grantPermissions will assume the package update is trying to
5861                 * expand its permissions.
5862                 */
5863                grantPermissionsLPw(pkg, true, pkg.packageName);
5864                mSettings.disableSystemPackageLPw(pkg.packageName);
5865            }
5866        }
5867
5868        return scannedPkg;
5869    }
5870
5871    private static String fixProcessName(String defProcessName,
5872            String processName, int uid) {
5873        if (processName == null) {
5874            return defProcessName;
5875        }
5876        return processName;
5877    }
5878
5879    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5880            throws PackageManagerException {
5881        if (pkgSetting.signatures.mSignatures != null) {
5882            // Already existing package. Make sure signatures match
5883            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5884                    == PackageManager.SIGNATURE_MATCH;
5885            if (!match) {
5886                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5887                        == PackageManager.SIGNATURE_MATCH;
5888            }
5889            if (!match) {
5890                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5891                        == PackageManager.SIGNATURE_MATCH;
5892            }
5893            if (!match) {
5894                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5895                        + pkg.packageName + " signatures do not match the "
5896                        + "previously installed version; ignoring!");
5897            }
5898        }
5899
5900        // Check for shared user signatures
5901        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5902            // Already existing package. Make sure signatures match
5903            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5904                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5905            if (!match) {
5906                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5907                        == PackageManager.SIGNATURE_MATCH;
5908            }
5909            if (!match) {
5910                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5911                        == PackageManager.SIGNATURE_MATCH;
5912            }
5913            if (!match) {
5914                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5915                        "Package " + pkg.packageName
5916                        + " has no signatures that match those in shared user "
5917                        + pkgSetting.sharedUser.name + "; ignoring!");
5918            }
5919        }
5920    }
5921
5922    /**
5923     * Enforces that only the system UID or root's UID can call a method exposed
5924     * via Binder.
5925     *
5926     * @param message used as message if SecurityException is thrown
5927     * @throws SecurityException if the caller is not system or root
5928     */
5929    private static final void enforceSystemOrRoot(String message) {
5930        final int uid = Binder.getCallingUid();
5931        if (uid != Process.SYSTEM_UID && uid != 0) {
5932            throw new SecurityException(message);
5933        }
5934    }
5935
5936    @Override
5937    public void performBootDexOpt() {
5938        enforceSystemOrRoot("Only the system can request dexopt be performed");
5939
5940        // Before everything else, see whether we need to fstrim.
5941        try {
5942            IMountService ms = PackageHelper.getMountService();
5943            if (ms != null) {
5944                final boolean isUpgrade = isUpgrade();
5945                boolean doTrim = isUpgrade;
5946                if (doTrim) {
5947                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5948                } else {
5949                    final long interval = android.provider.Settings.Global.getLong(
5950                            mContext.getContentResolver(),
5951                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5952                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5953                    if (interval > 0) {
5954                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5955                        if (timeSinceLast > interval) {
5956                            doTrim = true;
5957                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5958                                    + "; running immediately");
5959                        }
5960                    }
5961                }
5962                if (doTrim) {
5963                    if (!isFirstBoot()) {
5964                        try {
5965                            ActivityManagerNative.getDefault().showBootMessage(
5966                                    mContext.getResources().getString(
5967                                            R.string.android_upgrading_fstrim), true);
5968                        } catch (RemoteException e) {
5969                        }
5970                    }
5971                    ms.runMaintenance();
5972                }
5973            } else {
5974                Slog.e(TAG, "Mount service unavailable!");
5975            }
5976        } catch (RemoteException e) {
5977            // Can't happen; MountService is local
5978        }
5979
5980        final ArraySet<PackageParser.Package> pkgs;
5981        synchronized (mPackages) {
5982            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5983        }
5984
5985        if (pkgs != null) {
5986            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5987            // in case the device runs out of space.
5988            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5989            // Give priority to core apps.
5990            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5991                PackageParser.Package pkg = it.next();
5992                if (pkg.coreApp) {
5993                    if (DEBUG_DEXOPT) {
5994                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5995                    }
5996                    sortedPkgs.add(pkg);
5997                    it.remove();
5998                }
5999            }
6000            // Give priority to system apps that listen for pre boot complete.
6001            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6002            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6003            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6004                PackageParser.Package pkg = it.next();
6005                if (pkgNames.contains(pkg.packageName)) {
6006                    if (DEBUG_DEXOPT) {
6007                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6008                    }
6009                    sortedPkgs.add(pkg);
6010                    it.remove();
6011                }
6012            }
6013            // Give priority to system apps.
6014            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6015                PackageParser.Package pkg = it.next();
6016                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6017                    if (DEBUG_DEXOPT) {
6018                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6019                    }
6020                    sortedPkgs.add(pkg);
6021                    it.remove();
6022                }
6023            }
6024            // Give priority to updated system apps.
6025            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6026                PackageParser.Package pkg = it.next();
6027                if (pkg.isUpdatedSystemApp()) {
6028                    if (DEBUG_DEXOPT) {
6029                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6030                    }
6031                    sortedPkgs.add(pkg);
6032                    it.remove();
6033                }
6034            }
6035            // Give priority to apps that listen for boot complete.
6036            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6037            pkgNames = getPackageNamesForIntent(intent);
6038            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6039                PackageParser.Package pkg = it.next();
6040                if (pkgNames.contains(pkg.packageName)) {
6041                    if (DEBUG_DEXOPT) {
6042                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6043                    }
6044                    sortedPkgs.add(pkg);
6045                    it.remove();
6046                }
6047            }
6048            // Filter out packages that aren't recently used.
6049            filterRecentlyUsedApps(pkgs);
6050            // Add all remaining apps.
6051            for (PackageParser.Package pkg : pkgs) {
6052                if (DEBUG_DEXOPT) {
6053                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6054                }
6055                sortedPkgs.add(pkg);
6056            }
6057
6058            // If we want to be lazy, filter everything that wasn't recently used.
6059            if (mLazyDexOpt) {
6060                filterRecentlyUsedApps(sortedPkgs);
6061            }
6062
6063            int i = 0;
6064            int total = sortedPkgs.size();
6065            File dataDir = Environment.getDataDirectory();
6066            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6067            if (lowThreshold == 0) {
6068                throw new IllegalStateException("Invalid low memory threshold");
6069            }
6070            for (PackageParser.Package pkg : sortedPkgs) {
6071                long usableSpace = dataDir.getUsableSpace();
6072                if (usableSpace < lowThreshold) {
6073                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6074                    break;
6075                }
6076                performBootDexOpt(pkg, ++i, total);
6077            }
6078        }
6079    }
6080
6081    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6082        // Filter out packages that aren't recently used.
6083        //
6084        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6085        // should do a full dexopt.
6086        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6087            int total = pkgs.size();
6088            int skipped = 0;
6089            long now = System.currentTimeMillis();
6090            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6091                PackageParser.Package pkg = i.next();
6092                long then = pkg.mLastPackageUsageTimeInMills;
6093                if (then + mDexOptLRUThresholdInMills < now) {
6094                    if (DEBUG_DEXOPT) {
6095                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6096                              ((then == 0) ? "never" : new Date(then)));
6097                    }
6098                    i.remove();
6099                    skipped++;
6100                }
6101            }
6102            if (DEBUG_DEXOPT) {
6103                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6104            }
6105        }
6106    }
6107
6108    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6109        List<ResolveInfo> ris = null;
6110        try {
6111            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6112                    intent, null, 0, UserHandle.USER_OWNER);
6113        } catch (RemoteException e) {
6114        }
6115        ArraySet<String> pkgNames = new ArraySet<String>();
6116        if (ris != null) {
6117            for (ResolveInfo ri : ris) {
6118                pkgNames.add(ri.activityInfo.packageName);
6119            }
6120        }
6121        return pkgNames;
6122    }
6123
6124    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6125        if (DEBUG_DEXOPT) {
6126            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6127        }
6128        if (!isFirstBoot()) {
6129            try {
6130                ActivityManagerNative.getDefault().showBootMessage(
6131                        mContext.getResources().getString(R.string.android_upgrading_apk,
6132                                curr, total), true);
6133            } catch (RemoteException e) {
6134            }
6135        }
6136        PackageParser.Package p = pkg;
6137        synchronized (mInstallLock) {
6138            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6139                    false /* force dex */, false /* defer */, true /* include dependencies */);
6140        }
6141    }
6142
6143    @Override
6144    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6145        return performDexOpt(packageName, instructionSet, false);
6146    }
6147
6148    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6149        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6150        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6151        if (!dexopt && !updateUsage) {
6152            // We aren't going to dexopt or update usage, so bail early.
6153            return false;
6154        }
6155        PackageParser.Package p;
6156        final String targetInstructionSet;
6157        synchronized (mPackages) {
6158            p = mPackages.get(packageName);
6159            if (p == null) {
6160                return false;
6161            }
6162            if (updateUsage) {
6163                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6164            }
6165            mPackageUsage.write(false);
6166            if (!dexopt) {
6167                // We aren't going to dexopt, so bail early.
6168                return false;
6169            }
6170
6171            targetInstructionSet = instructionSet != null ? instructionSet :
6172                    getPrimaryInstructionSet(p.applicationInfo);
6173            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6174                return false;
6175            }
6176        }
6177        long callingId = Binder.clearCallingIdentity();
6178        try {
6179            synchronized (mInstallLock) {
6180                final String[] instructionSets = new String[] { targetInstructionSet };
6181                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6182                        false /* forceDex */, false /* defer */, true /* inclDependencies */);
6183                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6184            }
6185        } finally {
6186            Binder.restoreCallingIdentity(callingId);
6187        }
6188    }
6189
6190    public ArraySet<String> getPackagesThatNeedDexOpt() {
6191        ArraySet<String> pkgs = null;
6192        synchronized (mPackages) {
6193            for (PackageParser.Package p : mPackages.values()) {
6194                if (DEBUG_DEXOPT) {
6195                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6196                }
6197                if (!p.mDexOptPerformed.isEmpty()) {
6198                    continue;
6199                }
6200                if (pkgs == null) {
6201                    pkgs = new ArraySet<String>();
6202                }
6203                pkgs.add(p.packageName);
6204            }
6205        }
6206        return pkgs;
6207    }
6208
6209    public void shutdown() {
6210        mPackageUsage.write(true);
6211    }
6212
6213    @Override
6214    public void forceDexOpt(String packageName) {
6215        enforceSystemOrRoot("forceDexOpt");
6216
6217        PackageParser.Package pkg;
6218        synchronized (mPackages) {
6219            pkg = mPackages.get(packageName);
6220            if (pkg == null) {
6221                throw new IllegalArgumentException("Missing package: " + packageName);
6222            }
6223        }
6224
6225        synchronized (mInstallLock) {
6226            final String[] instructionSets = new String[] {
6227                    getPrimaryInstructionSet(pkg.applicationInfo) };
6228            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6229                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6230            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6231                throw new IllegalStateException("Failed to dexopt: " + res);
6232            }
6233        }
6234    }
6235
6236    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6237        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6238            Slog.w(TAG, "Unable to update from " + oldPkg.name
6239                    + " to " + newPkg.packageName
6240                    + ": old package not in system partition");
6241            return false;
6242        } else if (mPackages.get(oldPkg.name) != null) {
6243            Slog.w(TAG, "Unable to update from " + oldPkg.name
6244                    + " to " + newPkg.packageName
6245                    + ": old package still exists");
6246            return false;
6247        }
6248        return true;
6249    }
6250
6251    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6252        int[] users = sUserManager.getUserIds();
6253        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6254        if (res < 0) {
6255            return res;
6256        }
6257        for (int user : users) {
6258            if (user != 0) {
6259                res = mInstaller.createUserData(volumeUuid, packageName,
6260                        UserHandle.getUid(user, uid), user, seinfo);
6261                if (res < 0) {
6262                    return res;
6263                }
6264            }
6265        }
6266        return res;
6267    }
6268
6269    private int removeDataDirsLI(String volumeUuid, String packageName) {
6270        int[] users = sUserManager.getUserIds();
6271        int res = 0;
6272        for (int user : users) {
6273            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6274            if (resInner < 0) {
6275                res = resInner;
6276            }
6277        }
6278
6279        return res;
6280    }
6281
6282    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6283        int[] users = sUserManager.getUserIds();
6284        int res = 0;
6285        for (int user : users) {
6286            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6287            if (resInner < 0) {
6288                res = resInner;
6289            }
6290        }
6291        return res;
6292    }
6293
6294    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6295            PackageParser.Package changingLib) {
6296        if (file.path != null) {
6297            usesLibraryFiles.add(file.path);
6298            return;
6299        }
6300        PackageParser.Package p = mPackages.get(file.apk);
6301        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6302            // If we are doing this while in the middle of updating a library apk,
6303            // then we need to make sure to use that new apk for determining the
6304            // dependencies here.  (We haven't yet finished committing the new apk
6305            // to the package manager state.)
6306            if (p == null || p.packageName.equals(changingLib.packageName)) {
6307                p = changingLib;
6308            }
6309        }
6310        if (p != null) {
6311            usesLibraryFiles.addAll(p.getAllCodePaths());
6312        }
6313    }
6314
6315    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6316            PackageParser.Package changingLib) throws PackageManagerException {
6317        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6318            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6319            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6320            for (int i=0; i<N; i++) {
6321                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6322                if (file == null) {
6323                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6324                            "Package " + pkg.packageName + " requires unavailable shared library "
6325                            + pkg.usesLibraries.get(i) + "; failing!");
6326                }
6327                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6328            }
6329            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6330            for (int i=0; i<N; i++) {
6331                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6332                if (file == null) {
6333                    Slog.w(TAG, "Package " + pkg.packageName
6334                            + " desires unavailable shared library "
6335                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6336                } else {
6337                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6338                }
6339            }
6340            N = usesLibraryFiles.size();
6341            if (N > 0) {
6342                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6343            } else {
6344                pkg.usesLibraryFiles = null;
6345            }
6346        }
6347    }
6348
6349    private static boolean hasString(List<String> list, List<String> which) {
6350        if (list == null) {
6351            return false;
6352        }
6353        for (int i=list.size()-1; i>=0; i--) {
6354            for (int j=which.size()-1; j>=0; j--) {
6355                if (which.get(j).equals(list.get(i))) {
6356                    return true;
6357                }
6358            }
6359        }
6360        return false;
6361    }
6362
6363    private void updateAllSharedLibrariesLPw() {
6364        for (PackageParser.Package pkg : mPackages.values()) {
6365            try {
6366                updateSharedLibrariesLPw(pkg, null);
6367            } catch (PackageManagerException e) {
6368                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6369            }
6370        }
6371    }
6372
6373    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6374            PackageParser.Package changingPkg) {
6375        ArrayList<PackageParser.Package> res = null;
6376        for (PackageParser.Package pkg : mPackages.values()) {
6377            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6378                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6379                if (res == null) {
6380                    res = new ArrayList<PackageParser.Package>();
6381                }
6382                res.add(pkg);
6383                try {
6384                    updateSharedLibrariesLPw(pkg, changingPkg);
6385                } catch (PackageManagerException e) {
6386                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6387                }
6388            }
6389        }
6390        return res;
6391    }
6392
6393    /**
6394     * Derive the value of the {@code cpuAbiOverride} based on the provided
6395     * value and an optional stored value from the package settings.
6396     */
6397    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6398        String cpuAbiOverride = null;
6399
6400        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6401            cpuAbiOverride = null;
6402        } else if (abiOverride != null) {
6403            cpuAbiOverride = abiOverride;
6404        } else if (settings != null) {
6405            cpuAbiOverride = settings.cpuAbiOverrideString;
6406        }
6407
6408        return cpuAbiOverride;
6409    }
6410
6411    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6412            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6413        boolean success = false;
6414        try {
6415            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6416                    currentTime, user);
6417            success = true;
6418            return res;
6419        } finally {
6420            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6421                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6422            }
6423        }
6424    }
6425
6426    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6427            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6428        final File scanFile = new File(pkg.codePath);
6429        if (pkg.applicationInfo.getCodePath() == null ||
6430                pkg.applicationInfo.getResourcePath() == null) {
6431            // Bail out. The resource and code paths haven't been set.
6432            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6433                    "Code and resource paths haven't been set correctly");
6434        }
6435
6436        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6437            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6438        } else {
6439            // Only allow system apps to be flagged as core apps.
6440            pkg.coreApp = false;
6441        }
6442
6443        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6444            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6445        }
6446
6447        if (mCustomResolverComponentName != null &&
6448                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6449            setUpCustomResolverActivity(pkg);
6450        }
6451
6452        if (pkg.packageName.equals("android")) {
6453            synchronized (mPackages) {
6454                if (mAndroidApplication != null) {
6455                    Slog.w(TAG, "*************************************************");
6456                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6457                    Slog.w(TAG, " file=" + scanFile);
6458                    Slog.w(TAG, "*************************************************");
6459                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6460                            "Core android package being redefined.  Skipping.");
6461                }
6462
6463                // Set up information for our fall-back user intent resolution activity.
6464                mPlatformPackage = pkg;
6465                pkg.mVersionCode = mSdkVersion;
6466                mAndroidApplication = pkg.applicationInfo;
6467
6468                if (!mResolverReplaced) {
6469                    mResolveActivity.applicationInfo = mAndroidApplication;
6470                    mResolveActivity.name = ResolverActivity.class.getName();
6471                    mResolveActivity.packageName = mAndroidApplication.packageName;
6472                    mResolveActivity.processName = "system:ui";
6473                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6474                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6475                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6476                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6477                    mResolveActivity.exported = true;
6478                    mResolveActivity.enabled = true;
6479                    mResolveInfo.activityInfo = mResolveActivity;
6480                    mResolveInfo.priority = 0;
6481                    mResolveInfo.preferredOrder = 0;
6482                    mResolveInfo.match = 0;
6483                    mResolveComponentName = new ComponentName(
6484                            mAndroidApplication.packageName, mResolveActivity.name);
6485                }
6486            }
6487        }
6488
6489        if (DEBUG_PACKAGE_SCANNING) {
6490            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6491                Log.d(TAG, "Scanning package " + pkg.packageName);
6492        }
6493
6494        if (mPackages.containsKey(pkg.packageName)
6495                || mSharedLibraries.containsKey(pkg.packageName)) {
6496            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6497                    "Application package " + pkg.packageName
6498                    + " already installed.  Skipping duplicate.");
6499        }
6500
6501        // If we're only installing presumed-existing packages, require that the
6502        // scanned APK is both already known and at the path previously established
6503        // for it.  Previously unknown packages we pick up normally, but if we have an
6504        // a priori expectation about this package's install presence, enforce it.
6505        // With a singular exception for new system packages. When an OTA contains
6506        // a new system package, we allow the codepath to change from a system location
6507        // to the user-installed location. If we don't allow this change, any newer,
6508        // user-installed version of the application will be ignored.
6509        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6510            if (mExpectingBetter.containsKey(pkg.packageName)) {
6511                logCriticalInfo(Log.WARN,
6512                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6513            } else {
6514                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6515                if (known != null) {
6516                    if (DEBUG_PACKAGE_SCANNING) {
6517                        Log.d(TAG, "Examining " + pkg.codePath
6518                                + " and requiring known paths " + known.codePathString
6519                                + " & " + known.resourcePathString);
6520                    }
6521                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6522                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6523                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6524                                "Application package " + pkg.packageName
6525                                + " found at " + pkg.applicationInfo.getCodePath()
6526                                + " but expected at " + known.codePathString + "; ignoring.");
6527                    }
6528                }
6529            }
6530        }
6531
6532        // Initialize package source and resource directories
6533        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6534        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6535
6536        SharedUserSetting suid = null;
6537        PackageSetting pkgSetting = null;
6538
6539        if (!isSystemApp(pkg)) {
6540            // Only system apps can use these features.
6541            pkg.mOriginalPackages = null;
6542            pkg.mRealPackage = null;
6543            pkg.mAdoptPermissions = null;
6544        }
6545
6546        // writer
6547        synchronized (mPackages) {
6548            if (pkg.mSharedUserId != null) {
6549                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6550                if (suid == null) {
6551                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6552                            "Creating application package " + pkg.packageName
6553                            + " for shared user failed");
6554                }
6555                if (DEBUG_PACKAGE_SCANNING) {
6556                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6557                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6558                                + "): packages=" + suid.packages);
6559                }
6560            }
6561
6562            // Check if we are renaming from an original package name.
6563            PackageSetting origPackage = null;
6564            String realName = null;
6565            if (pkg.mOriginalPackages != null) {
6566                // This package may need to be renamed to a previously
6567                // installed name.  Let's check on that...
6568                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6569                if (pkg.mOriginalPackages.contains(renamed)) {
6570                    // This package had originally been installed as the
6571                    // original name, and we have already taken care of
6572                    // transitioning to the new one.  Just update the new
6573                    // one to continue using the old name.
6574                    realName = pkg.mRealPackage;
6575                    if (!pkg.packageName.equals(renamed)) {
6576                        // Callers into this function may have already taken
6577                        // care of renaming the package; only do it here if
6578                        // it is not already done.
6579                        pkg.setPackageName(renamed);
6580                    }
6581
6582                } else {
6583                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6584                        if ((origPackage = mSettings.peekPackageLPr(
6585                                pkg.mOriginalPackages.get(i))) != null) {
6586                            // We do have the package already installed under its
6587                            // original name...  should we use it?
6588                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6589                                // New package is not compatible with original.
6590                                origPackage = null;
6591                                continue;
6592                            } else if (origPackage.sharedUser != null) {
6593                                // Make sure uid is compatible between packages.
6594                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6595                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6596                                            + " to " + pkg.packageName + ": old uid "
6597                                            + origPackage.sharedUser.name
6598                                            + " differs from " + pkg.mSharedUserId);
6599                                    origPackage = null;
6600                                    continue;
6601                                }
6602                            } else {
6603                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6604                                        + pkg.packageName + " to old name " + origPackage.name);
6605                            }
6606                            break;
6607                        }
6608                    }
6609                }
6610            }
6611
6612            if (mTransferedPackages.contains(pkg.packageName)) {
6613                Slog.w(TAG, "Package " + pkg.packageName
6614                        + " was transferred to another, but its .apk remains");
6615            }
6616
6617            // Just create the setting, don't add it yet. For already existing packages
6618            // the PkgSetting exists already and doesn't have to be created.
6619            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6620                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6621                    pkg.applicationInfo.primaryCpuAbi,
6622                    pkg.applicationInfo.secondaryCpuAbi,
6623                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6624                    user, false);
6625            if (pkgSetting == null) {
6626                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6627                        "Creating application package " + pkg.packageName + " failed");
6628            }
6629
6630            if (pkgSetting.origPackage != null) {
6631                // If we are first transitioning from an original package,
6632                // fix up the new package's name now.  We need to do this after
6633                // looking up the package under its new name, so getPackageLP
6634                // can take care of fiddling things correctly.
6635                pkg.setPackageName(origPackage.name);
6636
6637                // File a report about this.
6638                String msg = "New package " + pkgSetting.realName
6639                        + " renamed to replace old package " + pkgSetting.name;
6640                reportSettingsProblem(Log.WARN, msg);
6641
6642                // Make a note of it.
6643                mTransferedPackages.add(origPackage.name);
6644
6645                // No longer need to retain this.
6646                pkgSetting.origPackage = null;
6647            }
6648
6649            if (realName != null) {
6650                // Make a note of it.
6651                mTransferedPackages.add(pkg.packageName);
6652            }
6653
6654            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6655                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6656            }
6657
6658            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6659                // Check all shared libraries and map to their actual file path.
6660                // We only do this here for apps not on a system dir, because those
6661                // are the only ones that can fail an install due to this.  We
6662                // will take care of the system apps by updating all of their
6663                // library paths after the scan is done.
6664                updateSharedLibrariesLPw(pkg, null);
6665            }
6666
6667            if (mFoundPolicyFile) {
6668                SELinuxMMAC.assignSeinfoValue(pkg);
6669            }
6670
6671            pkg.applicationInfo.uid = pkgSetting.appId;
6672            pkg.mExtras = pkgSetting;
6673            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6674                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6675                    // We just determined the app is signed correctly, so bring
6676                    // over the latest parsed certs.
6677                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6678                } else {
6679                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6680                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6681                                "Package " + pkg.packageName + " upgrade keys do not match the "
6682                                + "previously installed version");
6683                    } else {
6684                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6685                        String msg = "System package " + pkg.packageName
6686                            + " signature changed; retaining data.";
6687                        reportSettingsProblem(Log.WARN, msg);
6688                    }
6689                }
6690            } else {
6691                try {
6692                    verifySignaturesLP(pkgSetting, pkg);
6693                    // We just determined the app is signed correctly, so bring
6694                    // over the latest parsed certs.
6695                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6696                } catch (PackageManagerException e) {
6697                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6698                        throw e;
6699                    }
6700                    // The signature has changed, but this package is in the system
6701                    // image...  let's recover!
6702                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6703                    // However...  if this package is part of a shared user, but it
6704                    // doesn't match the signature of the shared user, let's fail.
6705                    // What this means is that you can't change the signatures
6706                    // associated with an overall shared user, which doesn't seem all
6707                    // that unreasonable.
6708                    if (pkgSetting.sharedUser != null) {
6709                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6710                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6711                            throw new PackageManagerException(
6712                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6713                                            "Signature mismatch for shared user : "
6714                                            + pkgSetting.sharedUser);
6715                        }
6716                    }
6717                    // File a report about this.
6718                    String msg = "System package " + pkg.packageName
6719                        + " signature changed; retaining data.";
6720                    reportSettingsProblem(Log.WARN, msg);
6721                }
6722            }
6723            // Verify that this new package doesn't have any content providers
6724            // that conflict with existing packages.  Only do this if the
6725            // package isn't already installed, since we don't want to break
6726            // things that are installed.
6727            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6728                final int N = pkg.providers.size();
6729                int i;
6730                for (i=0; i<N; i++) {
6731                    PackageParser.Provider p = pkg.providers.get(i);
6732                    if (p.info.authority != null) {
6733                        String names[] = p.info.authority.split(";");
6734                        for (int j = 0; j < names.length; j++) {
6735                            if (mProvidersByAuthority.containsKey(names[j])) {
6736                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6737                                final String otherPackageName =
6738                                        ((other != null && other.getComponentName() != null) ?
6739                                                other.getComponentName().getPackageName() : "?");
6740                                throw new PackageManagerException(
6741                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6742                                                "Can't install because provider name " + names[j]
6743                                                + " (in package " + pkg.applicationInfo.packageName
6744                                                + ") is already used by " + otherPackageName);
6745                            }
6746                        }
6747                    }
6748                }
6749            }
6750
6751            if (pkg.mAdoptPermissions != null) {
6752                // This package wants to adopt ownership of permissions from
6753                // another package.
6754                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6755                    final String origName = pkg.mAdoptPermissions.get(i);
6756                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6757                    if (orig != null) {
6758                        if (verifyPackageUpdateLPr(orig, pkg)) {
6759                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6760                                    + pkg.packageName);
6761                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6762                        }
6763                    }
6764                }
6765            }
6766        }
6767
6768        final String pkgName = pkg.packageName;
6769
6770        final long scanFileTime = scanFile.lastModified();
6771        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6772        pkg.applicationInfo.processName = fixProcessName(
6773                pkg.applicationInfo.packageName,
6774                pkg.applicationInfo.processName,
6775                pkg.applicationInfo.uid);
6776
6777        File dataPath;
6778        if (mPlatformPackage == pkg) {
6779            // The system package is special.
6780            dataPath = new File(Environment.getDataDirectory(), "system");
6781
6782            pkg.applicationInfo.dataDir = dataPath.getPath();
6783
6784        } else {
6785            // This is a normal package, need to make its data directory.
6786            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6787                    UserHandle.USER_OWNER, pkg.packageName);
6788
6789            boolean uidError = false;
6790            if (dataPath.exists()) {
6791                int currentUid = 0;
6792                try {
6793                    StructStat stat = Os.stat(dataPath.getPath());
6794                    currentUid = stat.st_uid;
6795                } catch (ErrnoException e) {
6796                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6797                }
6798
6799                // If we have mismatched owners for the data path, we have a problem.
6800                if (currentUid != pkg.applicationInfo.uid) {
6801                    boolean recovered = false;
6802                    if (currentUid == 0) {
6803                        // The directory somehow became owned by root.  Wow.
6804                        // This is probably because the system was stopped while
6805                        // installd was in the middle of messing with its libs
6806                        // directory.  Ask installd to fix that.
6807                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6808                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6809                        if (ret >= 0) {
6810                            recovered = true;
6811                            String msg = "Package " + pkg.packageName
6812                                    + " unexpectedly changed to uid 0; recovered to " +
6813                                    + pkg.applicationInfo.uid;
6814                            reportSettingsProblem(Log.WARN, msg);
6815                        }
6816                    }
6817                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6818                            || (scanFlags&SCAN_BOOTING) != 0)) {
6819                        // If this is a system app, we can at least delete its
6820                        // current data so the application will still work.
6821                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6822                        if (ret >= 0) {
6823                            // TODO: Kill the processes first
6824                            // Old data gone!
6825                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6826                                    ? "System package " : "Third party package ";
6827                            String msg = prefix + pkg.packageName
6828                                    + " has changed from uid: "
6829                                    + currentUid + " to "
6830                                    + pkg.applicationInfo.uid + "; old data erased";
6831                            reportSettingsProblem(Log.WARN, msg);
6832                            recovered = true;
6833
6834                            // And now re-install the app.
6835                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6836                                    pkg.applicationInfo.seinfo);
6837                            if (ret == -1) {
6838                                // Ack should not happen!
6839                                msg = prefix + pkg.packageName
6840                                        + " could not have data directory re-created after delete.";
6841                                reportSettingsProblem(Log.WARN, msg);
6842                                throw new PackageManagerException(
6843                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6844                            }
6845                        }
6846                        if (!recovered) {
6847                            mHasSystemUidErrors = true;
6848                        }
6849                    } else if (!recovered) {
6850                        // If we allow this install to proceed, we will be broken.
6851                        // Abort, abort!
6852                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6853                                "scanPackageLI");
6854                    }
6855                    if (!recovered) {
6856                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6857                            + pkg.applicationInfo.uid + "/fs_"
6858                            + currentUid;
6859                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6860                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6861                        String msg = "Package " + pkg.packageName
6862                                + " has mismatched uid: "
6863                                + currentUid + " on disk, "
6864                                + pkg.applicationInfo.uid + " in settings";
6865                        // writer
6866                        synchronized (mPackages) {
6867                            mSettings.mReadMessages.append(msg);
6868                            mSettings.mReadMessages.append('\n');
6869                            uidError = true;
6870                            if (!pkgSetting.uidError) {
6871                                reportSettingsProblem(Log.ERROR, msg);
6872                            }
6873                        }
6874                    }
6875                }
6876                pkg.applicationInfo.dataDir = dataPath.getPath();
6877                if (mShouldRestoreconData) {
6878                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6879                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6880                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6881                }
6882            } else {
6883                if (DEBUG_PACKAGE_SCANNING) {
6884                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6885                        Log.v(TAG, "Want this data dir: " + dataPath);
6886                }
6887                //invoke installer to do the actual installation
6888                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6889                        pkg.applicationInfo.seinfo);
6890                if (ret < 0) {
6891                    // Error from installer
6892                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6893                            "Unable to create data dirs [errorCode=" + ret + "]");
6894                }
6895
6896                if (dataPath.exists()) {
6897                    pkg.applicationInfo.dataDir = dataPath.getPath();
6898                } else {
6899                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6900                    pkg.applicationInfo.dataDir = null;
6901                }
6902            }
6903
6904            pkgSetting.uidError = uidError;
6905        }
6906
6907        final String path = scanFile.getPath();
6908        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6909
6910        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6911            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6912
6913            // Some system apps still use directory structure for native libraries
6914            // in which case we might end up not detecting abi solely based on apk
6915            // structure. Try to detect abi based on directory structure.
6916            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6917                    pkg.applicationInfo.primaryCpuAbi == null) {
6918                setBundledAppAbisAndRoots(pkg, pkgSetting);
6919                setNativeLibraryPaths(pkg);
6920            }
6921
6922        } else {
6923            if ((scanFlags & SCAN_MOVE) != 0) {
6924                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6925                // but we already have this packages package info in the PackageSetting. We just
6926                // use that and derive the native library path based on the new codepath.
6927                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6928                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6929            }
6930
6931            // Set native library paths again. For moves, the path will be updated based on the
6932            // ABIs we've determined above. For non-moves, the path will be updated based on the
6933            // ABIs we determined during compilation, but the path will depend on the final
6934            // package path (after the rename away from the stage path).
6935            setNativeLibraryPaths(pkg);
6936        }
6937
6938        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6939        final int[] userIds = sUserManager.getUserIds();
6940        synchronized (mInstallLock) {
6941            // Make sure all user data directories are ready to roll; we're okay
6942            // if they already exist
6943            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6944                for (int userId : userIds) {
6945                    if (userId != 0) {
6946                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6947                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6948                                pkg.applicationInfo.seinfo);
6949                    }
6950                }
6951            }
6952
6953            // Create a native library symlink only if we have native libraries
6954            // and if the native libraries are 32 bit libraries. We do not provide
6955            // this symlink for 64 bit libraries.
6956            if (pkg.applicationInfo.primaryCpuAbi != null &&
6957                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6958                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6959                for (int userId : userIds) {
6960                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6961                            nativeLibPath, userId) < 0) {
6962                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6963                                "Failed linking native library dir (user=" + userId + ")");
6964                    }
6965                }
6966            }
6967        }
6968
6969        // This is a special case for the "system" package, where the ABI is
6970        // dictated by the zygote configuration (and init.rc). We should keep track
6971        // of this ABI so that we can deal with "normal" applications that run under
6972        // the same UID correctly.
6973        if (mPlatformPackage == pkg) {
6974            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6975                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6976        }
6977
6978        // If there's a mismatch between the abi-override in the package setting
6979        // and the abiOverride specified for the install. Warn about this because we
6980        // would've already compiled the app without taking the package setting into
6981        // account.
6982        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6983            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6984                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6985                        " for package: " + pkg.packageName);
6986            }
6987        }
6988
6989        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6990        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6991        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6992
6993        // Copy the derived override back to the parsed package, so that we can
6994        // update the package settings accordingly.
6995        pkg.cpuAbiOverride = cpuAbiOverride;
6996
6997        if (DEBUG_ABI_SELECTION) {
6998            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6999                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7000                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7001        }
7002
7003        // Push the derived path down into PackageSettings so we know what to
7004        // clean up at uninstall time.
7005        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7006
7007        if (DEBUG_ABI_SELECTION) {
7008            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7009                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7010                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7011        }
7012
7013        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7014            // We don't do this here during boot because we can do it all
7015            // at once after scanning all existing packages.
7016            //
7017            // We also do this *before* we perform dexopt on this package, so that
7018            // we can avoid redundant dexopts, and also to make sure we've got the
7019            // code and package path correct.
7020            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7021                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
7022        }
7023
7024        if ((scanFlags & SCAN_NO_DEX) == 0) {
7025            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7026                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
7027            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7028                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7029            }
7030        }
7031        if (mFactoryTest && pkg.requestedPermissions.contains(
7032                android.Manifest.permission.FACTORY_TEST)) {
7033            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7034        }
7035
7036        ArrayList<PackageParser.Package> clientLibPkgs = null;
7037
7038        // writer
7039        synchronized (mPackages) {
7040            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7041                // Only system apps can add new shared libraries.
7042                if (pkg.libraryNames != null) {
7043                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7044                        String name = pkg.libraryNames.get(i);
7045                        boolean allowed = false;
7046                        if (pkg.isUpdatedSystemApp()) {
7047                            // New library entries can only be added through the
7048                            // system image.  This is important to get rid of a lot
7049                            // of nasty edge cases: for example if we allowed a non-
7050                            // system update of the app to add a library, then uninstalling
7051                            // the update would make the library go away, and assumptions
7052                            // we made such as through app install filtering would now
7053                            // have allowed apps on the device which aren't compatible
7054                            // with it.  Better to just have the restriction here, be
7055                            // conservative, and create many fewer cases that can negatively
7056                            // impact the user experience.
7057                            final PackageSetting sysPs = mSettings
7058                                    .getDisabledSystemPkgLPr(pkg.packageName);
7059                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7060                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7061                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7062                                        allowed = true;
7063                                        allowed = true;
7064                                        break;
7065                                    }
7066                                }
7067                            }
7068                        } else {
7069                            allowed = true;
7070                        }
7071                        if (allowed) {
7072                            if (!mSharedLibraries.containsKey(name)) {
7073                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7074                            } else if (!name.equals(pkg.packageName)) {
7075                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7076                                        + name + " already exists; skipping");
7077                            }
7078                        } else {
7079                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7080                                    + name + " that is not declared on system image; skipping");
7081                        }
7082                    }
7083                    if ((scanFlags&SCAN_BOOTING) == 0) {
7084                        // If we are not booting, we need to update any applications
7085                        // that are clients of our shared library.  If we are booting,
7086                        // this will all be done once the scan is complete.
7087                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7088                    }
7089                }
7090            }
7091        }
7092
7093        // We also need to dexopt any apps that are dependent on this library.  Note that
7094        // if these fail, we should abort the install since installing the library will
7095        // result in some apps being broken.
7096        if (clientLibPkgs != null) {
7097            if ((scanFlags & SCAN_NO_DEX) == 0) {
7098                for (int i = 0; i < clientLibPkgs.size(); i++) {
7099                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7100                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7101                            null /* instruction sets */, forceDex,
7102                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7103                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7104                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7105                                "scanPackageLI failed to dexopt clientLibPkgs");
7106                    }
7107                }
7108            }
7109        }
7110
7111        // Also need to kill any apps that are dependent on the library.
7112        if (clientLibPkgs != null) {
7113            for (int i=0; i<clientLibPkgs.size(); i++) {
7114                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7115                killApplication(clientPkg.applicationInfo.packageName,
7116                        clientPkg.applicationInfo.uid, "update lib");
7117            }
7118        }
7119
7120        // Make sure we're not adding any bogus keyset info
7121        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7122        ksms.assertScannedPackageValid(pkg);
7123
7124        // writer
7125        synchronized (mPackages) {
7126            // We don't expect installation to fail beyond this point
7127
7128            // Add the new setting to mSettings
7129            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7130            // Add the new setting to mPackages
7131            mPackages.put(pkg.applicationInfo.packageName, pkg);
7132            // Make sure we don't accidentally delete its data.
7133            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7134            while (iter.hasNext()) {
7135                PackageCleanItem item = iter.next();
7136                if (pkgName.equals(item.packageName)) {
7137                    iter.remove();
7138                }
7139            }
7140
7141            // Take care of first install / last update times.
7142            if (currentTime != 0) {
7143                if (pkgSetting.firstInstallTime == 0) {
7144                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7145                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7146                    pkgSetting.lastUpdateTime = currentTime;
7147                }
7148            } else if (pkgSetting.firstInstallTime == 0) {
7149                // We need *something*.  Take time time stamp of the file.
7150                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7151            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7152                if (scanFileTime != pkgSetting.timeStamp) {
7153                    // A package on the system image has changed; consider this
7154                    // to be an update.
7155                    pkgSetting.lastUpdateTime = scanFileTime;
7156                }
7157            }
7158
7159            // Add the package's KeySets to the global KeySetManagerService
7160            ksms.addScannedPackageLPw(pkg);
7161
7162            int N = pkg.providers.size();
7163            StringBuilder r = null;
7164            int i;
7165            for (i=0; i<N; i++) {
7166                PackageParser.Provider p = pkg.providers.get(i);
7167                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7168                        p.info.processName, pkg.applicationInfo.uid);
7169                mProviders.addProvider(p);
7170                p.syncable = p.info.isSyncable;
7171                if (p.info.authority != null) {
7172                    String names[] = p.info.authority.split(";");
7173                    p.info.authority = null;
7174                    for (int j = 0; j < names.length; j++) {
7175                        if (j == 1 && p.syncable) {
7176                            // We only want the first authority for a provider to possibly be
7177                            // syncable, so if we already added this provider using a different
7178                            // authority clear the syncable flag. We copy the provider before
7179                            // changing it because the mProviders object contains a reference
7180                            // to a provider that we don't want to change.
7181                            // Only do this for the second authority since the resulting provider
7182                            // object can be the same for all future authorities for this provider.
7183                            p = new PackageParser.Provider(p);
7184                            p.syncable = false;
7185                        }
7186                        if (!mProvidersByAuthority.containsKey(names[j])) {
7187                            mProvidersByAuthority.put(names[j], p);
7188                            if (p.info.authority == null) {
7189                                p.info.authority = names[j];
7190                            } else {
7191                                p.info.authority = p.info.authority + ";" + names[j];
7192                            }
7193                            if (DEBUG_PACKAGE_SCANNING) {
7194                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7195                                    Log.d(TAG, "Registered content provider: " + names[j]
7196                                            + ", className = " + p.info.name + ", isSyncable = "
7197                                            + p.info.isSyncable);
7198                            }
7199                        } else {
7200                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7201                            Slog.w(TAG, "Skipping provider name " + names[j] +
7202                                    " (in package " + pkg.applicationInfo.packageName +
7203                                    "): name already used by "
7204                                    + ((other != null && other.getComponentName() != null)
7205                                            ? other.getComponentName().getPackageName() : "?"));
7206                        }
7207                    }
7208                }
7209                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7210                    if (r == null) {
7211                        r = new StringBuilder(256);
7212                    } else {
7213                        r.append(' ');
7214                    }
7215                    r.append(p.info.name);
7216                }
7217            }
7218            if (r != null) {
7219                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7220            }
7221
7222            N = pkg.services.size();
7223            r = null;
7224            for (i=0; i<N; i++) {
7225                PackageParser.Service s = pkg.services.get(i);
7226                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7227                        s.info.processName, pkg.applicationInfo.uid);
7228                mServices.addService(s);
7229                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7230                    if (r == null) {
7231                        r = new StringBuilder(256);
7232                    } else {
7233                        r.append(' ');
7234                    }
7235                    r.append(s.info.name);
7236                }
7237            }
7238            if (r != null) {
7239                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7240            }
7241
7242            N = pkg.receivers.size();
7243            r = null;
7244            for (i=0; i<N; i++) {
7245                PackageParser.Activity a = pkg.receivers.get(i);
7246                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7247                        a.info.processName, pkg.applicationInfo.uid);
7248                mReceivers.addActivity(a, "receiver");
7249                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7250                    if (r == null) {
7251                        r = new StringBuilder(256);
7252                    } else {
7253                        r.append(' ');
7254                    }
7255                    r.append(a.info.name);
7256                }
7257            }
7258            if (r != null) {
7259                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7260            }
7261
7262            N = pkg.activities.size();
7263            r = null;
7264            for (i=0; i<N; i++) {
7265                PackageParser.Activity a = pkg.activities.get(i);
7266                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7267                        a.info.processName, pkg.applicationInfo.uid);
7268                mActivities.addActivity(a, "activity");
7269                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7270                    if (r == null) {
7271                        r = new StringBuilder(256);
7272                    } else {
7273                        r.append(' ');
7274                    }
7275                    r.append(a.info.name);
7276                }
7277            }
7278            if (r != null) {
7279                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7280            }
7281
7282            N = pkg.permissionGroups.size();
7283            r = null;
7284            for (i=0; i<N; i++) {
7285                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7286                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7287                if (cur == null) {
7288                    mPermissionGroups.put(pg.info.name, pg);
7289                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7290                        if (r == null) {
7291                            r = new StringBuilder(256);
7292                        } else {
7293                            r.append(' ');
7294                        }
7295                        r.append(pg.info.name);
7296                    }
7297                } else {
7298                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7299                            + pg.info.packageName + " ignored: original from "
7300                            + cur.info.packageName);
7301                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7302                        if (r == null) {
7303                            r = new StringBuilder(256);
7304                        } else {
7305                            r.append(' ');
7306                        }
7307                        r.append("DUP:");
7308                        r.append(pg.info.name);
7309                    }
7310                }
7311            }
7312            if (r != null) {
7313                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7314            }
7315
7316            N = pkg.permissions.size();
7317            r = null;
7318            for (i=0; i<N; i++) {
7319                PackageParser.Permission p = pkg.permissions.get(i);
7320
7321                // Now that permission groups have a special meaning, we ignore permission
7322                // groups for legacy apps to prevent unexpected behavior. In particular,
7323                // permissions for one app being granted to someone just becuase they happen
7324                // to be in a group defined by another app (before this had no implications).
7325                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7326                    p.group = mPermissionGroups.get(p.info.group);
7327                    // Warn for a permission in an unknown group.
7328                    if (p.info.group != null && p.group == null) {
7329                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7330                                + p.info.packageName + " in an unknown group " + p.info.group);
7331                    }
7332                }
7333
7334                ArrayMap<String, BasePermission> permissionMap =
7335                        p.tree ? mSettings.mPermissionTrees
7336                                : mSettings.mPermissions;
7337                BasePermission bp = permissionMap.get(p.info.name);
7338
7339                // Allow system apps to redefine non-system permissions
7340                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7341                    final boolean currentOwnerIsSystem = (bp.perm != null
7342                            && isSystemApp(bp.perm.owner));
7343                    if (isSystemApp(p.owner)) {
7344                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7345                            // It's a built-in permission and no owner, take ownership now
7346                            bp.packageSetting = pkgSetting;
7347                            bp.perm = p;
7348                            bp.uid = pkg.applicationInfo.uid;
7349                            bp.sourcePackage = p.info.packageName;
7350                        } else if (!currentOwnerIsSystem) {
7351                            String msg = "New decl " + p.owner + " of permission  "
7352                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7353                            reportSettingsProblem(Log.WARN, msg);
7354                            bp = null;
7355                        }
7356                    }
7357                }
7358
7359                if (bp == null) {
7360                    bp = new BasePermission(p.info.name, p.info.packageName,
7361                            BasePermission.TYPE_NORMAL);
7362                    permissionMap.put(p.info.name, bp);
7363                }
7364
7365                if (bp.perm == null) {
7366                    if (bp.sourcePackage == null
7367                            || bp.sourcePackage.equals(p.info.packageName)) {
7368                        BasePermission tree = findPermissionTreeLP(p.info.name);
7369                        if (tree == null
7370                                || tree.sourcePackage.equals(p.info.packageName)) {
7371                            bp.packageSetting = pkgSetting;
7372                            bp.perm = p;
7373                            bp.uid = pkg.applicationInfo.uid;
7374                            bp.sourcePackage = p.info.packageName;
7375                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7376                                if (r == null) {
7377                                    r = new StringBuilder(256);
7378                                } else {
7379                                    r.append(' ');
7380                                }
7381                                r.append(p.info.name);
7382                            }
7383                        } else {
7384                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7385                                    + p.info.packageName + " ignored: base tree "
7386                                    + tree.name + " is from package "
7387                                    + tree.sourcePackage);
7388                        }
7389                    } else {
7390                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7391                                + p.info.packageName + " ignored: original from "
7392                                + bp.sourcePackage);
7393                    }
7394                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7395                    if (r == null) {
7396                        r = new StringBuilder(256);
7397                    } else {
7398                        r.append(' ');
7399                    }
7400                    r.append("DUP:");
7401                    r.append(p.info.name);
7402                }
7403                if (bp.perm == p) {
7404                    bp.protectionLevel = p.info.protectionLevel;
7405                }
7406            }
7407
7408            if (r != null) {
7409                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7410            }
7411
7412            N = pkg.instrumentation.size();
7413            r = null;
7414            for (i=0; i<N; i++) {
7415                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7416                a.info.packageName = pkg.applicationInfo.packageName;
7417                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7418                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7419                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7420                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7421                a.info.dataDir = pkg.applicationInfo.dataDir;
7422
7423                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7424                // need other information about the application, like the ABI and what not ?
7425                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7426                mInstrumentation.put(a.getComponentName(), a);
7427                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7428                    if (r == null) {
7429                        r = new StringBuilder(256);
7430                    } else {
7431                        r.append(' ');
7432                    }
7433                    r.append(a.info.name);
7434                }
7435            }
7436            if (r != null) {
7437                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7438            }
7439
7440            if (pkg.protectedBroadcasts != null) {
7441                N = pkg.protectedBroadcasts.size();
7442                for (i=0; i<N; i++) {
7443                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7444                }
7445            }
7446
7447            pkgSetting.setTimeStamp(scanFileTime);
7448
7449            // Create idmap files for pairs of (packages, overlay packages).
7450            // Note: "android", ie framework-res.apk, is handled by native layers.
7451            if (pkg.mOverlayTarget != null) {
7452                // This is an overlay package.
7453                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7454                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7455                        mOverlays.put(pkg.mOverlayTarget,
7456                                new ArrayMap<String, PackageParser.Package>());
7457                    }
7458                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7459                    map.put(pkg.packageName, pkg);
7460                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7461                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7462                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7463                                "scanPackageLI failed to createIdmap");
7464                    }
7465                }
7466            } else if (mOverlays.containsKey(pkg.packageName) &&
7467                    !pkg.packageName.equals("android")) {
7468                // This is a regular package, with one or more known overlay packages.
7469                createIdmapsForPackageLI(pkg);
7470            }
7471        }
7472
7473        return pkg;
7474    }
7475
7476    /**
7477     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7478     * is derived purely on the basis of the contents of {@code scanFile} and
7479     * {@code cpuAbiOverride}.
7480     *
7481     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7482     */
7483    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7484                                 String cpuAbiOverride, boolean extractLibs)
7485            throws PackageManagerException {
7486        // TODO: We can probably be smarter about this stuff. For installed apps,
7487        // we can calculate this information at install time once and for all. For
7488        // system apps, we can probably assume that this information doesn't change
7489        // after the first boot scan. As things stand, we do lots of unnecessary work.
7490
7491        // Give ourselves some initial paths; we'll come back for another
7492        // pass once we've determined ABI below.
7493        setNativeLibraryPaths(pkg);
7494
7495        // We would never need to extract libs for forward-locked and external packages,
7496        // since the container service will do it for us. We shouldn't attempt to
7497        // extract libs from system app when it was not updated.
7498        if (pkg.isForwardLocked() || isExternal(pkg) ||
7499            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7500            extractLibs = false;
7501        }
7502
7503        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7504        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7505
7506        NativeLibraryHelper.Handle handle = null;
7507        try {
7508            handle = NativeLibraryHelper.Handle.create(pkg);
7509            // TODO(multiArch): This can be null for apps that didn't go through the
7510            // usual installation process. We can calculate it again, like we
7511            // do during install time.
7512            //
7513            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7514            // unnecessary.
7515            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7516
7517            // Null out the abis so that they can be recalculated.
7518            pkg.applicationInfo.primaryCpuAbi = null;
7519            pkg.applicationInfo.secondaryCpuAbi = null;
7520            if (isMultiArch(pkg.applicationInfo)) {
7521                // Warn if we've set an abiOverride for multi-lib packages..
7522                // By definition, we need to copy both 32 and 64 bit libraries for
7523                // such packages.
7524                if (pkg.cpuAbiOverride != null
7525                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7526                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7527                }
7528
7529                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7530                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7531                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7532                    if (extractLibs) {
7533                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7534                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7535                                useIsaSpecificSubdirs);
7536                    } else {
7537                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7538                    }
7539                }
7540
7541                maybeThrowExceptionForMultiArchCopy(
7542                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7543
7544                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7545                    if (extractLibs) {
7546                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7547                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7548                                useIsaSpecificSubdirs);
7549                    } else {
7550                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7551                    }
7552                }
7553
7554                maybeThrowExceptionForMultiArchCopy(
7555                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7556
7557                if (abi64 >= 0) {
7558                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7559                }
7560
7561                if (abi32 >= 0) {
7562                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7563                    if (abi64 >= 0) {
7564                        pkg.applicationInfo.secondaryCpuAbi = abi;
7565                    } else {
7566                        pkg.applicationInfo.primaryCpuAbi = abi;
7567                    }
7568                }
7569            } else {
7570                String[] abiList = (cpuAbiOverride != null) ?
7571                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7572
7573                // Enable gross and lame hacks for apps that are built with old
7574                // SDK tools. We must scan their APKs for renderscript bitcode and
7575                // not launch them if it's present. Don't bother checking on devices
7576                // that don't have 64 bit support.
7577                boolean needsRenderScriptOverride = false;
7578                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7579                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7580                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7581                    needsRenderScriptOverride = true;
7582                }
7583
7584                final int copyRet;
7585                if (extractLibs) {
7586                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7587                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7588                } else {
7589                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7590                }
7591
7592                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7593                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7594                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7595                }
7596
7597                if (copyRet >= 0) {
7598                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7599                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7600                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7601                } else if (needsRenderScriptOverride) {
7602                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7603                }
7604            }
7605        } catch (IOException ioe) {
7606            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7607        } finally {
7608            IoUtils.closeQuietly(handle);
7609        }
7610
7611        // Now that we've calculated the ABIs and determined if it's an internal app,
7612        // we will go ahead and populate the nativeLibraryPath.
7613        setNativeLibraryPaths(pkg);
7614    }
7615
7616    /**
7617     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7618     * i.e, so that all packages can be run inside a single process if required.
7619     *
7620     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7621     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7622     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7623     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7624     * updating a package that belongs to a shared user.
7625     *
7626     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7627     * adds unnecessary complexity.
7628     */
7629    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7630            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7631        String requiredInstructionSet = null;
7632        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7633            requiredInstructionSet = VMRuntime.getInstructionSet(
7634                     scannedPackage.applicationInfo.primaryCpuAbi);
7635        }
7636
7637        PackageSetting requirer = null;
7638        for (PackageSetting ps : packagesForUser) {
7639            // If packagesForUser contains scannedPackage, we skip it. This will happen
7640            // when scannedPackage is an update of an existing package. Without this check,
7641            // we will never be able to change the ABI of any package belonging to a shared
7642            // user, even if it's compatible with other packages.
7643            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7644                if (ps.primaryCpuAbiString == null) {
7645                    continue;
7646                }
7647
7648                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7649                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7650                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7651                    // this but there's not much we can do.
7652                    String errorMessage = "Instruction set mismatch, "
7653                            + ((requirer == null) ? "[caller]" : requirer)
7654                            + " requires " + requiredInstructionSet + " whereas " + ps
7655                            + " requires " + instructionSet;
7656                    Slog.w(TAG, errorMessage);
7657                }
7658
7659                if (requiredInstructionSet == null) {
7660                    requiredInstructionSet = instructionSet;
7661                    requirer = ps;
7662                }
7663            }
7664        }
7665
7666        if (requiredInstructionSet != null) {
7667            String adjustedAbi;
7668            if (requirer != null) {
7669                // requirer != null implies that either scannedPackage was null or that scannedPackage
7670                // did not require an ABI, in which case we have to adjust scannedPackage to match
7671                // the ABI of the set (which is the same as requirer's ABI)
7672                adjustedAbi = requirer.primaryCpuAbiString;
7673                if (scannedPackage != null) {
7674                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7675                }
7676            } else {
7677                // requirer == null implies that we're updating all ABIs in the set to
7678                // match scannedPackage.
7679                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7680            }
7681
7682            for (PackageSetting ps : packagesForUser) {
7683                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7684                    if (ps.primaryCpuAbiString != null) {
7685                        continue;
7686                    }
7687
7688                    ps.primaryCpuAbiString = adjustedAbi;
7689                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7690                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7691                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7692
7693                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7694                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7695                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7696                            ps.primaryCpuAbiString = null;
7697                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7698                            return;
7699                        } else {
7700                            mInstaller.rmdex(ps.codePathString,
7701                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7702                        }
7703                    }
7704                }
7705            }
7706        }
7707    }
7708
7709    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7710        synchronized (mPackages) {
7711            mResolverReplaced = true;
7712            // Set up information for custom user intent resolution activity.
7713            mResolveActivity.applicationInfo = pkg.applicationInfo;
7714            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7715            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7716            mResolveActivity.processName = pkg.applicationInfo.packageName;
7717            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7718            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7719                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7720            mResolveActivity.theme = 0;
7721            mResolveActivity.exported = true;
7722            mResolveActivity.enabled = true;
7723            mResolveInfo.activityInfo = mResolveActivity;
7724            mResolveInfo.priority = 0;
7725            mResolveInfo.preferredOrder = 0;
7726            mResolveInfo.match = 0;
7727            mResolveComponentName = mCustomResolverComponentName;
7728            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7729                    mResolveComponentName);
7730        }
7731    }
7732
7733    private static String calculateBundledApkRoot(final String codePathString) {
7734        final File codePath = new File(codePathString);
7735        final File codeRoot;
7736        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7737            codeRoot = Environment.getRootDirectory();
7738        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7739            codeRoot = Environment.getOemDirectory();
7740        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7741            codeRoot = Environment.getVendorDirectory();
7742        } else {
7743            // Unrecognized code path; take its top real segment as the apk root:
7744            // e.g. /something/app/blah.apk => /something
7745            try {
7746                File f = codePath.getCanonicalFile();
7747                File parent = f.getParentFile();    // non-null because codePath is a file
7748                File tmp;
7749                while ((tmp = parent.getParentFile()) != null) {
7750                    f = parent;
7751                    parent = tmp;
7752                }
7753                codeRoot = f;
7754                Slog.w(TAG, "Unrecognized code path "
7755                        + codePath + " - using " + codeRoot);
7756            } catch (IOException e) {
7757                // Can't canonicalize the code path -- shenanigans?
7758                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7759                return Environment.getRootDirectory().getPath();
7760            }
7761        }
7762        return codeRoot.getPath();
7763    }
7764
7765    /**
7766     * Derive and set the location of native libraries for the given package,
7767     * which varies depending on where and how the package was installed.
7768     */
7769    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7770        final ApplicationInfo info = pkg.applicationInfo;
7771        final String codePath = pkg.codePath;
7772        final File codeFile = new File(codePath);
7773        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7774        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7775
7776        info.nativeLibraryRootDir = null;
7777        info.nativeLibraryRootRequiresIsa = false;
7778        info.nativeLibraryDir = null;
7779        info.secondaryNativeLibraryDir = null;
7780
7781        if (isApkFile(codeFile)) {
7782            // Monolithic install
7783            if (bundledApp) {
7784                // If "/system/lib64/apkname" exists, assume that is the per-package
7785                // native library directory to use; otherwise use "/system/lib/apkname".
7786                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7787                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7788                        getPrimaryInstructionSet(info));
7789
7790                // This is a bundled system app so choose the path based on the ABI.
7791                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7792                // is just the default path.
7793                final String apkName = deriveCodePathName(codePath);
7794                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7795                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7796                        apkName).getAbsolutePath();
7797
7798                if (info.secondaryCpuAbi != null) {
7799                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7800                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7801                            secondaryLibDir, apkName).getAbsolutePath();
7802                }
7803            } else if (asecApp) {
7804                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7805                        .getAbsolutePath();
7806            } else {
7807                final String apkName = deriveCodePathName(codePath);
7808                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7809                        .getAbsolutePath();
7810            }
7811
7812            info.nativeLibraryRootRequiresIsa = false;
7813            info.nativeLibraryDir = info.nativeLibraryRootDir;
7814        } else {
7815            // Cluster install
7816            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7817            info.nativeLibraryRootRequiresIsa = true;
7818
7819            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7820                    getPrimaryInstructionSet(info)).getAbsolutePath();
7821
7822            if (info.secondaryCpuAbi != null) {
7823                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7824                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7825            }
7826        }
7827    }
7828
7829    /**
7830     * Calculate the abis and roots for a bundled app. These can uniquely
7831     * be determined from the contents of the system partition, i.e whether
7832     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7833     * of this information, and instead assume that the system was built
7834     * sensibly.
7835     */
7836    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7837                                           PackageSetting pkgSetting) {
7838        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7839
7840        // If "/system/lib64/apkname" exists, assume that is the per-package
7841        // native library directory to use; otherwise use "/system/lib/apkname".
7842        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7843        setBundledAppAbi(pkg, apkRoot, apkName);
7844        // pkgSetting might be null during rescan following uninstall of updates
7845        // to a bundled app, so accommodate that possibility.  The settings in
7846        // that case will be established later from the parsed package.
7847        //
7848        // If the settings aren't null, sync them up with what we've just derived.
7849        // note that apkRoot isn't stored in the package settings.
7850        if (pkgSetting != null) {
7851            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7852            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7853        }
7854    }
7855
7856    /**
7857     * Deduces the ABI of a bundled app and sets the relevant fields on the
7858     * parsed pkg object.
7859     *
7860     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7861     *        under which system libraries are installed.
7862     * @param apkName the name of the installed package.
7863     */
7864    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7865        final File codeFile = new File(pkg.codePath);
7866
7867        final boolean has64BitLibs;
7868        final boolean has32BitLibs;
7869        if (isApkFile(codeFile)) {
7870            // Monolithic install
7871            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7872            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7873        } else {
7874            // Cluster install
7875            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7876            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7877                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7878                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7879                has64BitLibs = (new File(rootDir, isa)).exists();
7880            } else {
7881                has64BitLibs = false;
7882            }
7883            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7884                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7885                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7886                has32BitLibs = (new File(rootDir, isa)).exists();
7887            } else {
7888                has32BitLibs = false;
7889            }
7890        }
7891
7892        if (has64BitLibs && !has32BitLibs) {
7893            // The package has 64 bit libs, but not 32 bit libs. Its primary
7894            // ABI should be 64 bit. We can safely assume here that the bundled
7895            // native libraries correspond to the most preferred ABI in the list.
7896
7897            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7898            pkg.applicationInfo.secondaryCpuAbi = null;
7899        } else if (has32BitLibs && !has64BitLibs) {
7900            // The package has 32 bit libs but not 64 bit libs. Its primary
7901            // ABI should be 32 bit.
7902
7903            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7904            pkg.applicationInfo.secondaryCpuAbi = null;
7905        } else if (has32BitLibs && has64BitLibs) {
7906            // The application has both 64 and 32 bit bundled libraries. We check
7907            // here that the app declares multiArch support, and warn if it doesn't.
7908            //
7909            // We will be lenient here and record both ABIs. The primary will be the
7910            // ABI that's higher on the list, i.e, a device that's configured to prefer
7911            // 64 bit apps will see a 64 bit primary ABI,
7912
7913            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7914                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7915            }
7916
7917            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7918                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7919                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7920            } else {
7921                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7922                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7923            }
7924        } else {
7925            pkg.applicationInfo.primaryCpuAbi = null;
7926            pkg.applicationInfo.secondaryCpuAbi = null;
7927        }
7928    }
7929
7930    private void killApplication(String pkgName, int appId, String reason) {
7931        // Request the ActivityManager to kill the process(only for existing packages)
7932        // so that we do not end up in a confused state while the user is still using the older
7933        // version of the application while the new one gets installed.
7934        IActivityManager am = ActivityManagerNative.getDefault();
7935        if (am != null) {
7936            try {
7937                am.killApplicationWithAppId(pkgName, appId, reason);
7938            } catch (RemoteException e) {
7939            }
7940        }
7941    }
7942
7943    void removePackageLI(PackageSetting ps, boolean chatty) {
7944        if (DEBUG_INSTALL) {
7945            if (chatty)
7946                Log.d(TAG, "Removing package " + ps.name);
7947        }
7948
7949        // writer
7950        synchronized (mPackages) {
7951            mPackages.remove(ps.name);
7952            final PackageParser.Package pkg = ps.pkg;
7953            if (pkg != null) {
7954                cleanPackageDataStructuresLILPw(pkg, chatty);
7955            }
7956        }
7957    }
7958
7959    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7960        if (DEBUG_INSTALL) {
7961            if (chatty)
7962                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7963        }
7964
7965        // writer
7966        synchronized (mPackages) {
7967            mPackages.remove(pkg.applicationInfo.packageName);
7968            cleanPackageDataStructuresLILPw(pkg, chatty);
7969        }
7970    }
7971
7972    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7973        int N = pkg.providers.size();
7974        StringBuilder r = null;
7975        int i;
7976        for (i=0; i<N; i++) {
7977            PackageParser.Provider p = pkg.providers.get(i);
7978            mProviders.removeProvider(p);
7979            if (p.info.authority == null) {
7980
7981                /* There was another ContentProvider with this authority when
7982                 * this app was installed so this authority is null,
7983                 * Ignore it as we don't have to unregister the provider.
7984                 */
7985                continue;
7986            }
7987            String names[] = p.info.authority.split(";");
7988            for (int j = 0; j < names.length; j++) {
7989                if (mProvidersByAuthority.get(names[j]) == p) {
7990                    mProvidersByAuthority.remove(names[j]);
7991                    if (DEBUG_REMOVE) {
7992                        if (chatty)
7993                            Log.d(TAG, "Unregistered content provider: " + names[j]
7994                                    + ", className = " + p.info.name + ", isSyncable = "
7995                                    + p.info.isSyncable);
7996                    }
7997                }
7998            }
7999            if (DEBUG_REMOVE && chatty) {
8000                if (r == null) {
8001                    r = new StringBuilder(256);
8002                } else {
8003                    r.append(' ');
8004                }
8005                r.append(p.info.name);
8006            }
8007        }
8008        if (r != null) {
8009            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8010        }
8011
8012        N = pkg.services.size();
8013        r = null;
8014        for (i=0; i<N; i++) {
8015            PackageParser.Service s = pkg.services.get(i);
8016            mServices.removeService(s);
8017            if (chatty) {
8018                if (r == null) {
8019                    r = new StringBuilder(256);
8020                } else {
8021                    r.append(' ');
8022                }
8023                r.append(s.info.name);
8024            }
8025        }
8026        if (r != null) {
8027            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8028        }
8029
8030        N = pkg.receivers.size();
8031        r = null;
8032        for (i=0; i<N; i++) {
8033            PackageParser.Activity a = pkg.receivers.get(i);
8034            mReceivers.removeActivity(a, "receiver");
8035            if (DEBUG_REMOVE && chatty) {
8036                if (r == null) {
8037                    r = new StringBuilder(256);
8038                } else {
8039                    r.append(' ');
8040                }
8041                r.append(a.info.name);
8042            }
8043        }
8044        if (r != null) {
8045            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8046        }
8047
8048        N = pkg.activities.size();
8049        r = null;
8050        for (i=0; i<N; i++) {
8051            PackageParser.Activity a = pkg.activities.get(i);
8052            mActivities.removeActivity(a, "activity");
8053            if (DEBUG_REMOVE && chatty) {
8054                if (r == null) {
8055                    r = new StringBuilder(256);
8056                } else {
8057                    r.append(' ');
8058                }
8059                r.append(a.info.name);
8060            }
8061        }
8062        if (r != null) {
8063            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8064        }
8065
8066        N = pkg.permissions.size();
8067        r = null;
8068        for (i=0; i<N; i++) {
8069            PackageParser.Permission p = pkg.permissions.get(i);
8070            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8071            if (bp == null) {
8072                bp = mSettings.mPermissionTrees.get(p.info.name);
8073            }
8074            if (bp != null && bp.perm == p) {
8075                bp.perm = null;
8076                if (DEBUG_REMOVE && chatty) {
8077                    if (r == null) {
8078                        r = new StringBuilder(256);
8079                    } else {
8080                        r.append(' ');
8081                    }
8082                    r.append(p.info.name);
8083                }
8084            }
8085            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8086                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8087                if (appOpPerms != null) {
8088                    appOpPerms.remove(pkg.packageName);
8089                }
8090            }
8091        }
8092        if (r != null) {
8093            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8094        }
8095
8096        N = pkg.requestedPermissions.size();
8097        r = null;
8098        for (i=0; i<N; i++) {
8099            String perm = pkg.requestedPermissions.get(i);
8100            BasePermission bp = mSettings.mPermissions.get(perm);
8101            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8102                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8103                if (appOpPerms != null) {
8104                    appOpPerms.remove(pkg.packageName);
8105                    if (appOpPerms.isEmpty()) {
8106                        mAppOpPermissionPackages.remove(perm);
8107                    }
8108                }
8109            }
8110        }
8111        if (r != null) {
8112            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8113        }
8114
8115        N = pkg.instrumentation.size();
8116        r = null;
8117        for (i=0; i<N; i++) {
8118            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8119            mInstrumentation.remove(a.getComponentName());
8120            if (DEBUG_REMOVE && chatty) {
8121                if (r == null) {
8122                    r = new StringBuilder(256);
8123                } else {
8124                    r.append(' ');
8125                }
8126                r.append(a.info.name);
8127            }
8128        }
8129        if (r != null) {
8130            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8131        }
8132
8133        r = null;
8134        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8135            // Only system apps can hold shared libraries.
8136            if (pkg.libraryNames != null) {
8137                for (i=0; i<pkg.libraryNames.size(); i++) {
8138                    String name = pkg.libraryNames.get(i);
8139                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8140                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8141                        mSharedLibraries.remove(name);
8142                        if (DEBUG_REMOVE && chatty) {
8143                            if (r == null) {
8144                                r = new StringBuilder(256);
8145                            } else {
8146                                r.append(' ');
8147                            }
8148                            r.append(name);
8149                        }
8150                    }
8151                }
8152            }
8153        }
8154        if (r != null) {
8155            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8156        }
8157    }
8158
8159    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8160        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8161            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8162                return true;
8163            }
8164        }
8165        return false;
8166    }
8167
8168    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8169    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8170    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8171
8172    private void updatePermissionsLPw(String changingPkg,
8173            PackageParser.Package pkgInfo, int flags) {
8174        // Make sure there are no dangling permission trees.
8175        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8176        while (it.hasNext()) {
8177            final BasePermission bp = it.next();
8178            if (bp.packageSetting == null) {
8179                // We may not yet have parsed the package, so just see if
8180                // we still know about its settings.
8181                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8182            }
8183            if (bp.packageSetting == null) {
8184                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8185                        + " from package " + bp.sourcePackage);
8186                it.remove();
8187            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8188                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8189                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8190                            + " from package " + bp.sourcePackage);
8191                    flags |= UPDATE_PERMISSIONS_ALL;
8192                    it.remove();
8193                }
8194            }
8195        }
8196
8197        // Make sure all dynamic permissions have been assigned to a package,
8198        // and make sure there are no dangling permissions.
8199        it = mSettings.mPermissions.values().iterator();
8200        while (it.hasNext()) {
8201            final BasePermission bp = it.next();
8202            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8203                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8204                        + bp.name + " pkg=" + bp.sourcePackage
8205                        + " info=" + bp.pendingInfo);
8206                if (bp.packageSetting == null && bp.pendingInfo != null) {
8207                    final BasePermission tree = findPermissionTreeLP(bp.name);
8208                    if (tree != null && tree.perm != null) {
8209                        bp.packageSetting = tree.packageSetting;
8210                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8211                                new PermissionInfo(bp.pendingInfo));
8212                        bp.perm.info.packageName = tree.perm.info.packageName;
8213                        bp.perm.info.name = bp.name;
8214                        bp.uid = tree.uid;
8215                    }
8216                }
8217            }
8218            if (bp.packageSetting == null) {
8219                // We may not yet have parsed the package, so just see if
8220                // we still know about its settings.
8221                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8222            }
8223            if (bp.packageSetting == null) {
8224                Slog.w(TAG, "Removing dangling permission: " + bp.name
8225                        + " from package " + bp.sourcePackage);
8226                it.remove();
8227            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8228                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8229                    Slog.i(TAG, "Removing old permission: " + bp.name
8230                            + " from package " + bp.sourcePackage);
8231                    flags |= UPDATE_PERMISSIONS_ALL;
8232                    it.remove();
8233                }
8234            }
8235        }
8236
8237        // Now update the permissions for all packages, in particular
8238        // replace the granted permissions of the system packages.
8239        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8240            for (PackageParser.Package pkg : mPackages.values()) {
8241                if (pkg != pkgInfo) {
8242                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8243                            changingPkg);
8244                }
8245            }
8246        }
8247
8248        if (pkgInfo != null) {
8249            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8250        }
8251    }
8252
8253    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8254            String packageOfInterest) {
8255        // IMPORTANT: There are two types of permissions: install and runtime.
8256        // Install time permissions are granted when the app is installed to
8257        // all device users and users added in the future. Runtime permissions
8258        // are granted at runtime explicitly to specific users. Normal and signature
8259        // protected permissions are install time permissions. Dangerous permissions
8260        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8261        // otherwise they are runtime permissions. This function does not manage
8262        // runtime permissions except for the case an app targeting Lollipop MR1
8263        // being upgraded to target a newer SDK, in which case dangerous permissions
8264        // are transformed from install time to runtime ones.
8265
8266        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8267        if (ps == null) {
8268            return;
8269        }
8270
8271        PermissionsState permissionsState = ps.getPermissionsState();
8272        PermissionsState origPermissions = permissionsState;
8273
8274        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8275
8276        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8277
8278        boolean changedInstallPermission = false;
8279
8280        if (replace) {
8281            ps.installPermissionsFixed = false;
8282            if (!ps.isSharedUser()) {
8283                origPermissions = new PermissionsState(permissionsState);
8284                permissionsState.reset();
8285            }
8286        }
8287
8288        permissionsState.setGlobalGids(mGlobalGids);
8289
8290        final int N = pkg.requestedPermissions.size();
8291        for (int i=0; i<N; i++) {
8292            final String name = pkg.requestedPermissions.get(i);
8293            final BasePermission bp = mSettings.mPermissions.get(name);
8294
8295            if (DEBUG_INSTALL) {
8296                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8297            }
8298
8299            if (bp == null || bp.packageSetting == null) {
8300                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8301                    Slog.w(TAG, "Unknown permission " + name
8302                            + " in package " + pkg.packageName);
8303                }
8304                continue;
8305            }
8306
8307            final String perm = bp.name;
8308            boolean allowedSig = false;
8309            int grant = GRANT_DENIED;
8310
8311            // Keep track of app op permissions.
8312            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8313                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8314                if (pkgs == null) {
8315                    pkgs = new ArraySet<>();
8316                    mAppOpPermissionPackages.put(bp.name, pkgs);
8317                }
8318                pkgs.add(pkg.packageName);
8319            }
8320
8321            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8322            switch (level) {
8323                case PermissionInfo.PROTECTION_NORMAL: {
8324                    // For all apps normal permissions are install time ones.
8325                    grant = GRANT_INSTALL;
8326                } break;
8327
8328                case PermissionInfo.PROTECTION_DANGEROUS: {
8329                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8330                        // For legacy apps dangerous permissions are install time ones.
8331                        grant = GRANT_INSTALL_LEGACY;
8332                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8333                        // For legacy apps that became modern, install becomes runtime.
8334                        grant = GRANT_UPGRADE;
8335                    } else {
8336                        // For modern apps keep runtime permissions unchanged.
8337                        grant = GRANT_RUNTIME;
8338                    }
8339                } break;
8340
8341                case PermissionInfo.PROTECTION_SIGNATURE: {
8342                    // For all apps signature permissions are install time ones.
8343                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8344                    if (allowedSig) {
8345                        grant = GRANT_INSTALL;
8346                    }
8347                } break;
8348            }
8349
8350            if (DEBUG_INSTALL) {
8351                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8352            }
8353
8354            if (grant != GRANT_DENIED) {
8355                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8356                    // If this is an existing, non-system package, then
8357                    // we can't add any new permissions to it.
8358                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8359                        // Except...  if this is a permission that was added
8360                        // to the platform (note: need to only do this when
8361                        // updating the platform).
8362                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8363                            grant = GRANT_DENIED;
8364                        }
8365                    }
8366                }
8367
8368                switch (grant) {
8369                    case GRANT_INSTALL: {
8370                        // Revoke this as runtime permission to handle the case of
8371                        // a runtime permission being downgraded to an install one.
8372                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8373                            if (origPermissions.getRuntimePermissionState(
8374                                    bp.name, userId) != null) {
8375                                // Revoke the runtime permission and clear the flags.
8376                                origPermissions.revokeRuntimePermission(bp, userId);
8377                                origPermissions.updatePermissionFlags(bp, userId,
8378                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8379                                // If we revoked a permission permission, we have to write.
8380                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8381                                        changedRuntimePermissionUserIds, userId);
8382                            }
8383                        }
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_INSTALL_LEGACY: {
8392                        // Grant an install permission.
8393                        if (permissionsState.grantInstallPermission(bp) !=
8394                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8395                            changedInstallPermission = true;
8396                        }
8397                    } break;
8398
8399                    case GRANT_RUNTIME: {
8400                        // Grant previously granted runtime permissions.
8401                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8402                            PermissionState permissionState = origPermissions
8403                                    .getRuntimePermissionState(bp.name, userId);
8404                            final int flags = permissionState != null
8405                                    ? permissionState.getFlags() : 0;
8406                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8407                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8408                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8409                                    // If we cannot put the permission as it was, we have to write.
8410                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8411                                            changedRuntimePermissionUserIds, userId);
8412                                }
8413                            }
8414                            // Propagate the permission flags.
8415                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8416                        }
8417                    } break;
8418
8419                    case GRANT_UPGRADE: {
8420                        // Grant runtime permissions for a previously held install permission.
8421                        PermissionState permissionState = origPermissions
8422                                .getInstallPermissionState(bp.name);
8423                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8424
8425                        if (origPermissions.revokeInstallPermission(bp)
8426                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8427                            // We will be transferring the permission flags, so clear them.
8428                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8429                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8430                            changedInstallPermission = true;
8431                        }
8432
8433                        // If the permission is not to be promoted to runtime we ignore it and
8434                        // also its other flags as they are not applicable to install permissions.
8435                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8436                            for (int userId : currentUserIds) {
8437                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8438                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8439                                    // Transfer the permission flags.
8440                                    permissionsState.updatePermissionFlags(bp, userId,
8441                                            flags, flags);
8442                                    // If we granted the permission, we have to write.
8443                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8444                                            changedRuntimePermissionUserIds, userId);
8445                                }
8446                            }
8447                        }
8448                    } break;
8449
8450                    default: {
8451                        if (packageOfInterest == null
8452                                || packageOfInterest.equals(pkg.packageName)) {
8453                            Slog.w(TAG, "Not granting permission " + perm
8454                                    + " to package " + pkg.packageName
8455                                    + " because it was previously installed without");
8456                        }
8457                    } break;
8458                }
8459            } else {
8460                if (permissionsState.revokeInstallPermission(bp) !=
8461                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8462                    // Also drop the permission flags.
8463                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8464                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8465                    changedInstallPermission = true;
8466                    Slog.i(TAG, "Un-granting permission " + perm
8467                            + " from package " + pkg.packageName
8468                            + " (protectionLevel=" + bp.protectionLevel
8469                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8470                            + ")");
8471                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8472                    // Don't print warning for app op permissions, since it is fine for them
8473                    // not to be granted, there is a UI for the user to decide.
8474                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8475                        Slog.w(TAG, "Not granting permission " + perm
8476                                + " to package " + pkg.packageName
8477                                + " (protectionLevel=" + bp.protectionLevel
8478                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8479                                + ")");
8480                    }
8481                }
8482            }
8483        }
8484
8485        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8486                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8487            // This is the first that we have heard about this package, so the
8488            // permissions we have now selected are fixed until explicitly
8489            // changed.
8490            ps.installPermissionsFixed = true;
8491        }
8492
8493        // Persist the runtime permissions state for users with changes.
8494        for (int userId : changedRuntimePermissionUserIds) {
8495            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8496        }
8497    }
8498
8499    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8500        boolean allowed = false;
8501        final int NP = PackageParser.NEW_PERMISSIONS.length;
8502        for (int ip=0; ip<NP; ip++) {
8503            final PackageParser.NewPermissionInfo npi
8504                    = PackageParser.NEW_PERMISSIONS[ip];
8505            if (npi.name.equals(perm)
8506                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8507                allowed = true;
8508                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8509                        + pkg.packageName);
8510                break;
8511            }
8512        }
8513        return allowed;
8514    }
8515
8516    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8517            BasePermission bp, PermissionsState origPermissions) {
8518        boolean allowed;
8519        allowed = (compareSignatures(
8520                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8521                        == PackageManager.SIGNATURE_MATCH)
8522                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8523                        == PackageManager.SIGNATURE_MATCH);
8524        if (!allowed && (bp.protectionLevel
8525                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8526            if (isSystemApp(pkg)) {
8527                // For updated system applications, a system permission
8528                // is granted only if it had been defined by the original application.
8529                if (pkg.isUpdatedSystemApp()) {
8530                    final PackageSetting sysPs = mSettings
8531                            .getDisabledSystemPkgLPr(pkg.packageName);
8532                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8533                        // If the original was granted this permission, we take
8534                        // that grant decision as read and propagate it to the
8535                        // update.
8536                        if (sysPs.isPrivileged()) {
8537                            allowed = true;
8538                        }
8539                    } else {
8540                        // The system apk may have been updated with an older
8541                        // version of the one on the data partition, but which
8542                        // granted a new system permission that it didn't have
8543                        // before.  In this case we do want to allow the app to
8544                        // now get the new permission if the ancestral apk is
8545                        // privileged to get it.
8546                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8547                            for (int j=0;
8548                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8549                                if (perm.equals(
8550                                        sysPs.pkg.requestedPermissions.get(j))) {
8551                                    allowed = true;
8552                                    break;
8553                                }
8554                            }
8555                        }
8556                    }
8557                } else {
8558                    allowed = isPrivilegedApp(pkg);
8559                }
8560            }
8561        }
8562        if (!allowed) {
8563            if (!allowed && (bp.protectionLevel
8564                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8565                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8566                // If this was a previously normal/dangerous permission that got moved
8567                // to a system permission as part of the runtime permission redesign, then
8568                // we still want to blindly grant it to old apps.
8569                allowed = true;
8570            }
8571            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8572                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8573                // If this permission is to be granted to the system installer and
8574                // this app is an installer, then it gets the permission.
8575                allowed = true;
8576            }
8577            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8578                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8579                // If this permission is to be granted to the system verifier and
8580                // this app is a verifier, then it gets the permission.
8581                allowed = true;
8582            }
8583            if (!allowed && (bp.protectionLevel
8584                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8585                    && isSystemApp(pkg)) {
8586                // Any pre-installed system app is allowed to get this permission.
8587                allowed = true;
8588            }
8589            if (!allowed && (bp.protectionLevel
8590                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8591                // For development permissions, a development permission
8592                // is granted only if it was already granted.
8593                allowed = origPermissions.hasInstallPermission(perm);
8594            }
8595        }
8596        return allowed;
8597    }
8598
8599    final class ActivityIntentResolver
8600            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8601        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8602                boolean defaultOnly, int userId) {
8603            if (!sUserManager.exists(userId)) return null;
8604            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8605            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8606        }
8607
8608        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8609                int userId) {
8610            if (!sUserManager.exists(userId)) return null;
8611            mFlags = flags;
8612            return super.queryIntent(intent, resolvedType,
8613                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8614        }
8615
8616        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8617                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8618            if (!sUserManager.exists(userId)) return null;
8619            if (packageActivities == null) {
8620                return null;
8621            }
8622            mFlags = flags;
8623            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8624            final int N = packageActivities.size();
8625            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8626                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8627
8628            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8629            for (int i = 0; i < N; ++i) {
8630                intentFilters = packageActivities.get(i).intents;
8631                if (intentFilters != null && intentFilters.size() > 0) {
8632                    PackageParser.ActivityIntentInfo[] array =
8633                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8634                    intentFilters.toArray(array);
8635                    listCut.add(array);
8636                }
8637            }
8638            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8639        }
8640
8641        public final void addActivity(PackageParser.Activity a, String type) {
8642            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8643            mActivities.put(a.getComponentName(), a);
8644            if (DEBUG_SHOW_INFO)
8645                Log.v(
8646                TAG, "  " + type + " " +
8647                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8648            if (DEBUG_SHOW_INFO)
8649                Log.v(TAG, "    Class=" + a.info.name);
8650            final int NI = a.intents.size();
8651            for (int j=0; j<NI; j++) {
8652                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8653                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8654                    intent.setPriority(0);
8655                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8656                            + a.className + " with priority > 0, forcing to 0");
8657                }
8658                if (DEBUG_SHOW_INFO) {
8659                    Log.v(TAG, "    IntentFilter:");
8660                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8661                }
8662                if (!intent.debugCheck()) {
8663                    Log.w(TAG, "==> For Activity " + a.info.name);
8664                }
8665                addFilter(intent);
8666            }
8667        }
8668
8669        public final void removeActivity(PackageParser.Activity a, String type) {
8670            mActivities.remove(a.getComponentName());
8671            if (DEBUG_SHOW_INFO) {
8672                Log.v(TAG, "  " + type + " "
8673                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8674                                : a.info.name) + ":");
8675                Log.v(TAG, "    Class=" + a.info.name);
8676            }
8677            final int NI = a.intents.size();
8678            for (int j=0; j<NI; j++) {
8679                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8680                if (DEBUG_SHOW_INFO) {
8681                    Log.v(TAG, "    IntentFilter:");
8682                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8683                }
8684                removeFilter(intent);
8685            }
8686        }
8687
8688        @Override
8689        protected boolean allowFilterResult(
8690                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8691            ActivityInfo filterAi = filter.activity.info;
8692            for (int i=dest.size()-1; i>=0; i--) {
8693                ActivityInfo destAi = dest.get(i).activityInfo;
8694                if (destAi.name == filterAi.name
8695                        && destAi.packageName == filterAi.packageName) {
8696                    return false;
8697                }
8698            }
8699            return true;
8700        }
8701
8702        @Override
8703        protected ActivityIntentInfo[] newArray(int size) {
8704            return new ActivityIntentInfo[size];
8705        }
8706
8707        @Override
8708        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8709            if (!sUserManager.exists(userId)) return true;
8710            PackageParser.Package p = filter.activity.owner;
8711            if (p != null) {
8712                PackageSetting ps = (PackageSetting)p.mExtras;
8713                if (ps != null) {
8714                    // System apps are never considered stopped for purposes of
8715                    // filtering, because there may be no way for the user to
8716                    // actually re-launch them.
8717                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8718                            && ps.getStopped(userId);
8719                }
8720            }
8721            return false;
8722        }
8723
8724        @Override
8725        protected boolean isPackageForFilter(String packageName,
8726                PackageParser.ActivityIntentInfo info) {
8727            return packageName.equals(info.activity.owner.packageName);
8728        }
8729
8730        @Override
8731        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8732                int match, int userId) {
8733            if (!sUserManager.exists(userId)) return null;
8734            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8735                return null;
8736            }
8737            final PackageParser.Activity activity = info.activity;
8738            if (mSafeMode && (activity.info.applicationInfo.flags
8739                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8740                return null;
8741            }
8742            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8743            if (ps == null) {
8744                return null;
8745            }
8746            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8747                    ps.readUserState(userId), userId);
8748            if (ai == null) {
8749                return null;
8750            }
8751            final ResolveInfo res = new ResolveInfo();
8752            res.activityInfo = ai;
8753            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8754                res.filter = info;
8755            }
8756            if (info != null) {
8757                res.handleAllWebDataURI = info.handleAllWebDataURI();
8758            }
8759            res.priority = info.getPriority();
8760            res.preferredOrder = activity.owner.mPreferredOrder;
8761            //System.out.println("Result: " + res.activityInfo.className +
8762            //                   " = " + res.priority);
8763            res.match = match;
8764            res.isDefault = info.hasDefault;
8765            res.labelRes = info.labelRes;
8766            res.nonLocalizedLabel = info.nonLocalizedLabel;
8767            if (userNeedsBadging(userId)) {
8768                res.noResourceId = true;
8769            } else {
8770                res.icon = info.icon;
8771            }
8772            res.iconResourceId = info.icon;
8773            res.system = res.activityInfo.applicationInfo.isSystemApp();
8774            return res;
8775        }
8776
8777        @Override
8778        protected void sortResults(List<ResolveInfo> results) {
8779            Collections.sort(results, mResolvePrioritySorter);
8780        }
8781
8782        @Override
8783        protected void dumpFilter(PrintWriter out, String prefix,
8784                PackageParser.ActivityIntentInfo filter) {
8785            out.print(prefix); out.print(
8786                    Integer.toHexString(System.identityHashCode(filter.activity)));
8787                    out.print(' ');
8788                    filter.activity.printComponentShortName(out);
8789                    out.print(" filter ");
8790                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8791        }
8792
8793        @Override
8794        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8795            return filter.activity;
8796        }
8797
8798        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8799            PackageParser.Activity activity = (PackageParser.Activity)label;
8800            out.print(prefix); out.print(
8801                    Integer.toHexString(System.identityHashCode(activity)));
8802                    out.print(' ');
8803                    activity.printComponentShortName(out);
8804            if (count > 1) {
8805                out.print(" ("); out.print(count); out.print(" filters)");
8806            }
8807            out.println();
8808        }
8809
8810//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8811//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8812//            final List<ResolveInfo> retList = Lists.newArrayList();
8813//            while (i.hasNext()) {
8814//                final ResolveInfo resolveInfo = i.next();
8815//                if (isEnabledLP(resolveInfo.activityInfo)) {
8816//                    retList.add(resolveInfo);
8817//                }
8818//            }
8819//            return retList;
8820//        }
8821
8822        // Keys are String (activity class name), values are Activity.
8823        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8824                = new ArrayMap<ComponentName, PackageParser.Activity>();
8825        private int mFlags;
8826    }
8827
8828    private final class ServiceIntentResolver
8829            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8830        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8831                boolean defaultOnly, int userId) {
8832            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8833            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8834        }
8835
8836        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8837                int userId) {
8838            if (!sUserManager.exists(userId)) return null;
8839            mFlags = flags;
8840            return super.queryIntent(intent, resolvedType,
8841                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8842        }
8843
8844        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8845                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8846            if (!sUserManager.exists(userId)) return null;
8847            if (packageServices == null) {
8848                return null;
8849            }
8850            mFlags = flags;
8851            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8852            final int N = packageServices.size();
8853            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8854                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8855
8856            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8857            for (int i = 0; i < N; ++i) {
8858                intentFilters = packageServices.get(i).intents;
8859                if (intentFilters != null && intentFilters.size() > 0) {
8860                    PackageParser.ServiceIntentInfo[] array =
8861                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8862                    intentFilters.toArray(array);
8863                    listCut.add(array);
8864                }
8865            }
8866            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8867        }
8868
8869        public final void addService(PackageParser.Service s) {
8870            mServices.put(s.getComponentName(), s);
8871            if (DEBUG_SHOW_INFO) {
8872                Log.v(TAG, "  "
8873                        + (s.info.nonLocalizedLabel != null
8874                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8875                Log.v(TAG, "    Class=" + s.info.name);
8876            }
8877            final int NI = s.intents.size();
8878            int j;
8879            for (j=0; j<NI; j++) {
8880                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8881                if (DEBUG_SHOW_INFO) {
8882                    Log.v(TAG, "    IntentFilter:");
8883                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8884                }
8885                if (!intent.debugCheck()) {
8886                    Log.w(TAG, "==> For Service " + s.info.name);
8887                }
8888                addFilter(intent);
8889            }
8890        }
8891
8892        public final void removeService(PackageParser.Service s) {
8893            mServices.remove(s.getComponentName());
8894            if (DEBUG_SHOW_INFO) {
8895                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8896                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8897                Log.v(TAG, "    Class=" + s.info.name);
8898            }
8899            final int NI = s.intents.size();
8900            int j;
8901            for (j=0; j<NI; j++) {
8902                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8903                if (DEBUG_SHOW_INFO) {
8904                    Log.v(TAG, "    IntentFilter:");
8905                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8906                }
8907                removeFilter(intent);
8908            }
8909        }
8910
8911        @Override
8912        protected boolean allowFilterResult(
8913                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8914            ServiceInfo filterSi = filter.service.info;
8915            for (int i=dest.size()-1; i>=0; i--) {
8916                ServiceInfo destAi = dest.get(i).serviceInfo;
8917                if (destAi.name == filterSi.name
8918                        && destAi.packageName == filterSi.packageName) {
8919                    return false;
8920                }
8921            }
8922            return true;
8923        }
8924
8925        @Override
8926        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8927            return new PackageParser.ServiceIntentInfo[size];
8928        }
8929
8930        @Override
8931        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8932            if (!sUserManager.exists(userId)) return true;
8933            PackageParser.Package p = filter.service.owner;
8934            if (p != null) {
8935                PackageSetting ps = (PackageSetting)p.mExtras;
8936                if (ps != null) {
8937                    // System apps are never considered stopped for purposes of
8938                    // filtering, because there may be no way for the user to
8939                    // actually re-launch them.
8940                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8941                            && ps.getStopped(userId);
8942                }
8943            }
8944            return false;
8945        }
8946
8947        @Override
8948        protected boolean isPackageForFilter(String packageName,
8949                PackageParser.ServiceIntentInfo info) {
8950            return packageName.equals(info.service.owner.packageName);
8951        }
8952
8953        @Override
8954        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8955                int match, int userId) {
8956            if (!sUserManager.exists(userId)) return null;
8957            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8958            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8959                return null;
8960            }
8961            final PackageParser.Service service = info.service;
8962            if (mSafeMode && (service.info.applicationInfo.flags
8963                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8964                return null;
8965            }
8966            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8967            if (ps == null) {
8968                return null;
8969            }
8970            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8971                    ps.readUserState(userId), userId);
8972            if (si == null) {
8973                return null;
8974            }
8975            final ResolveInfo res = new ResolveInfo();
8976            res.serviceInfo = si;
8977            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8978                res.filter = filter;
8979            }
8980            res.priority = info.getPriority();
8981            res.preferredOrder = service.owner.mPreferredOrder;
8982            res.match = match;
8983            res.isDefault = info.hasDefault;
8984            res.labelRes = info.labelRes;
8985            res.nonLocalizedLabel = info.nonLocalizedLabel;
8986            res.icon = info.icon;
8987            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8988            return res;
8989        }
8990
8991        @Override
8992        protected void sortResults(List<ResolveInfo> results) {
8993            Collections.sort(results, mResolvePrioritySorter);
8994        }
8995
8996        @Override
8997        protected void dumpFilter(PrintWriter out, String prefix,
8998                PackageParser.ServiceIntentInfo filter) {
8999            out.print(prefix); out.print(
9000                    Integer.toHexString(System.identityHashCode(filter.service)));
9001                    out.print(' ');
9002                    filter.service.printComponentShortName(out);
9003                    out.print(" filter ");
9004                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9005        }
9006
9007        @Override
9008        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9009            return filter.service;
9010        }
9011
9012        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9013            PackageParser.Service service = (PackageParser.Service)label;
9014            out.print(prefix); out.print(
9015                    Integer.toHexString(System.identityHashCode(service)));
9016                    out.print(' ');
9017                    service.printComponentShortName(out);
9018            if (count > 1) {
9019                out.print(" ("); out.print(count); out.print(" filters)");
9020            }
9021            out.println();
9022        }
9023
9024//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9025//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9026//            final List<ResolveInfo> retList = Lists.newArrayList();
9027//            while (i.hasNext()) {
9028//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9029//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9030//                    retList.add(resolveInfo);
9031//                }
9032//            }
9033//            return retList;
9034//        }
9035
9036        // Keys are String (activity class name), values are Activity.
9037        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9038                = new ArrayMap<ComponentName, PackageParser.Service>();
9039        private int mFlags;
9040    };
9041
9042    private final class ProviderIntentResolver
9043            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9044        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9045                boolean defaultOnly, int userId) {
9046            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9047            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9048        }
9049
9050        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9051                int userId) {
9052            if (!sUserManager.exists(userId))
9053                return null;
9054            mFlags = flags;
9055            return super.queryIntent(intent, resolvedType,
9056                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9057        }
9058
9059        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9060                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9061            if (!sUserManager.exists(userId))
9062                return null;
9063            if (packageProviders == null) {
9064                return null;
9065            }
9066            mFlags = flags;
9067            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9068            final int N = packageProviders.size();
9069            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9070                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9071
9072            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9073            for (int i = 0; i < N; ++i) {
9074                intentFilters = packageProviders.get(i).intents;
9075                if (intentFilters != null && intentFilters.size() > 0) {
9076                    PackageParser.ProviderIntentInfo[] array =
9077                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9078                    intentFilters.toArray(array);
9079                    listCut.add(array);
9080                }
9081            }
9082            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9083        }
9084
9085        public final void addProvider(PackageParser.Provider p) {
9086            if (mProviders.containsKey(p.getComponentName())) {
9087                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9088                return;
9089            }
9090
9091            mProviders.put(p.getComponentName(), p);
9092            if (DEBUG_SHOW_INFO) {
9093                Log.v(TAG, "  "
9094                        + (p.info.nonLocalizedLabel != null
9095                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9096                Log.v(TAG, "    Class=" + p.info.name);
9097            }
9098            final int NI = p.intents.size();
9099            int j;
9100            for (j = 0; j < NI; j++) {
9101                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9102                if (DEBUG_SHOW_INFO) {
9103                    Log.v(TAG, "    IntentFilter:");
9104                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9105                }
9106                if (!intent.debugCheck()) {
9107                    Log.w(TAG, "==> For Provider " + p.info.name);
9108                }
9109                addFilter(intent);
9110            }
9111        }
9112
9113        public final void removeProvider(PackageParser.Provider p) {
9114            mProviders.remove(p.getComponentName());
9115            if (DEBUG_SHOW_INFO) {
9116                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9117                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9118                Log.v(TAG, "    Class=" + p.info.name);
9119            }
9120            final int NI = p.intents.size();
9121            int j;
9122            for (j = 0; j < NI; j++) {
9123                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9124                if (DEBUG_SHOW_INFO) {
9125                    Log.v(TAG, "    IntentFilter:");
9126                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9127                }
9128                removeFilter(intent);
9129            }
9130        }
9131
9132        @Override
9133        protected boolean allowFilterResult(
9134                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9135            ProviderInfo filterPi = filter.provider.info;
9136            for (int i = dest.size() - 1; i >= 0; i--) {
9137                ProviderInfo destPi = dest.get(i).providerInfo;
9138                if (destPi.name == filterPi.name
9139                        && destPi.packageName == filterPi.packageName) {
9140                    return false;
9141                }
9142            }
9143            return true;
9144        }
9145
9146        @Override
9147        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9148            return new PackageParser.ProviderIntentInfo[size];
9149        }
9150
9151        @Override
9152        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9153            if (!sUserManager.exists(userId))
9154                return true;
9155            PackageParser.Package p = filter.provider.owner;
9156            if (p != null) {
9157                PackageSetting ps = (PackageSetting) p.mExtras;
9158                if (ps != null) {
9159                    // System apps are never considered stopped for purposes of
9160                    // filtering, because there may be no way for the user to
9161                    // actually re-launch them.
9162                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9163                            && ps.getStopped(userId);
9164                }
9165            }
9166            return false;
9167        }
9168
9169        @Override
9170        protected boolean isPackageForFilter(String packageName,
9171                PackageParser.ProviderIntentInfo info) {
9172            return packageName.equals(info.provider.owner.packageName);
9173        }
9174
9175        @Override
9176        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9177                int match, int userId) {
9178            if (!sUserManager.exists(userId))
9179                return null;
9180            final PackageParser.ProviderIntentInfo info = filter;
9181            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9182                return null;
9183            }
9184            final PackageParser.Provider provider = info.provider;
9185            if (mSafeMode && (provider.info.applicationInfo.flags
9186                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9187                return null;
9188            }
9189            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9190            if (ps == null) {
9191                return null;
9192            }
9193            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9194                    ps.readUserState(userId), userId);
9195            if (pi == null) {
9196                return null;
9197            }
9198            final ResolveInfo res = new ResolveInfo();
9199            res.providerInfo = pi;
9200            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9201                res.filter = filter;
9202            }
9203            res.priority = info.getPriority();
9204            res.preferredOrder = provider.owner.mPreferredOrder;
9205            res.match = match;
9206            res.isDefault = info.hasDefault;
9207            res.labelRes = info.labelRes;
9208            res.nonLocalizedLabel = info.nonLocalizedLabel;
9209            res.icon = info.icon;
9210            res.system = res.providerInfo.applicationInfo.isSystemApp();
9211            return res;
9212        }
9213
9214        @Override
9215        protected void sortResults(List<ResolveInfo> results) {
9216            Collections.sort(results, mResolvePrioritySorter);
9217        }
9218
9219        @Override
9220        protected void dumpFilter(PrintWriter out, String prefix,
9221                PackageParser.ProviderIntentInfo filter) {
9222            out.print(prefix);
9223            out.print(
9224                    Integer.toHexString(System.identityHashCode(filter.provider)));
9225            out.print(' ');
9226            filter.provider.printComponentShortName(out);
9227            out.print(" filter ");
9228            out.println(Integer.toHexString(System.identityHashCode(filter)));
9229        }
9230
9231        @Override
9232        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9233            return filter.provider;
9234        }
9235
9236        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9237            PackageParser.Provider provider = (PackageParser.Provider)label;
9238            out.print(prefix); out.print(
9239                    Integer.toHexString(System.identityHashCode(provider)));
9240                    out.print(' ');
9241                    provider.printComponentShortName(out);
9242            if (count > 1) {
9243                out.print(" ("); out.print(count); out.print(" filters)");
9244            }
9245            out.println();
9246        }
9247
9248        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9249                = new ArrayMap<ComponentName, PackageParser.Provider>();
9250        private int mFlags;
9251    };
9252
9253    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9254            new Comparator<ResolveInfo>() {
9255        public int compare(ResolveInfo r1, ResolveInfo r2) {
9256            int v1 = r1.priority;
9257            int v2 = r2.priority;
9258            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9259            if (v1 != v2) {
9260                return (v1 > v2) ? -1 : 1;
9261            }
9262            v1 = r1.preferredOrder;
9263            v2 = r2.preferredOrder;
9264            if (v1 != v2) {
9265                return (v1 > v2) ? -1 : 1;
9266            }
9267            if (r1.isDefault != r2.isDefault) {
9268                return r1.isDefault ? -1 : 1;
9269            }
9270            v1 = r1.match;
9271            v2 = r2.match;
9272            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9273            if (v1 != v2) {
9274                return (v1 > v2) ? -1 : 1;
9275            }
9276            if (r1.system != r2.system) {
9277                return r1.system ? -1 : 1;
9278            }
9279            return 0;
9280        }
9281    };
9282
9283    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9284            new Comparator<ProviderInfo>() {
9285        public int compare(ProviderInfo p1, ProviderInfo p2) {
9286            final int v1 = p1.initOrder;
9287            final int v2 = p2.initOrder;
9288            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9289        }
9290    };
9291
9292    final void sendPackageBroadcast(final String action, final String pkg,
9293            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9294            final int[] userIds) {
9295        mHandler.post(new Runnable() {
9296            @Override
9297            public void run() {
9298                try {
9299                    final IActivityManager am = ActivityManagerNative.getDefault();
9300                    if (am == null) return;
9301                    final int[] resolvedUserIds;
9302                    if (userIds == null) {
9303                        resolvedUserIds = am.getRunningUserIds();
9304                    } else {
9305                        resolvedUserIds = userIds;
9306                    }
9307                    for (int id : resolvedUserIds) {
9308                        final Intent intent = new Intent(action,
9309                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9310                        if (extras != null) {
9311                            intent.putExtras(extras);
9312                        }
9313                        if (targetPkg != null) {
9314                            intent.setPackage(targetPkg);
9315                        }
9316                        // Modify the UID when posting to other users
9317                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9318                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9319                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9320                            intent.putExtra(Intent.EXTRA_UID, uid);
9321                        }
9322                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9323                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9324                        if (DEBUG_BROADCASTS) {
9325                            RuntimeException here = new RuntimeException("here");
9326                            here.fillInStackTrace();
9327                            Slog.d(TAG, "Sending to user " + id + ": "
9328                                    + intent.toShortString(false, true, false, false)
9329                                    + " " + intent.getExtras(), here);
9330                        }
9331                        am.broadcastIntent(null, intent, null, finishedReceiver,
9332                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9333                                null, finishedReceiver != null, false, id);
9334                    }
9335                } catch (RemoteException ex) {
9336                }
9337            }
9338        });
9339    }
9340
9341    /**
9342     * Check if the external storage media is available. This is true if there
9343     * is a mounted external storage medium or if the external storage is
9344     * emulated.
9345     */
9346    private boolean isExternalMediaAvailable() {
9347        return mMediaMounted || Environment.isExternalStorageEmulated();
9348    }
9349
9350    @Override
9351    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9352        // writer
9353        synchronized (mPackages) {
9354            if (!isExternalMediaAvailable()) {
9355                // If the external storage is no longer mounted at this point,
9356                // the caller may not have been able to delete all of this
9357                // packages files and can not delete any more.  Bail.
9358                return null;
9359            }
9360            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9361            if (lastPackage != null) {
9362                pkgs.remove(lastPackage);
9363            }
9364            if (pkgs.size() > 0) {
9365                return pkgs.get(0);
9366            }
9367        }
9368        return null;
9369    }
9370
9371    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9372        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9373                userId, andCode ? 1 : 0, packageName);
9374        if (mSystemReady) {
9375            msg.sendToTarget();
9376        } else {
9377            if (mPostSystemReadyMessages == null) {
9378                mPostSystemReadyMessages = new ArrayList<>();
9379            }
9380            mPostSystemReadyMessages.add(msg);
9381        }
9382    }
9383
9384    void startCleaningPackages() {
9385        // reader
9386        synchronized (mPackages) {
9387            if (!isExternalMediaAvailable()) {
9388                return;
9389            }
9390            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9391                return;
9392            }
9393        }
9394        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9395        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9396        IActivityManager am = ActivityManagerNative.getDefault();
9397        if (am != null) {
9398            try {
9399                am.startService(null, intent, null, mContext.getOpPackageName(),
9400                        UserHandle.USER_OWNER);
9401            } catch (RemoteException e) {
9402            }
9403        }
9404    }
9405
9406    @Override
9407    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9408            int installFlags, String installerPackageName, VerificationParams verificationParams,
9409            String packageAbiOverride) {
9410        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9411                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9412    }
9413
9414    @Override
9415    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9416            int installFlags, String installerPackageName, VerificationParams verificationParams,
9417            String packageAbiOverride, int userId) {
9418        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9419
9420        final int callingUid = Binder.getCallingUid();
9421        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9422
9423        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9424            try {
9425                if (observer != null) {
9426                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9427                }
9428            } catch (RemoteException re) {
9429            }
9430            return;
9431        }
9432
9433        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9434            installFlags |= PackageManager.INSTALL_FROM_ADB;
9435
9436        } else {
9437            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9438            // about installerPackageName.
9439
9440            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9441            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9442        }
9443
9444        UserHandle user;
9445        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9446            user = UserHandle.ALL;
9447        } else {
9448            user = new UserHandle(userId);
9449        }
9450
9451        // Only system components can circumvent runtime permissions when installing.
9452        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9453                && mContext.checkCallingOrSelfPermission(Manifest.permission
9454                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9455            throw new SecurityException("You need the "
9456                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9457                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9458        }
9459
9460        verificationParams.setInstallerUid(callingUid);
9461
9462        final File originFile = new File(originPath);
9463        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9464
9465        final Message msg = mHandler.obtainMessage(INIT_COPY);
9466        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9467                null, verificationParams, user, packageAbiOverride, null);
9468        mHandler.sendMessage(msg);
9469    }
9470
9471    void installStage(String packageName, File stagedDir, String stagedCid,
9472            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9473            String installerPackageName, int installerUid, UserHandle user) {
9474        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9475                params.referrerUri, installerUid, null);
9476        verifParams.setInstallerUid(installerUid);
9477
9478        final OriginInfo origin;
9479        if (stagedDir != null) {
9480            origin = OriginInfo.fromStagedFile(stagedDir);
9481        } else {
9482            origin = OriginInfo.fromStagedContainer(stagedCid);
9483        }
9484
9485        final Message msg = mHandler.obtainMessage(INIT_COPY);
9486        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9487                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9488                params.grantedRuntimePermissions);
9489        mHandler.sendMessage(msg);
9490    }
9491
9492    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9493        Bundle extras = new Bundle(1);
9494        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9495
9496        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9497                packageName, extras, null, null, new int[] {userId});
9498        try {
9499            IActivityManager am = ActivityManagerNative.getDefault();
9500            final boolean isSystem =
9501                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9502            if (isSystem && am.isUserRunning(userId, false)) {
9503                // The just-installed/enabled app is bundled on the system, so presumed
9504                // to be able to run automatically without needing an explicit launch.
9505                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9506                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9507                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9508                        .setPackage(packageName);
9509                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9510                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9511            }
9512        } catch (RemoteException e) {
9513            // shouldn't happen
9514            Slog.w(TAG, "Unable to bootstrap installed package", e);
9515        }
9516    }
9517
9518    @Override
9519    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9520            int userId) {
9521        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9522        PackageSetting pkgSetting;
9523        final int uid = Binder.getCallingUid();
9524        enforceCrossUserPermission(uid, userId, true, true,
9525                "setApplicationHiddenSetting for user " + userId);
9526
9527        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9528            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9529            return false;
9530        }
9531
9532        long callingId = Binder.clearCallingIdentity();
9533        try {
9534            boolean sendAdded = false;
9535            boolean sendRemoved = false;
9536            // writer
9537            synchronized (mPackages) {
9538                pkgSetting = mSettings.mPackages.get(packageName);
9539                if (pkgSetting == null) {
9540                    return false;
9541                }
9542                if (pkgSetting.getHidden(userId) != hidden) {
9543                    pkgSetting.setHidden(hidden, userId);
9544                    mSettings.writePackageRestrictionsLPr(userId);
9545                    if (hidden) {
9546                        sendRemoved = true;
9547                    } else {
9548                        sendAdded = true;
9549                    }
9550                }
9551            }
9552            if (sendAdded) {
9553                sendPackageAddedForUser(packageName, pkgSetting, userId);
9554                return true;
9555            }
9556            if (sendRemoved) {
9557                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9558                        "hiding pkg");
9559                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9560            }
9561        } finally {
9562            Binder.restoreCallingIdentity(callingId);
9563        }
9564        return false;
9565    }
9566
9567    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9568            int userId) {
9569        final PackageRemovedInfo info = new PackageRemovedInfo();
9570        info.removedPackage = packageName;
9571        info.removedUsers = new int[] {userId};
9572        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9573        info.sendBroadcast(false, false, false);
9574    }
9575
9576    /**
9577     * Returns true if application is not found or there was an error. Otherwise it returns
9578     * the hidden state of the package for the given user.
9579     */
9580    @Override
9581    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9582        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9583        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9584                false, "getApplicationHidden for user " + userId);
9585        PackageSetting pkgSetting;
9586        long callingId = Binder.clearCallingIdentity();
9587        try {
9588            // writer
9589            synchronized (mPackages) {
9590                pkgSetting = mSettings.mPackages.get(packageName);
9591                if (pkgSetting == null) {
9592                    return true;
9593                }
9594                return pkgSetting.getHidden(userId);
9595            }
9596        } finally {
9597            Binder.restoreCallingIdentity(callingId);
9598        }
9599    }
9600
9601    /**
9602     * @hide
9603     */
9604    @Override
9605    public int installExistingPackageAsUser(String packageName, int userId) {
9606        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9607                null);
9608        PackageSetting pkgSetting;
9609        final int uid = Binder.getCallingUid();
9610        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9611                + userId);
9612        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9613            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9614        }
9615
9616        long callingId = Binder.clearCallingIdentity();
9617        try {
9618            boolean sendAdded = false;
9619
9620            // writer
9621            synchronized (mPackages) {
9622                pkgSetting = mSettings.mPackages.get(packageName);
9623                if (pkgSetting == null) {
9624                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9625                }
9626                if (!pkgSetting.getInstalled(userId)) {
9627                    pkgSetting.setInstalled(true, userId);
9628                    pkgSetting.setHidden(false, userId);
9629                    mSettings.writePackageRestrictionsLPr(userId);
9630                    sendAdded = true;
9631                }
9632            }
9633
9634            if (sendAdded) {
9635                sendPackageAddedForUser(packageName, pkgSetting, userId);
9636            }
9637        } finally {
9638            Binder.restoreCallingIdentity(callingId);
9639        }
9640
9641        return PackageManager.INSTALL_SUCCEEDED;
9642    }
9643
9644    boolean isUserRestricted(int userId, String restrictionKey) {
9645        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9646        if (restrictions.getBoolean(restrictionKey, false)) {
9647            Log.w(TAG, "User is restricted: " + restrictionKey);
9648            return true;
9649        }
9650        return false;
9651    }
9652
9653    @Override
9654    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9655        mContext.enforceCallingOrSelfPermission(
9656                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9657                "Only package verification agents can verify applications");
9658
9659        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9660        final PackageVerificationResponse response = new PackageVerificationResponse(
9661                verificationCode, Binder.getCallingUid());
9662        msg.arg1 = id;
9663        msg.obj = response;
9664        mHandler.sendMessage(msg);
9665    }
9666
9667    @Override
9668    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9669            long millisecondsToDelay) {
9670        mContext.enforceCallingOrSelfPermission(
9671                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9672                "Only package verification agents can extend verification timeouts");
9673
9674        final PackageVerificationState state = mPendingVerification.get(id);
9675        final PackageVerificationResponse response = new PackageVerificationResponse(
9676                verificationCodeAtTimeout, Binder.getCallingUid());
9677
9678        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9679            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9680        }
9681        if (millisecondsToDelay < 0) {
9682            millisecondsToDelay = 0;
9683        }
9684        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9685                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9686            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9687        }
9688
9689        if ((state != null) && !state.timeoutExtended()) {
9690            state.extendTimeout();
9691
9692            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9693            msg.arg1 = id;
9694            msg.obj = response;
9695            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9696        }
9697    }
9698
9699    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9700            int verificationCode, UserHandle user) {
9701        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9702        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9703        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9704        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9705        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9706
9707        mContext.sendBroadcastAsUser(intent, user,
9708                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9709    }
9710
9711    private ComponentName matchComponentForVerifier(String packageName,
9712            List<ResolveInfo> receivers) {
9713        ActivityInfo targetReceiver = null;
9714
9715        final int NR = receivers.size();
9716        for (int i = 0; i < NR; i++) {
9717            final ResolveInfo info = receivers.get(i);
9718            if (info.activityInfo == null) {
9719                continue;
9720            }
9721
9722            if (packageName.equals(info.activityInfo.packageName)) {
9723                targetReceiver = info.activityInfo;
9724                break;
9725            }
9726        }
9727
9728        if (targetReceiver == null) {
9729            return null;
9730        }
9731
9732        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9733    }
9734
9735    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9736            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9737        if (pkgInfo.verifiers.length == 0) {
9738            return null;
9739        }
9740
9741        final int N = pkgInfo.verifiers.length;
9742        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9743        for (int i = 0; i < N; i++) {
9744            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9745
9746            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9747                    receivers);
9748            if (comp == null) {
9749                continue;
9750            }
9751
9752            final int verifierUid = getUidForVerifier(verifierInfo);
9753            if (verifierUid == -1) {
9754                continue;
9755            }
9756
9757            if (DEBUG_VERIFY) {
9758                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9759                        + " with the correct signature");
9760            }
9761            sufficientVerifiers.add(comp);
9762            verificationState.addSufficientVerifier(verifierUid);
9763        }
9764
9765        return sufficientVerifiers;
9766    }
9767
9768    private int getUidForVerifier(VerifierInfo verifierInfo) {
9769        synchronized (mPackages) {
9770            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9771            if (pkg == null) {
9772                return -1;
9773            } else if (pkg.mSignatures.length != 1) {
9774                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9775                        + " has more than one signature; ignoring");
9776                return -1;
9777            }
9778
9779            /*
9780             * If the public key of the package's signature does not match
9781             * our expected public key, then this is a different package and
9782             * we should skip.
9783             */
9784
9785            final byte[] expectedPublicKey;
9786            try {
9787                final Signature verifierSig = pkg.mSignatures[0];
9788                final PublicKey publicKey = verifierSig.getPublicKey();
9789                expectedPublicKey = publicKey.getEncoded();
9790            } catch (CertificateException e) {
9791                return -1;
9792            }
9793
9794            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9795
9796            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9797                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9798                        + " does not have the expected public key; ignoring");
9799                return -1;
9800            }
9801
9802            return pkg.applicationInfo.uid;
9803        }
9804    }
9805
9806    @Override
9807    public void finishPackageInstall(int token) {
9808        enforceSystemOrRoot("Only the system is allowed to finish installs");
9809
9810        if (DEBUG_INSTALL) {
9811            Slog.v(TAG, "BM finishing package install for " + token);
9812        }
9813
9814        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9815        mHandler.sendMessage(msg);
9816    }
9817
9818    /**
9819     * Get the verification agent timeout.
9820     *
9821     * @return verification timeout in milliseconds
9822     */
9823    private long getVerificationTimeout() {
9824        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9825                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9826                DEFAULT_VERIFICATION_TIMEOUT);
9827    }
9828
9829    /**
9830     * Get the default verification agent response code.
9831     *
9832     * @return default verification response code
9833     */
9834    private int getDefaultVerificationResponse() {
9835        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9836                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9837                DEFAULT_VERIFICATION_RESPONSE);
9838    }
9839
9840    /**
9841     * Check whether or not package verification has been enabled.
9842     *
9843     * @return true if verification should be performed
9844     */
9845    private boolean isVerificationEnabled(int userId, int installFlags) {
9846        if (!DEFAULT_VERIFY_ENABLE) {
9847            return false;
9848        }
9849
9850        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9851
9852        // Check if installing from ADB
9853        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9854            // Do not run verification in a test harness environment
9855            if (ActivityManager.isRunningInTestHarness()) {
9856                return false;
9857            }
9858            if (ensureVerifyAppsEnabled) {
9859                return true;
9860            }
9861            // Check if the developer does not want package verification for ADB installs
9862            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9863                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9864                return false;
9865            }
9866        }
9867
9868        if (ensureVerifyAppsEnabled) {
9869            return true;
9870        }
9871
9872        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9873                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9874    }
9875
9876    @Override
9877    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9878            throws RemoteException {
9879        mContext.enforceCallingOrSelfPermission(
9880                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9881                "Only intentfilter verification agents can verify applications");
9882
9883        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9884        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9885                Binder.getCallingUid(), verificationCode, failedDomains);
9886        msg.arg1 = id;
9887        msg.obj = response;
9888        mHandler.sendMessage(msg);
9889    }
9890
9891    @Override
9892    public int getIntentVerificationStatus(String packageName, int userId) {
9893        synchronized (mPackages) {
9894            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9895        }
9896    }
9897
9898    @Override
9899    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9900        mContext.enforceCallingOrSelfPermission(
9901                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9902
9903        boolean result = false;
9904        synchronized (mPackages) {
9905            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9906        }
9907        if (result) {
9908            scheduleWritePackageRestrictionsLocked(userId);
9909        }
9910        return result;
9911    }
9912
9913    @Override
9914    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9915        synchronized (mPackages) {
9916            return mSettings.getIntentFilterVerificationsLPr(packageName);
9917        }
9918    }
9919
9920    @Override
9921    public List<IntentFilter> getAllIntentFilters(String packageName) {
9922        if (TextUtils.isEmpty(packageName)) {
9923            return Collections.<IntentFilter>emptyList();
9924        }
9925        synchronized (mPackages) {
9926            PackageParser.Package pkg = mPackages.get(packageName);
9927            if (pkg == null || pkg.activities == null) {
9928                return Collections.<IntentFilter>emptyList();
9929            }
9930            final int count = pkg.activities.size();
9931            ArrayList<IntentFilter> result = new ArrayList<>();
9932            for (int n=0; n<count; n++) {
9933                PackageParser.Activity activity = pkg.activities.get(n);
9934                if (activity.intents != null || activity.intents.size() > 0) {
9935                    result.addAll(activity.intents);
9936                }
9937            }
9938            return result;
9939        }
9940    }
9941
9942    @Override
9943    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9944        mContext.enforceCallingOrSelfPermission(
9945                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9946
9947        synchronized (mPackages) {
9948            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9949            if (packageName != null) {
9950                result |= updateIntentVerificationStatus(packageName,
9951                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9952                        userId);
9953                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9954                        packageName, userId);
9955            }
9956            return result;
9957        }
9958    }
9959
9960    @Override
9961    public String getDefaultBrowserPackageName(int userId) {
9962        synchronized (mPackages) {
9963            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9964        }
9965    }
9966
9967    /**
9968     * Get the "allow unknown sources" setting.
9969     *
9970     * @return the current "allow unknown sources" setting
9971     */
9972    private int getUnknownSourcesSettings() {
9973        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9974                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9975                -1);
9976    }
9977
9978    @Override
9979    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9980        final int uid = Binder.getCallingUid();
9981        // writer
9982        synchronized (mPackages) {
9983            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9984            if (targetPackageSetting == null) {
9985                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9986            }
9987
9988            PackageSetting installerPackageSetting;
9989            if (installerPackageName != null) {
9990                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9991                if (installerPackageSetting == null) {
9992                    throw new IllegalArgumentException("Unknown installer package: "
9993                            + installerPackageName);
9994                }
9995            } else {
9996                installerPackageSetting = null;
9997            }
9998
9999            Signature[] callerSignature;
10000            Object obj = mSettings.getUserIdLPr(uid);
10001            if (obj != null) {
10002                if (obj instanceof SharedUserSetting) {
10003                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10004                } else if (obj instanceof PackageSetting) {
10005                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10006                } else {
10007                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10008                }
10009            } else {
10010                throw new SecurityException("Unknown calling uid " + uid);
10011            }
10012
10013            // Verify: can't set installerPackageName to a package that is
10014            // not signed with the same cert as the caller.
10015            if (installerPackageSetting != null) {
10016                if (compareSignatures(callerSignature,
10017                        installerPackageSetting.signatures.mSignatures)
10018                        != PackageManager.SIGNATURE_MATCH) {
10019                    throw new SecurityException(
10020                            "Caller does not have same cert as new installer package "
10021                            + installerPackageName);
10022                }
10023            }
10024
10025            // Verify: if target already has an installer package, it must
10026            // be signed with the same cert as the caller.
10027            if (targetPackageSetting.installerPackageName != null) {
10028                PackageSetting setting = mSettings.mPackages.get(
10029                        targetPackageSetting.installerPackageName);
10030                // If the currently set package isn't valid, then it's always
10031                // okay to change it.
10032                if (setting != null) {
10033                    if (compareSignatures(callerSignature,
10034                            setting.signatures.mSignatures)
10035                            != PackageManager.SIGNATURE_MATCH) {
10036                        throw new SecurityException(
10037                                "Caller does not have same cert as old installer package "
10038                                + targetPackageSetting.installerPackageName);
10039                    }
10040                }
10041            }
10042
10043            // Okay!
10044            targetPackageSetting.installerPackageName = installerPackageName;
10045            scheduleWriteSettingsLocked();
10046        }
10047    }
10048
10049    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10050        // Queue up an async operation since the package installation may take a little while.
10051        mHandler.post(new Runnable() {
10052            public void run() {
10053                mHandler.removeCallbacks(this);
10054                 // Result object to be returned
10055                PackageInstalledInfo res = new PackageInstalledInfo();
10056                res.returnCode = currentStatus;
10057                res.uid = -1;
10058                res.pkg = null;
10059                res.removedInfo = new PackageRemovedInfo();
10060                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10061                    args.doPreInstall(res.returnCode);
10062                    synchronized (mInstallLock) {
10063                        installPackageLI(args, res);
10064                    }
10065                    args.doPostInstall(res.returnCode, res.uid);
10066                }
10067
10068                // A restore should be performed at this point if (a) the install
10069                // succeeded, (b) the operation is not an update, and (c) the new
10070                // package has not opted out of backup participation.
10071                final boolean update = res.removedInfo.removedPackage != null;
10072                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10073                boolean doRestore = !update
10074                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10075
10076                // Set up the post-install work request bookkeeping.  This will be used
10077                // and cleaned up by the post-install event handling regardless of whether
10078                // there's a restore pass performed.  Token values are >= 1.
10079                int token;
10080                if (mNextInstallToken < 0) mNextInstallToken = 1;
10081                token = mNextInstallToken++;
10082
10083                PostInstallData data = new PostInstallData(args, res);
10084                mRunningInstalls.put(token, data);
10085                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10086
10087                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10088                    // Pass responsibility to the Backup Manager.  It will perform a
10089                    // restore if appropriate, then pass responsibility back to the
10090                    // Package Manager to run the post-install observer callbacks
10091                    // and broadcasts.
10092                    IBackupManager bm = IBackupManager.Stub.asInterface(
10093                            ServiceManager.getService(Context.BACKUP_SERVICE));
10094                    if (bm != null) {
10095                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10096                                + " to BM for possible restore");
10097                        try {
10098                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10099                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10100                            } else {
10101                                doRestore = false;
10102                            }
10103                        } catch (RemoteException e) {
10104                            // can't happen; the backup manager is local
10105                        } catch (Exception e) {
10106                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10107                            doRestore = false;
10108                        }
10109                    } else {
10110                        Slog.e(TAG, "Backup Manager not found!");
10111                        doRestore = false;
10112                    }
10113                }
10114
10115                if (!doRestore) {
10116                    // No restore possible, or the Backup Manager was mysteriously not
10117                    // available -- just fire the post-install work request directly.
10118                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10119                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10120                    mHandler.sendMessage(msg);
10121                }
10122            }
10123        });
10124    }
10125
10126    private abstract class HandlerParams {
10127        private static final int MAX_RETRIES = 4;
10128
10129        /**
10130         * Number of times startCopy() has been attempted and had a non-fatal
10131         * error.
10132         */
10133        private int mRetries = 0;
10134
10135        /** User handle for the user requesting the information or installation. */
10136        private final UserHandle mUser;
10137
10138        HandlerParams(UserHandle user) {
10139            mUser = user;
10140        }
10141
10142        UserHandle getUser() {
10143            return mUser;
10144        }
10145
10146        final boolean startCopy() {
10147            boolean res;
10148            try {
10149                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10150
10151                if (++mRetries > MAX_RETRIES) {
10152                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10153                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10154                    handleServiceError();
10155                    return false;
10156                } else {
10157                    handleStartCopy();
10158                    res = true;
10159                }
10160            } catch (RemoteException e) {
10161                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10162                mHandler.sendEmptyMessage(MCS_RECONNECT);
10163                res = false;
10164            }
10165            handleReturnCode();
10166            return res;
10167        }
10168
10169        final void serviceError() {
10170            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10171            handleServiceError();
10172            handleReturnCode();
10173        }
10174
10175        abstract void handleStartCopy() throws RemoteException;
10176        abstract void handleServiceError();
10177        abstract void handleReturnCode();
10178    }
10179
10180    class MeasureParams extends HandlerParams {
10181        private final PackageStats mStats;
10182        private boolean mSuccess;
10183
10184        private final IPackageStatsObserver mObserver;
10185
10186        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10187            super(new UserHandle(stats.userHandle));
10188            mObserver = observer;
10189            mStats = stats;
10190        }
10191
10192        @Override
10193        public String toString() {
10194            return "MeasureParams{"
10195                + Integer.toHexString(System.identityHashCode(this))
10196                + " " + mStats.packageName + "}";
10197        }
10198
10199        @Override
10200        void handleStartCopy() throws RemoteException {
10201            synchronized (mInstallLock) {
10202                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10203            }
10204
10205            if (mSuccess) {
10206                final boolean mounted;
10207                if (Environment.isExternalStorageEmulated()) {
10208                    mounted = true;
10209                } else {
10210                    final String status = Environment.getExternalStorageState();
10211                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10212                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10213                }
10214
10215                if (mounted) {
10216                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10217
10218                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10219                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10220
10221                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10222                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10223
10224                    // Always subtract cache size, since it's a subdirectory
10225                    mStats.externalDataSize -= mStats.externalCacheSize;
10226
10227                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10228                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10229
10230                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10231                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10232                }
10233            }
10234        }
10235
10236        @Override
10237        void handleReturnCode() {
10238            if (mObserver != null) {
10239                try {
10240                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10241                } catch (RemoteException e) {
10242                    Slog.i(TAG, "Observer no longer exists.");
10243                }
10244            }
10245        }
10246
10247        @Override
10248        void handleServiceError() {
10249            Slog.e(TAG, "Could not measure application " + mStats.packageName
10250                            + " external storage");
10251        }
10252    }
10253
10254    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10255            throws RemoteException {
10256        long result = 0;
10257        for (File path : paths) {
10258            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10259        }
10260        return result;
10261    }
10262
10263    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10264        for (File path : paths) {
10265            try {
10266                mcs.clearDirectory(path.getAbsolutePath());
10267            } catch (RemoteException e) {
10268            }
10269        }
10270    }
10271
10272    static class OriginInfo {
10273        /**
10274         * Location where install is coming from, before it has been
10275         * copied/renamed into place. This could be a single monolithic APK
10276         * file, or a cluster directory. This location may be untrusted.
10277         */
10278        final File file;
10279        final String cid;
10280
10281        /**
10282         * Flag indicating that {@link #file} or {@link #cid} has already been
10283         * staged, meaning downstream users don't need to defensively copy the
10284         * contents.
10285         */
10286        final boolean staged;
10287
10288        /**
10289         * Flag indicating that {@link #file} or {@link #cid} is an already
10290         * installed app that is being moved.
10291         */
10292        final boolean existing;
10293
10294        final String resolvedPath;
10295        final File resolvedFile;
10296
10297        static OriginInfo fromNothing() {
10298            return new OriginInfo(null, null, false, false);
10299        }
10300
10301        static OriginInfo fromUntrustedFile(File file) {
10302            return new OriginInfo(file, null, false, false);
10303        }
10304
10305        static OriginInfo fromExistingFile(File file) {
10306            return new OriginInfo(file, null, false, true);
10307        }
10308
10309        static OriginInfo fromStagedFile(File file) {
10310            return new OriginInfo(file, null, true, false);
10311        }
10312
10313        static OriginInfo fromStagedContainer(String cid) {
10314            return new OriginInfo(null, cid, true, false);
10315        }
10316
10317        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10318            this.file = file;
10319            this.cid = cid;
10320            this.staged = staged;
10321            this.existing = existing;
10322
10323            if (cid != null) {
10324                resolvedPath = PackageHelper.getSdDir(cid);
10325                resolvedFile = new File(resolvedPath);
10326            } else if (file != null) {
10327                resolvedPath = file.getAbsolutePath();
10328                resolvedFile = file;
10329            } else {
10330                resolvedPath = null;
10331                resolvedFile = null;
10332            }
10333        }
10334    }
10335
10336    class MoveInfo {
10337        final int moveId;
10338        final String fromUuid;
10339        final String toUuid;
10340        final String packageName;
10341        final String dataAppName;
10342        final int appId;
10343        final String seinfo;
10344
10345        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10346                String dataAppName, int appId, String seinfo) {
10347            this.moveId = moveId;
10348            this.fromUuid = fromUuid;
10349            this.toUuid = toUuid;
10350            this.packageName = packageName;
10351            this.dataAppName = dataAppName;
10352            this.appId = appId;
10353            this.seinfo = seinfo;
10354        }
10355    }
10356
10357    class InstallParams extends HandlerParams {
10358        final OriginInfo origin;
10359        final MoveInfo move;
10360        final IPackageInstallObserver2 observer;
10361        int installFlags;
10362        final String installerPackageName;
10363        final String volumeUuid;
10364        final VerificationParams verificationParams;
10365        private InstallArgs mArgs;
10366        private int mRet;
10367        final String packageAbiOverride;
10368        final String[] grantedRuntimePermissions;
10369
10370
10371        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10372                int installFlags, String installerPackageName, String volumeUuid,
10373                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10374                String[] grantedPermissions) {
10375            super(user);
10376            this.origin = origin;
10377            this.move = move;
10378            this.observer = observer;
10379            this.installFlags = installFlags;
10380            this.installerPackageName = installerPackageName;
10381            this.volumeUuid = volumeUuid;
10382            this.verificationParams = verificationParams;
10383            this.packageAbiOverride = packageAbiOverride;
10384            this.grantedRuntimePermissions = grantedPermissions;
10385        }
10386
10387        @Override
10388        public String toString() {
10389            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10390                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10391        }
10392
10393        public ManifestDigest getManifestDigest() {
10394            if (verificationParams == null) {
10395                return null;
10396            }
10397            return verificationParams.getManifestDigest();
10398        }
10399
10400        private int installLocationPolicy(PackageInfoLite pkgLite) {
10401            String packageName = pkgLite.packageName;
10402            int installLocation = pkgLite.installLocation;
10403            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10404            // reader
10405            synchronized (mPackages) {
10406                PackageParser.Package pkg = mPackages.get(packageName);
10407                if (pkg != null) {
10408                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10409                        // Check for downgrading.
10410                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10411                            try {
10412                                checkDowngrade(pkg, pkgLite);
10413                            } catch (PackageManagerException e) {
10414                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10415                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10416                            }
10417                        }
10418                        // Check for updated system application.
10419                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10420                            if (onSd) {
10421                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10422                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10423                            }
10424                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10425                        } else {
10426                            if (onSd) {
10427                                // Install flag overrides everything.
10428                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10429                            }
10430                            // If current upgrade specifies particular preference
10431                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10432                                // Application explicitly specified internal.
10433                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10434                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10435                                // App explictly prefers external. Let policy decide
10436                            } else {
10437                                // Prefer previous location
10438                                if (isExternal(pkg)) {
10439                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10440                                }
10441                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10442                            }
10443                        }
10444                    } else {
10445                        // Invalid install. Return error code
10446                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10447                    }
10448                }
10449            }
10450            // All the special cases have been taken care of.
10451            // Return result based on recommended install location.
10452            if (onSd) {
10453                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10454            }
10455            return pkgLite.recommendedInstallLocation;
10456        }
10457
10458        /*
10459         * Invoke remote method to get package information and install
10460         * location values. Override install location based on default
10461         * policy if needed and then create install arguments based
10462         * on the install location.
10463         */
10464        public void handleStartCopy() throws RemoteException {
10465            int ret = PackageManager.INSTALL_SUCCEEDED;
10466
10467            // If we're already staged, we've firmly committed to an install location
10468            if (origin.staged) {
10469                if (origin.file != null) {
10470                    installFlags |= PackageManager.INSTALL_INTERNAL;
10471                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10472                } else if (origin.cid != null) {
10473                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10474                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10475                } else {
10476                    throw new IllegalStateException("Invalid stage location");
10477                }
10478            }
10479
10480            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10481            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10482
10483            PackageInfoLite pkgLite = null;
10484
10485            if (onInt && onSd) {
10486                // Check if both bits are set.
10487                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10488                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10489            } else {
10490                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10491                        packageAbiOverride);
10492
10493                /*
10494                 * If we have too little free space, try to free cache
10495                 * before giving up.
10496                 */
10497                if (!origin.staged && pkgLite.recommendedInstallLocation
10498                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10499                    // TODO: focus freeing disk space on the target device
10500                    final StorageManager storage = StorageManager.from(mContext);
10501                    final long lowThreshold = storage.getStorageLowBytes(
10502                            Environment.getDataDirectory());
10503
10504                    final long sizeBytes = mContainerService.calculateInstalledSize(
10505                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10506
10507                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10508                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10509                                installFlags, packageAbiOverride);
10510                    }
10511
10512                    /*
10513                     * The cache free must have deleted the file we
10514                     * downloaded to install.
10515                     *
10516                     * TODO: fix the "freeCache" call to not delete
10517                     *       the file we care about.
10518                     */
10519                    if (pkgLite.recommendedInstallLocation
10520                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10521                        pkgLite.recommendedInstallLocation
10522                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10523                    }
10524                }
10525            }
10526
10527            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10528                int loc = pkgLite.recommendedInstallLocation;
10529                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10530                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10531                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10532                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10533                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10534                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10535                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10536                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10537                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10538                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10539                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10540                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10541                } else {
10542                    // Override with defaults if needed.
10543                    loc = installLocationPolicy(pkgLite);
10544                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10545                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10546                    } else if (!onSd && !onInt) {
10547                        // Override install location with flags
10548                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10549                            // Set the flag to install on external media.
10550                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10551                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10552                        } else {
10553                            // Make sure the flag for installing on external
10554                            // media is unset
10555                            installFlags |= PackageManager.INSTALL_INTERNAL;
10556                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10557                        }
10558                    }
10559                }
10560            }
10561
10562            final InstallArgs args = createInstallArgs(this);
10563            mArgs = args;
10564
10565            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10566                 /*
10567                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10568                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10569                 */
10570                int userIdentifier = getUser().getIdentifier();
10571                if (userIdentifier == UserHandle.USER_ALL
10572                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10573                    userIdentifier = UserHandle.USER_OWNER;
10574                }
10575
10576                /*
10577                 * Determine if we have any installed package verifiers. If we
10578                 * do, then we'll defer to them to verify the packages.
10579                 */
10580                final int requiredUid = mRequiredVerifierPackage == null ? -1
10581                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10582                if (!origin.existing && requiredUid != -1
10583                        && isVerificationEnabled(userIdentifier, installFlags)) {
10584                    final Intent verification = new Intent(
10585                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10586                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10587                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10588                            PACKAGE_MIME_TYPE);
10589                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10590
10591                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10592                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10593                            0 /* TODO: Which userId? */);
10594
10595                    if (DEBUG_VERIFY) {
10596                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10597                                + verification.toString() + " with " + pkgLite.verifiers.length
10598                                + " optional verifiers");
10599                    }
10600
10601                    final int verificationId = mPendingVerificationToken++;
10602
10603                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10604
10605                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10606                            installerPackageName);
10607
10608                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10609                            installFlags);
10610
10611                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10612                            pkgLite.packageName);
10613
10614                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10615                            pkgLite.versionCode);
10616
10617                    if (verificationParams != null) {
10618                        if (verificationParams.getVerificationURI() != null) {
10619                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10620                                 verificationParams.getVerificationURI());
10621                        }
10622                        if (verificationParams.getOriginatingURI() != null) {
10623                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10624                                  verificationParams.getOriginatingURI());
10625                        }
10626                        if (verificationParams.getReferrer() != null) {
10627                            verification.putExtra(Intent.EXTRA_REFERRER,
10628                                  verificationParams.getReferrer());
10629                        }
10630                        if (verificationParams.getOriginatingUid() >= 0) {
10631                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10632                                  verificationParams.getOriginatingUid());
10633                        }
10634                        if (verificationParams.getInstallerUid() >= 0) {
10635                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10636                                  verificationParams.getInstallerUid());
10637                        }
10638                    }
10639
10640                    final PackageVerificationState verificationState = new PackageVerificationState(
10641                            requiredUid, args);
10642
10643                    mPendingVerification.append(verificationId, verificationState);
10644
10645                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10646                            receivers, verificationState);
10647
10648                    // Apps installed for "all" users use the device owner to verify the app
10649                    UserHandle verifierUser = getUser();
10650                    if (verifierUser == UserHandle.ALL) {
10651                        verifierUser = UserHandle.OWNER;
10652                    }
10653
10654                    /*
10655                     * If any sufficient verifiers were listed in the package
10656                     * manifest, attempt to ask them.
10657                     */
10658                    if (sufficientVerifiers != null) {
10659                        final int N = sufficientVerifiers.size();
10660                        if (N == 0) {
10661                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10662                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10663                        } else {
10664                            for (int i = 0; i < N; i++) {
10665                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10666
10667                                final Intent sufficientIntent = new Intent(verification);
10668                                sufficientIntent.setComponent(verifierComponent);
10669                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10670                            }
10671                        }
10672                    }
10673
10674                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10675                            mRequiredVerifierPackage, receivers);
10676                    if (ret == PackageManager.INSTALL_SUCCEEDED
10677                            && mRequiredVerifierPackage != null) {
10678                        /*
10679                         * Send the intent to the required verification agent,
10680                         * but only start the verification timeout after the
10681                         * target BroadcastReceivers have run.
10682                         */
10683                        verification.setComponent(requiredVerifierComponent);
10684                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10685                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10686                                new BroadcastReceiver() {
10687                                    @Override
10688                                    public void onReceive(Context context, Intent intent) {
10689                                        final Message msg = mHandler
10690                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10691                                        msg.arg1 = verificationId;
10692                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10693                                    }
10694                                }, null, 0, null, null);
10695
10696                        /*
10697                         * We don't want the copy to proceed until verification
10698                         * succeeds, so null out this field.
10699                         */
10700                        mArgs = null;
10701                    }
10702                } else {
10703                    /*
10704                     * No package verification is enabled, so immediately start
10705                     * the remote call to initiate copy using temporary file.
10706                     */
10707                    ret = args.copyApk(mContainerService, true);
10708                }
10709            }
10710
10711            mRet = ret;
10712        }
10713
10714        @Override
10715        void handleReturnCode() {
10716            // If mArgs is null, then MCS couldn't be reached. When it
10717            // reconnects, it will try again to install. At that point, this
10718            // will succeed.
10719            if (mArgs != null) {
10720                processPendingInstall(mArgs, mRet);
10721            }
10722        }
10723
10724        @Override
10725        void handleServiceError() {
10726            mArgs = createInstallArgs(this);
10727            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10728        }
10729
10730        public boolean isForwardLocked() {
10731            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10732        }
10733    }
10734
10735    /**
10736     * Used during creation of InstallArgs
10737     *
10738     * @param installFlags package installation flags
10739     * @return true if should be installed on external storage
10740     */
10741    private static boolean installOnExternalAsec(int installFlags) {
10742        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10743            return false;
10744        }
10745        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10746            return true;
10747        }
10748        return false;
10749    }
10750
10751    /**
10752     * Used during creation of InstallArgs
10753     *
10754     * @param installFlags package installation flags
10755     * @return true if should be installed as forward locked
10756     */
10757    private static boolean installForwardLocked(int installFlags) {
10758        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10759    }
10760
10761    private InstallArgs createInstallArgs(InstallParams params) {
10762        if (params.move != null) {
10763            return new MoveInstallArgs(params);
10764        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10765            return new AsecInstallArgs(params);
10766        } else {
10767            return new FileInstallArgs(params);
10768        }
10769    }
10770
10771    /**
10772     * Create args that describe an existing installed package. Typically used
10773     * when cleaning up old installs, or used as a move source.
10774     */
10775    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10776            String resourcePath, String[] instructionSets) {
10777        final boolean isInAsec;
10778        if (installOnExternalAsec(installFlags)) {
10779            /* Apps on SD card are always in ASEC containers. */
10780            isInAsec = true;
10781        } else if (installForwardLocked(installFlags)
10782                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10783            /*
10784             * Forward-locked apps are only in ASEC containers if they're the
10785             * new style
10786             */
10787            isInAsec = true;
10788        } else {
10789            isInAsec = false;
10790        }
10791
10792        if (isInAsec) {
10793            return new AsecInstallArgs(codePath, instructionSets,
10794                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10795        } else {
10796            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10797        }
10798    }
10799
10800    static abstract class InstallArgs {
10801        /** @see InstallParams#origin */
10802        final OriginInfo origin;
10803        /** @see InstallParams#move */
10804        final MoveInfo move;
10805
10806        final IPackageInstallObserver2 observer;
10807        // Always refers to PackageManager flags only
10808        final int installFlags;
10809        final String installerPackageName;
10810        final String volumeUuid;
10811        final ManifestDigest manifestDigest;
10812        final UserHandle user;
10813        final String abiOverride;
10814        final String[] installGrantPermissions;
10815
10816        // The list of instruction sets supported by this app. This is currently
10817        // only used during the rmdex() phase to clean up resources. We can get rid of this
10818        // if we move dex files under the common app path.
10819        /* nullable */ String[] instructionSets;
10820
10821        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10822                int installFlags, String installerPackageName, String volumeUuid,
10823                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10824                String abiOverride, String[] installGrantPermissions) {
10825            this.origin = origin;
10826            this.move = move;
10827            this.installFlags = installFlags;
10828            this.observer = observer;
10829            this.installerPackageName = installerPackageName;
10830            this.volumeUuid = volumeUuid;
10831            this.manifestDigest = manifestDigest;
10832            this.user = user;
10833            this.instructionSets = instructionSets;
10834            this.abiOverride = abiOverride;
10835            this.installGrantPermissions = installGrantPermissions;
10836        }
10837
10838        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10839        abstract int doPreInstall(int status);
10840
10841        /**
10842         * Rename package into final resting place. All paths on the given
10843         * scanned package should be updated to reflect the rename.
10844         */
10845        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10846        abstract int doPostInstall(int status, int uid);
10847
10848        /** @see PackageSettingBase#codePathString */
10849        abstract String getCodePath();
10850        /** @see PackageSettingBase#resourcePathString */
10851        abstract String getResourcePath();
10852
10853        // Need installer lock especially for dex file removal.
10854        abstract void cleanUpResourcesLI();
10855        abstract boolean doPostDeleteLI(boolean delete);
10856
10857        /**
10858         * Called before the source arguments are copied. This is used mostly
10859         * for MoveParams when it needs to read the source file to put it in the
10860         * destination.
10861         */
10862        int doPreCopy() {
10863            return PackageManager.INSTALL_SUCCEEDED;
10864        }
10865
10866        /**
10867         * Called after the source arguments are copied. This is used mostly for
10868         * MoveParams when it needs to read the source file to put it in the
10869         * destination.
10870         *
10871         * @return
10872         */
10873        int doPostCopy(int uid) {
10874            return PackageManager.INSTALL_SUCCEEDED;
10875        }
10876
10877        protected boolean isFwdLocked() {
10878            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10879        }
10880
10881        protected boolean isExternalAsec() {
10882            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10883        }
10884
10885        UserHandle getUser() {
10886            return user;
10887        }
10888    }
10889
10890    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10891        if (!allCodePaths.isEmpty()) {
10892            if (instructionSets == null) {
10893                throw new IllegalStateException("instructionSet == null");
10894            }
10895            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10896            for (String codePath : allCodePaths) {
10897                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10898                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10899                    if (retCode < 0) {
10900                        Slog.w(TAG, "Couldn't remove dex file for package: "
10901                                + " at location " + codePath + ", retcode=" + retCode);
10902                        // we don't consider this to be a failure of the core package deletion
10903                    }
10904                }
10905            }
10906        }
10907    }
10908
10909    /**
10910     * Logic to handle installation of non-ASEC applications, including copying
10911     * and renaming logic.
10912     */
10913    class FileInstallArgs extends InstallArgs {
10914        private File codeFile;
10915        private File resourceFile;
10916
10917        // Example topology:
10918        // /data/app/com.example/base.apk
10919        // /data/app/com.example/split_foo.apk
10920        // /data/app/com.example/lib/arm/libfoo.so
10921        // /data/app/com.example/lib/arm64/libfoo.so
10922        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10923
10924        /** New install */
10925        FileInstallArgs(InstallParams params) {
10926            super(params.origin, params.move, params.observer, params.installFlags,
10927                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10928                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
10929                    params.grantedRuntimePermissions);
10930            if (isFwdLocked()) {
10931                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10932            }
10933        }
10934
10935        /** Existing install */
10936        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10937            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10938                    null, null);
10939            this.codeFile = (codePath != null) ? new File(codePath) : null;
10940            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10941        }
10942
10943        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10944            if (origin.staged) {
10945                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10946                codeFile = origin.file;
10947                resourceFile = origin.file;
10948                return PackageManager.INSTALL_SUCCEEDED;
10949            }
10950
10951            try {
10952                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10953                codeFile = tempDir;
10954                resourceFile = tempDir;
10955            } catch (IOException e) {
10956                Slog.w(TAG, "Failed to create copy file: " + e);
10957                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10958            }
10959
10960            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10961                @Override
10962                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10963                    if (!FileUtils.isValidExtFilename(name)) {
10964                        throw new IllegalArgumentException("Invalid filename: " + name);
10965                    }
10966                    try {
10967                        final File file = new File(codeFile, name);
10968                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10969                                O_RDWR | O_CREAT, 0644);
10970                        Os.chmod(file.getAbsolutePath(), 0644);
10971                        return new ParcelFileDescriptor(fd);
10972                    } catch (ErrnoException e) {
10973                        throw new RemoteException("Failed to open: " + e.getMessage());
10974                    }
10975                }
10976            };
10977
10978            int ret = PackageManager.INSTALL_SUCCEEDED;
10979            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10980            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10981                Slog.e(TAG, "Failed to copy package");
10982                return ret;
10983            }
10984
10985            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10986            NativeLibraryHelper.Handle handle = null;
10987            try {
10988                handle = NativeLibraryHelper.Handle.create(codeFile);
10989                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10990                        abiOverride);
10991            } catch (IOException e) {
10992                Slog.e(TAG, "Copying native libraries failed", e);
10993                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10994            } finally {
10995                IoUtils.closeQuietly(handle);
10996            }
10997
10998            return ret;
10999        }
11000
11001        int doPreInstall(int status) {
11002            if (status != PackageManager.INSTALL_SUCCEEDED) {
11003                cleanUp();
11004            }
11005            return status;
11006        }
11007
11008        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11009            if (status != PackageManager.INSTALL_SUCCEEDED) {
11010                cleanUp();
11011                return false;
11012            }
11013
11014            final File targetDir = codeFile.getParentFile();
11015            final File beforeCodeFile = codeFile;
11016            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11017
11018            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11019            try {
11020                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11021            } catch (ErrnoException e) {
11022                Slog.w(TAG, "Failed to rename", e);
11023                return false;
11024            }
11025
11026            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11027                Slog.w(TAG, "Failed to restorecon");
11028                return false;
11029            }
11030
11031            // Reflect the rename internally
11032            codeFile = afterCodeFile;
11033            resourceFile = afterCodeFile;
11034
11035            // Reflect the rename in scanned details
11036            pkg.codePath = afterCodeFile.getAbsolutePath();
11037            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11038                    pkg.baseCodePath);
11039            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11040                    pkg.splitCodePaths);
11041
11042            // Reflect the rename in app info
11043            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11044            pkg.applicationInfo.setCodePath(pkg.codePath);
11045            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11046            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11047            pkg.applicationInfo.setResourcePath(pkg.codePath);
11048            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11049            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11050
11051            return true;
11052        }
11053
11054        int doPostInstall(int status, int uid) {
11055            if (status != PackageManager.INSTALL_SUCCEEDED) {
11056                cleanUp();
11057            }
11058            return status;
11059        }
11060
11061        @Override
11062        String getCodePath() {
11063            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11064        }
11065
11066        @Override
11067        String getResourcePath() {
11068            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11069        }
11070
11071        private boolean cleanUp() {
11072            if (codeFile == null || !codeFile.exists()) {
11073                return false;
11074            }
11075
11076            if (codeFile.isDirectory()) {
11077                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11078            } else {
11079                codeFile.delete();
11080            }
11081
11082            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11083                resourceFile.delete();
11084            }
11085
11086            return true;
11087        }
11088
11089        void cleanUpResourcesLI() {
11090            // Try enumerating all code paths before deleting
11091            List<String> allCodePaths = Collections.EMPTY_LIST;
11092            if (codeFile != null && codeFile.exists()) {
11093                try {
11094                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11095                    allCodePaths = pkg.getAllCodePaths();
11096                } catch (PackageParserException e) {
11097                    // Ignored; we tried our best
11098                }
11099            }
11100
11101            cleanUp();
11102            removeDexFiles(allCodePaths, instructionSets);
11103        }
11104
11105        boolean doPostDeleteLI(boolean delete) {
11106            // XXX err, shouldn't we respect the delete flag?
11107            cleanUpResourcesLI();
11108            return true;
11109        }
11110    }
11111
11112    private boolean isAsecExternal(String cid) {
11113        final String asecPath = PackageHelper.getSdFilesystem(cid);
11114        return !asecPath.startsWith(mAsecInternalPath);
11115    }
11116
11117    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11118            PackageManagerException {
11119        if (copyRet < 0) {
11120            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11121                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11122                throw new PackageManagerException(copyRet, message);
11123            }
11124        }
11125    }
11126
11127    /**
11128     * Extract the MountService "container ID" from the full code path of an
11129     * .apk.
11130     */
11131    static String cidFromCodePath(String fullCodePath) {
11132        int eidx = fullCodePath.lastIndexOf("/");
11133        String subStr1 = fullCodePath.substring(0, eidx);
11134        int sidx = subStr1.lastIndexOf("/");
11135        return subStr1.substring(sidx+1, eidx);
11136    }
11137
11138    /**
11139     * Logic to handle installation of ASEC applications, including copying and
11140     * renaming logic.
11141     */
11142    class AsecInstallArgs extends InstallArgs {
11143        static final String RES_FILE_NAME = "pkg.apk";
11144        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11145
11146        String cid;
11147        String packagePath;
11148        String resourcePath;
11149
11150        /** New install */
11151        AsecInstallArgs(InstallParams params) {
11152            super(params.origin, params.move, params.observer, params.installFlags,
11153                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11154                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11155                    params.grantedRuntimePermissions);
11156        }
11157
11158        /** Existing install */
11159        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11160                        boolean isExternal, boolean isForwardLocked) {
11161            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11162                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11163                    instructionSets, null, null);
11164            // Hackily pretend we're still looking at a full code path
11165            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11166                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11167            }
11168
11169            // Extract cid from fullCodePath
11170            int eidx = fullCodePath.lastIndexOf("/");
11171            String subStr1 = fullCodePath.substring(0, eidx);
11172            int sidx = subStr1.lastIndexOf("/");
11173            cid = subStr1.substring(sidx+1, eidx);
11174            setMountPath(subStr1);
11175        }
11176
11177        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11178            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11179                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11180                    instructionSets, null, null);
11181            this.cid = cid;
11182            setMountPath(PackageHelper.getSdDir(cid));
11183        }
11184
11185        void createCopyFile() {
11186            cid = mInstallerService.allocateExternalStageCidLegacy();
11187        }
11188
11189        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11190            if (origin.staged) {
11191                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11192                cid = origin.cid;
11193                setMountPath(PackageHelper.getSdDir(cid));
11194                return PackageManager.INSTALL_SUCCEEDED;
11195            }
11196
11197            if (temp) {
11198                createCopyFile();
11199            } else {
11200                /*
11201                 * Pre-emptively destroy the container since it's destroyed if
11202                 * copying fails due to it existing anyway.
11203                 */
11204                PackageHelper.destroySdDir(cid);
11205            }
11206
11207            final String newMountPath = imcs.copyPackageToContainer(
11208                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11209                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11210
11211            if (newMountPath != null) {
11212                setMountPath(newMountPath);
11213                return PackageManager.INSTALL_SUCCEEDED;
11214            } else {
11215                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11216            }
11217        }
11218
11219        @Override
11220        String getCodePath() {
11221            return packagePath;
11222        }
11223
11224        @Override
11225        String getResourcePath() {
11226            return resourcePath;
11227        }
11228
11229        int doPreInstall(int status) {
11230            if (status != PackageManager.INSTALL_SUCCEEDED) {
11231                // Destroy container
11232                PackageHelper.destroySdDir(cid);
11233            } else {
11234                boolean mounted = PackageHelper.isContainerMounted(cid);
11235                if (!mounted) {
11236                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11237                            Process.SYSTEM_UID);
11238                    if (newMountPath != null) {
11239                        setMountPath(newMountPath);
11240                    } else {
11241                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11242                    }
11243                }
11244            }
11245            return status;
11246        }
11247
11248        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11249            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11250            String newMountPath = null;
11251            if (PackageHelper.isContainerMounted(cid)) {
11252                // Unmount the container
11253                if (!PackageHelper.unMountSdDir(cid)) {
11254                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11255                    return false;
11256                }
11257            }
11258            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11259                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11260                        " which might be stale. Will try to clean up.");
11261                // Clean up the stale container and proceed to recreate.
11262                if (!PackageHelper.destroySdDir(newCacheId)) {
11263                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11264                    return false;
11265                }
11266                // Successfully cleaned up stale container. Try to rename again.
11267                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11268                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11269                            + " inspite of cleaning it up.");
11270                    return false;
11271                }
11272            }
11273            if (!PackageHelper.isContainerMounted(newCacheId)) {
11274                Slog.w(TAG, "Mounting container " + newCacheId);
11275                newMountPath = PackageHelper.mountSdDir(newCacheId,
11276                        getEncryptKey(), Process.SYSTEM_UID);
11277            } else {
11278                newMountPath = PackageHelper.getSdDir(newCacheId);
11279            }
11280            if (newMountPath == null) {
11281                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11282                return false;
11283            }
11284            Log.i(TAG, "Succesfully renamed " + cid +
11285                    " to " + newCacheId +
11286                    " at new path: " + newMountPath);
11287            cid = newCacheId;
11288
11289            final File beforeCodeFile = new File(packagePath);
11290            setMountPath(newMountPath);
11291            final File afterCodeFile = new File(packagePath);
11292
11293            // Reflect the rename in scanned details
11294            pkg.codePath = afterCodeFile.getAbsolutePath();
11295            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11296                    pkg.baseCodePath);
11297            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11298                    pkg.splitCodePaths);
11299
11300            // Reflect the rename in app info
11301            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11302            pkg.applicationInfo.setCodePath(pkg.codePath);
11303            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11304            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11305            pkg.applicationInfo.setResourcePath(pkg.codePath);
11306            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11307            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11308
11309            return true;
11310        }
11311
11312        private void setMountPath(String mountPath) {
11313            final File mountFile = new File(mountPath);
11314
11315            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11316            if (monolithicFile.exists()) {
11317                packagePath = monolithicFile.getAbsolutePath();
11318                if (isFwdLocked()) {
11319                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11320                } else {
11321                    resourcePath = packagePath;
11322                }
11323            } else {
11324                packagePath = mountFile.getAbsolutePath();
11325                resourcePath = packagePath;
11326            }
11327        }
11328
11329        int doPostInstall(int status, int uid) {
11330            if (status != PackageManager.INSTALL_SUCCEEDED) {
11331                cleanUp();
11332            } else {
11333                final int groupOwner;
11334                final String protectedFile;
11335                if (isFwdLocked()) {
11336                    groupOwner = UserHandle.getSharedAppGid(uid);
11337                    protectedFile = RES_FILE_NAME;
11338                } else {
11339                    groupOwner = -1;
11340                    protectedFile = null;
11341                }
11342
11343                if (uid < Process.FIRST_APPLICATION_UID
11344                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11345                    Slog.e(TAG, "Failed to finalize " + cid);
11346                    PackageHelper.destroySdDir(cid);
11347                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11348                }
11349
11350                boolean mounted = PackageHelper.isContainerMounted(cid);
11351                if (!mounted) {
11352                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11353                }
11354            }
11355            return status;
11356        }
11357
11358        private void cleanUp() {
11359            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11360
11361            // Destroy secure container
11362            PackageHelper.destroySdDir(cid);
11363        }
11364
11365        private List<String> getAllCodePaths() {
11366            final File codeFile = new File(getCodePath());
11367            if (codeFile != null && codeFile.exists()) {
11368                try {
11369                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11370                    return pkg.getAllCodePaths();
11371                } catch (PackageParserException e) {
11372                    // Ignored; we tried our best
11373                }
11374            }
11375            return Collections.EMPTY_LIST;
11376        }
11377
11378        void cleanUpResourcesLI() {
11379            // Enumerate all code paths before deleting
11380            cleanUpResourcesLI(getAllCodePaths());
11381        }
11382
11383        private void cleanUpResourcesLI(List<String> allCodePaths) {
11384            cleanUp();
11385            removeDexFiles(allCodePaths, instructionSets);
11386        }
11387
11388        String getPackageName() {
11389            return getAsecPackageName(cid);
11390        }
11391
11392        boolean doPostDeleteLI(boolean delete) {
11393            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11394            final List<String> allCodePaths = getAllCodePaths();
11395            boolean mounted = PackageHelper.isContainerMounted(cid);
11396            if (mounted) {
11397                // Unmount first
11398                if (PackageHelper.unMountSdDir(cid)) {
11399                    mounted = false;
11400                }
11401            }
11402            if (!mounted && delete) {
11403                cleanUpResourcesLI(allCodePaths);
11404            }
11405            return !mounted;
11406        }
11407
11408        @Override
11409        int doPreCopy() {
11410            if (isFwdLocked()) {
11411                if (!PackageHelper.fixSdPermissions(cid,
11412                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11413                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11414                }
11415            }
11416
11417            return PackageManager.INSTALL_SUCCEEDED;
11418        }
11419
11420        @Override
11421        int doPostCopy(int uid) {
11422            if (isFwdLocked()) {
11423                if (uid < Process.FIRST_APPLICATION_UID
11424                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11425                                RES_FILE_NAME)) {
11426                    Slog.e(TAG, "Failed to finalize " + cid);
11427                    PackageHelper.destroySdDir(cid);
11428                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11429                }
11430            }
11431
11432            return PackageManager.INSTALL_SUCCEEDED;
11433        }
11434    }
11435
11436    /**
11437     * Logic to handle movement of existing installed applications.
11438     */
11439    class MoveInstallArgs extends InstallArgs {
11440        private File codeFile;
11441        private File resourceFile;
11442
11443        /** New install */
11444        MoveInstallArgs(InstallParams params) {
11445            super(params.origin, params.move, params.observer, params.installFlags,
11446                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11447                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11448                    params.grantedRuntimePermissions);
11449        }
11450
11451        int copyApk(IMediaContainerService imcs, boolean temp) {
11452            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11453                    + move.fromUuid + " to " + move.toUuid);
11454            synchronized (mInstaller) {
11455                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11456                        move.dataAppName, move.appId, move.seinfo) != 0) {
11457                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11458                }
11459            }
11460
11461            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11462            resourceFile = codeFile;
11463            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11464
11465            return PackageManager.INSTALL_SUCCEEDED;
11466        }
11467
11468        int doPreInstall(int status) {
11469            if (status != PackageManager.INSTALL_SUCCEEDED) {
11470                cleanUp(move.toUuid);
11471            }
11472            return status;
11473        }
11474
11475        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11476            if (status != PackageManager.INSTALL_SUCCEEDED) {
11477                cleanUp(move.toUuid);
11478                return false;
11479            }
11480
11481            // Reflect the move in app info
11482            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11483            pkg.applicationInfo.setCodePath(pkg.codePath);
11484            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11485            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11486            pkg.applicationInfo.setResourcePath(pkg.codePath);
11487            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11488            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11489
11490            return true;
11491        }
11492
11493        int doPostInstall(int status, int uid) {
11494            if (status == PackageManager.INSTALL_SUCCEEDED) {
11495                cleanUp(move.fromUuid);
11496            } else {
11497                cleanUp(move.toUuid);
11498            }
11499            return status;
11500        }
11501
11502        @Override
11503        String getCodePath() {
11504            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11505        }
11506
11507        @Override
11508        String getResourcePath() {
11509            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11510        }
11511
11512        private boolean cleanUp(String volumeUuid) {
11513            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11514                    move.dataAppName);
11515            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11516            synchronized (mInstallLock) {
11517                // Clean up both app data and code
11518                removeDataDirsLI(volumeUuid, move.packageName);
11519                if (codeFile.isDirectory()) {
11520                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11521                } else {
11522                    codeFile.delete();
11523                }
11524            }
11525            return true;
11526        }
11527
11528        void cleanUpResourcesLI() {
11529            throw new UnsupportedOperationException();
11530        }
11531
11532        boolean doPostDeleteLI(boolean delete) {
11533            throw new UnsupportedOperationException();
11534        }
11535    }
11536
11537    static String getAsecPackageName(String packageCid) {
11538        int idx = packageCid.lastIndexOf("-");
11539        if (idx == -1) {
11540            return packageCid;
11541        }
11542        return packageCid.substring(0, idx);
11543    }
11544
11545    // Utility method used to create code paths based on package name and available index.
11546    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11547        String idxStr = "";
11548        int idx = 1;
11549        // Fall back to default value of idx=1 if prefix is not
11550        // part of oldCodePath
11551        if (oldCodePath != null) {
11552            String subStr = oldCodePath;
11553            // Drop the suffix right away
11554            if (suffix != null && subStr.endsWith(suffix)) {
11555                subStr = subStr.substring(0, subStr.length() - suffix.length());
11556            }
11557            // If oldCodePath already contains prefix find out the
11558            // ending index to either increment or decrement.
11559            int sidx = subStr.lastIndexOf(prefix);
11560            if (sidx != -1) {
11561                subStr = subStr.substring(sidx + prefix.length());
11562                if (subStr != null) {
11563                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11564                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11565                    }
11566                    try {
11567                        idx = Integer.parseInt(subStr);
11568                        if (idx <= 1) {
11569                            idx++;
11570                        } else {
11571                            idx--;
11572                        }
11573                    } catch(NumberFormatException e) {
11574                    }
11575                }
11576            }
11577        }
11578        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11579        return prefix + idxStr;
11580    }
11581
11582    private File getNextCodePath(File targetDir, String packageName) {
11583        int suffix = 1;
11584        File result;
11585        do {
11586            result = new File(targetDir, packageName + "-" + suffix);
11587            suffix++;
11588        } while (result.exists());
11589        return result;
11590    }
11591
11592    // Utility method that returns the relative package path with respect
11593    // to the installation directory. Like say for /data/data/com.test-1.apk
11594    // string com.test-1 is returned.
11595    static String deriveCodePathName(String codePath) {
11596        if (codePath == null) {
11597            return null;
11598        }
11599        final File codeFile = new File(codePath);
11600        final String name = codeFile.getName();
11601        if (codeFile.isDirectory()) {
11602            return name;
11603        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11604            final int lastDot = name.lastIndexOf('.');
11605            return name.substring(0, lastDot);
11606        } else {
11607            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11608            return null;
11609        }
11610    }
11611
11612    class PackageInstalledInfo {
11613        String name;
11614        int uid;
11615        // The set of users that originally had this package installed.
11616        int[] origUsers;
11617        // The set of users that now have this package installed.
11618        int[] newUsers;
11619        PackageParser.Package pkg;
11620        int returnCode;
11621        String returnMsg;
11622        PackageRemovedInfo removedInfo;
11623
11624        public void setError(int code, String msg) {
11625            returnCode = code;
11626            returnMsg = msg;
11627            Slog.w(TAG, msg);
11628        }
11629
11630        public void setError(String msg, PackageParserException e) {
11631            returnCode = e.error;
11632            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11633            Slog.w(TAG, msg, e);
11634        }
11635
11636        public void setError(String msg, PackageManagerException e) {
11637            returnCode = e.error;
11638            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11639            Slog.w(TAG, msg, e);
11640        }
11641
11642        // In some error cases we want to convey more info back to the observer
11643        String origPackage;
11644        String origPermission;
11645    }
11646
11647    /*
11648     * Install a non-existing package.
11649     */
11650    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11651            UserHandle user, String installerPackageName, String volumeUuid,
11652            PackageInstalledInfo res) {
11653        // Remember this for later, in case we need to rollback this install
11654        String pkgName = pkg.packageName;
11655
11656        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11657        final boolean dataDirExists = Environment
11658                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11659        synchronized(mPackages) {
11660            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11661                // A package with the same name is already installed, though
11662                // it has been renamed to an older name.  The package we
11663                // are trying to install should be installed as an update to
11664                // the existing one, but that has not been requested, so bail.
11665                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11666                        + " without first uninstalling package running as "
11667                        + mSettings.mRenamedPackages.get(pkgName));
11668                return;
11669            }
11670            if (mPackages.containsKey(pkgName)) {
11671                // Don't allow installation over an existing package with the same name.
11672                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11673                        + " without first uninstalling.");
11674                return;
11675            }
11676        }
11677
11678        try {
11679            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11680                    System.currentTimeMillis(), user);
11681
11682            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11683            // delete the partially installed application. the data directory will have to be
11684            // restored if it was already existing
11685            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11686                // remove package from internal structures.  Note that we want deletePackageX to
11687                // delete the package data and cache directories that it created in
11688                // scanPackageLocked, unless those directories existed before we even tried to
11689                // install.
11690                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11691                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11692                                res.removedInfo, true);
11693            }
11694
11695        } catch (PackageManagerException e) {
11696            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11697        }
11698    }
11699
11700    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11701        // Can't rotate keys during boot or if sharedUser.
11702        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11703                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11704            return false;
11705        }
11706        // app is using upgradeKeySets; make sure all are valid
11707        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11708        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11709        for (int i = 0; i < upgradeKeySets.length; i++) {
11710            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11711                Slog.wtf(TAG, "Package "
11712                         + (oldPs.name != null ? oldPs.name : "<null>")
11713                         + " contains upgrade-key-set reference to unknown key-set: "
11714                         + upgradeKeySets[i]
11715                         + " reverting to signatures check.");
11716                return false;
11717            }
11718        }
11719        return true;
11720    }
11721
11722    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11723        // Upgrade keysets are being used.  Determine if new package has a superset of the
11724        // required keys.
11725        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11726        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11727        for (int i = 0; i < upgradeKeySets.length; i++) {
11728            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11729            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11730                return true;
11731            }
11732        }
11733        return false;
11734    }
11735
11736    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11737            UserHandle user, String installerPackageName, String volumeUuid,
11738            PackageInstalledInfo res) {
11739        final PackageParser.Package oldPackage;
11740        final String pkgName = pkg.packageName;
11741        final int[] allUsers;
11742        final boolean[] perUserInstalled;
11743        final boolean weFroze;
11744
11745        // First find the old package info and check signatures
11746        synchronized(mPackages) {
11747            oldPackage = mPackages.get(pkgName);
11748            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11749            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11750            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11751                if(!checkUpgradeKeySetLP(ps, pkg)) {
11752                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11753                            "New package not signed by keys specified by upgrade-keysets: "
11754                            + pkgName);
11755                    return;
11756                }
11757            } else {
11758                // default to original signature matching
11759                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11760                    != PackageManager.SIGNATURE_MATCH) {
11761                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11762                            "New package has a different signature: " + pkgName);
11763                    return;
11764                }
11765            }
11766
11767            // In case of rollback, remember per-user/profile install state
11768            allUsers = sUserManager.getUserIds();
11769            perUserInstalled = new boolean[allUsers.length];
11770            for (int i = 0; i < allUsers.length; i++) {
11771                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11772            }
11773
11774            // Mark the app as frozen to prevent launching during the upgrade
11775            // process, and then kill all running instances
11776            if (!ps.frozen) {
11777                ps.frozen = true;
11778                weFroze = true;
11779            } else {
11780                weFroze = false;
11781            }
11782        }
11783
11784        // Now that we're guarded by frozen state, kill app during upgrade
11785        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11786
11787        try {
11788            boolean sysPkg = (isSystemApp(oldPackage));
11789            if (sysPkg) {
11790                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11791                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11792            } else {
11793                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11794                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11795            }
11796        } finally {
11797            // Regardless of success or failure of upgrade steps above, always
11798            // unfreeze the package if we froze it
11799            if (weFroze) {
11800                unfreezePackage(pkgName);
11801            }
11802        }
11803    }
11804
11805    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11806            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11807            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11808            String volumeUuid, PackageInstalledInfo res) {
11809        String pkgName = deletedPackage.packageName;
11810        boolean deletedPkg = true;
11811        boolean updatedSettings = false;
11812
11813        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11814                + deletedPackage);
11815        long origUpdateTime;
11816        if (pkg.mExtras != null) {
11817            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11818        } else {
11819            origUpdateTime = 0;
11820        }
11821
11822        // First delete the existing package while retaining the data directory
11823        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11824                res.removedInfo, true)) {
11825            // If the existing package wasn't successfully deleted
11826            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11827            deletedPkg = false;
11828        } else {
11829            // Successfully deleted the old package; proceed with replace.
11830
11831            // If deleted package lived in a container, give users a chance to
11832            // relinquish resources before killing.
11833            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11834                if (DEBUG_INSTALL) {
11835                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11836                }
11837                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11838                final ArrayList<String> pkgList = new ArrayList<String>(1);
11839                pkgList.add(deletedPackage.applicationInfo.packageName);
11840                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11841            }
11842
11843            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11844            try {
11845                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11846                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11847                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11848                        perUserInstalled, res, user);
11849                updatedSettings = true;
11850            } catch (PackageManagerException e) {
11851                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11852            }
11853        }
11854
11855        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11856            // remove package from internal structures.  Note that we want deletePackageX to
11857            // delete the package data and cache directories that it created in
11858            // scanPackageLocked, unless those directories existed before we even tried to
11859            // install.
11860            if(updatedSettings) {
11861                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11862                deletePackageLI(
11863                        pkgName, null, true, allUsers, perUserInstalled,
11864                        PackageManager.DELETE_KEEP_DATA,
11865                                res.removedInfo, true);
11866            }
11867            // Since we failed to install the new package we need to restore the old
11868            // package that we deleted.
11869            if (deletedPkg) {
11870                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11871                File restoreFile = new File(deletedPackage.codePath);
11872                // Parse old package
11873                boolean oldExternal = isExternal(deletedPackage);
11874                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11875                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11876                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11877                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11878                try {
11879                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11880                } catch (PackageManagerException e) {
11881                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11882                            + e.getMessage());
11883                    return;
11884                }
11885                // Restore of old package succeeded. Update permissions.
11886                // writer
11887                synchronized (mPackages) {
11888                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11889                            UPDATE_PERMISSIONS_ALL);
11890                    // can downgrade to reader
11891                    mSettings.writeLPr();
11892                }
11893                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11894            }
11895        }
11896    }
11897
11898    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11899            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11900            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11901            String volumeUuid, PackageInstalledInfo res) {
11902        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11903                + ", old=" + deletedPackage);
11904        boolean disabledSystem = false;
11905        boolean updatedSettings = false;
11906        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11907        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11908                != 0) {
11909            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11910        }
11911        String packageName = deletedPackage.packageName;
11912        if (packageName == null) {
11913            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11914                    "Attempt to delete null packageName.");
11915            return;
11916        }
11917        PackageParser.Package oldPkg;
11918        PackageSetting oldPkgSetting;
11919        // reader
11920        synchronized (mPackages) {
11921            oldPkg = mPackages.get(packageName);
11922            oldPkgSetting = mSettings.mPackages.get(packageName);
11923            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11924                    (oldPkgSetting == null)) {
11925                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11926                        "Couldn't find package:" + packageName + " information");
11927                return;
11928            }
11929        }
11930
11931        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11932        res.removedInfo.removedPackage = packageName;
11933        // Remove existing system package
11934        removePackageLI(oldPkgSetting, true);
11935        // writer
11936        synchronized (mPackages) {
11937            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11938            if (!disabledSystem && deletedPackage != null) {
11939                // We didn't need to disable the .apk as a current system package,
11940                // which means we are replacing another update that is already
11941                // installed.  We need to make sure to delete the older one's .apk.
11942                res.removedInfo.args = createInstallArgsForExisting(0,
11943                        deletedPackage.applicationInfo.getCodePath(),
11944                        deletedPackage.applicationInfo.getResourcePath(),
11945                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11946            } else {
11947                res.removedInfo.args = null;
11948            }
11949        }
11950
11951        // Successfully disabled the old package. Now proceed with re-installation
11952        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11953
11954        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11955        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11956
11957        PackageParser.Package newPackage = null;
11958        try {
11959            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11960            if (newPackage.mExtras != null) {
11961                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11962                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11963                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11964
11965                // is the update attempting to change shared user? that isn't going to work...
11966                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11967                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11968                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11969                            + " to " + newPkgSetting.sharedUser);
11970                    updatedSettings = true;
11971                }
11972            }
11973
11974            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11975                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11976                        perUserInstalled, res, user);
11977                updatedSettings = true;
11978            }
11979
11980        } catch (PackageManagerException e) {
11981            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11982        }
11983
11984        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11985            // Re installation failed. Restore old information
11986            // Remove new pkg information
11987            if (newPackage != null) {
11988                removeInstalledPackageLI(newPackage, true);
11989            }
11990            // Add back the old system package
11991            try {
11992                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11993            } catch (PackageManagerException e) {
11994                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11995            }
11996            // Restore the old system information in Settings
11997            synchronized (mPackages) {
11998                if (disabledSystem) {
11999                    mSettings.enableSystemPackageLPw(packageName);
12000                }
12001                if (updatedSettings) {
12002                    mSettings.setInstallerPackageName(packageName,
12003                            oldPkgSetting.installerPackageName);
12004                }
12005                mSettings.writeLPr();
12006            }
12007        }
12008    }
12009
12010    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12011            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12012            UserHandle user) {
12013        String pkgName = newPackage.packageName;
12014        synchronized (mPackages) {
12015            //write settings. the installStatus will be incomplete at this stage.
12016            //note that the new package setting would have already been
12017            //added to mPackages. It hasn't been persisted yet.
12018            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12019            mSettings.writeLPr();
12020        }
12021
12022        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12023
12024        synchronized (mPackages) {
12025            updatePermissionsLPw(newPackage.packageName, newPackage,
12026                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12027                            ? UPDATE_PERMISSIONS_ALL : 0));
12028            // For system-bundled packages, we assume that installing an upgraded version
12029            // of the package implies that the user actually wants to run that new code,
12030            // so we enable the package.
12031            PackageSetting ps = mSettings.mPackages.get(pkgName);
12032            if (ps != null) {
12033                if (isSystemApp(newPackage)) {
12034                    // NB: implicit assumption that system package upgrades apply to all users
12035                    if (DEBUG_INSTALL) {
12036                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12037                    }
12038                    if (res.origUsers != null) {
12039                        for (int userHandle : res.origUsers) {
12040                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12041                                    userHandle, installerPackageName);
12042                        }
12043                    }
12044                    // Also convey the prior install/uninstall state
12045                    if (allUsers != null && perUserInstalled != null) {
12046                        for (int i = 0; i < allUsers.length; i++) {
12047                            if (DEBUG_INSTALL) {
12048                                Slog.d(TAG, "    user " + allUsers[i]
12049                                        + " => " + perUserInstalled[i]);
12050                            }
12051                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12052                        }
12053                        // these install state changes will be persisted in the
12054                        // upcoming call to mSettings.writeLPr().
12055                    }
12056                }
12057                // It's implied that when a user requests installation, they want the app to be
12058                // installed and enabled.
12059                int userId = user.getIdentifier();
12060                if (userId != UserHandle.USER_ALL) {
12061                    ps.setInstalled(true, userId);
12062                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12063                }
12064            }
12065            res.name = pkgName;
12066            res.uid = newPackage.applicationInfo.uid;
12067            res.pkg = newPackage;
12068            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12069            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12070            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12071            //to update install status
12072            mSettings.writeLPr();
12073        }
12074    }
12075
12076    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12077        final int installFlags = args.installFlags;
12078        final String installerPackageName = args.installerPackageName;
12079        final String volumeUuid = args.volumeUuid;
12080        final File tmpPackageFile = new File(args.getCodePath());
12081        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12082        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12083                || (args.volumeUuid != null));
12084        boolean replace = false;
12085        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12086        if (args.move != null) {
12087            // moving a complete application; perfom an initial scan on the new install location
12088            scanFlags |= SCAN_INITIAL;
12089        }
12090        // Result object to be returned
12091        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12092
12093        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12094        // Retrieve PackageSettings and parse package
12095        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12096                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12097                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12098        PackageParser pp = new PackageParser();
12099        pp.setSeparateProcesses(mSeparateProcesses);
12100        pp.setDisplayMetrics(mMetrics);
12101
12102        final PackageParser.Package pkg;
12103        try {
12104            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12105        } catch (PackageParserException e) {
12106            res.setError("Failed parse during installPackageLI", e);
12107            return;
12108        }
12109
12110        // Mark that we have an install time CPU ABI override.
12111        pkg.cpuAbiOverride = args.abiOverride;
12112
12113        String pkgName = res.name = pkg.packageName;
12114        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12115            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12116                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12117                return;
12118            }
12119        }
12120
12121        try {
12122            pp.collectCertificates(pkg, parseFlags);
12123            pp.collectManifestDigest(pkg);
12124        } catch (PackageParserException e) {
12125            res.setError("Failed collect during installPackageLI", e);
12126            return;
12127        }
12128
12129        /* If the installer passed in a manifest digest, compare it now. */
12130        if (args.manifestDigest != null) {
12131            if (DEBUG_INSTALL) {
12132                final String parsedManifest = pkg.manifestDigest == null ? "null"
12133                        : pkg.manifestDigest.toString();
12134                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12135                        + parsedManifest);
12136            }
12137
12138            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12139                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12140                return;
12141            }
12142        } else if (DEBUG_INSTALL) {
12143            final String parsedManifest = pkg.manifestDigest == null
12144                    ? "null" : pkg.manifestDigest.toString();
12145            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12146        }
12147
12148        // Get rid of all references to package scan path via parser.
12149        pp = null;
12150        String oldCodePath = null;
12151        boolean systemApp = false;
12152        synchronized (mPackages) {
12153            // Check if installing already existing package
12154            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12155                String oldName = mSettings.mRenamedPackages.get(pkgName);
12156                if (pkg.mOriginalPackages != null
12157                        && pkg.mOriginalPackages.contains(oldName)
12158                        && mPackages.containsKey(oldName)) {
12159                    // This package is derived from an original package,
12160                    // and this device has been updating from that original
12161                    // name.  We must continue using the original name, so
12162                    // rename the new package here.
12163                    pkg.setPackageName(oldName);
12164                    pkgName = pkg.packageName;
12165                    replace = true;
12166                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12167                            + oldName + " pkgName=" + pkgName);
12168                } else if (mPackages.containsKey(pkgName)) {
12169                    // This package, under its official name, already exists
12170                    // on the device; we should replace it.
12171                    replace = true;
12172                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12173                }
12174
12175                // Prevent apps opting out from runtime permissions
12176                if (replace) {
12177                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12178                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12179                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12180                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12181                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12182                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12183                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12184                                        + " doesn't support runtime permissions but the old"
12185                                        + " target SDK " + oldTargetSdk + " does.");
12186                        return;
12187                    }
12188                }
12189            }
12190
12191            PackageSetting ps = mSettings.mPackages.get(pkgName);
12192            if (ps != null) {
12193                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12194
12195                // Quick sanity check that we're signed correctly if updating;
12196                // we'll check this again later when scanning, but we want to
12197                // bail early here before tripping over redefined permissions.
12198                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12199                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12200                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12201                                + pkg.packageName + " upgrade keys do not match the "
12202                                + "previously installed version");
12203                        return;
12204                    }
12205                } else {
12206                    try {
12207                        verifySignaturesLP(ps, pkg);
12208                    } catch (PackageManagerException e) {
12209                        res.setError(e.error, e.getMessage());
12210                        return;
12211                    }
12212                }
12213
12214                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12215                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12216                    systemApp = (ps.pkg.applicationInfo.flags &
12217                            ApplicationInfo.FLAG_SYSTEM) != 0;
12218                }
12219                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12220            }
12221
12222            // Check whether the newly-scanned package wants to define an already-defined perm
12223            int N = pkg.permissions.size();
12224            for (int i = N-1; i >= 0; i--) {
12225                PackageParser.Permission perm = pkg.permissions.get(i);
12226                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12227                if (bp != null) {
12228                    // If the defining package is signed with our cert, it's okay.  This
12229                    // also includes the "updating the same package" case, of course.
12230                    // "updating same package" could also involve key-rotation.
12231                    final boolean sigsOk;
12232                    if (bp.sourcePackage.equals(pkg.packageName)
12233                            && (bp.packageSetting instanceof PackageSetting)
12234                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12235                                    scanFlags))) {
12236                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12237                    } else {
12238                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12239                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12240                    }
12241                    if (!sigsOk) {
12242                        // If the owning package is the system itself, we log but allow
12243                        // install to proceed; we fail the install on all other permission
12244                        // redefinitions.
12245                        if (!bp.sourcePackage.equals("android")) {
12246                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12247                                    + pkg.packageName + " attempting to redeclare permission "
12248                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12249                            res.origPermission = perm.info.name;
12250                            res.origPackage = bp.sourcePackage;
12251                            return;
12252                        } else {
12253                            Slog.w(TAG, "Package " + pkg.packageName
12254                                    + " attempting to redeclare system permission "
12255                                    + perm.info.name + "; ignoring new declaration");
12256                            pkg.permissions.remove(i);
12257                        }
12258                    }
12259                }
12260            }
12261
12262        }
12263
12264        if (systemApp && onExternal) {
12265            // Disable updates to system apps on sdcard
12266            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12267                    "Cannot install updates to system apps on sdcard");
12268            return;
12269        }
12270
12271        if (args.move != null) {
12272            // We did an in-place move, so dex is ready to roll
12273            scanFlags |= SCAN_NO_DEX;
12274            scanFlags |= SCAN_MOVE;
12275        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12276            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12277            scanFlags |= SCAN_NO_DEX;
12278
12279            try {
12280                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12281                        true /* extract libs */);
12282            } catch (PackageManagerException pme) {
12283                Slog.e(TAG, "Error deriving application ABI", pme);
12284                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12285                return;
12286            }
12287
12288            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12289            int result = mPackageDexOptimizer
12290                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12291                            false /* defer */, false /* inclDependencies */);
12292            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12293                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12294                return;
12295            }
12296        }
12297
12298        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12299            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12300            return;
12301        }
12302
12303        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12304
12305        if (replace) {
12306            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12307                    installerPackageName, volumeUuid, res);
12308        } else {
12309            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12310                    args.user, installerPackageName, volumeUuid, res);
12311        }
12312        synchronized (mPackages) {
12313            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12314            if (ps != null) {
12315                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12316            }
12317        }
12318    }
12319
12320    private void startIntentFilterVerifications(int userId, boolean replacing,
12321            PackageParser.Package pkg) {
12322        if (mIntentFilterVerifierComponent == null) {
12323            Slog.w(TAG, "No IntentFilter verification will not be done as "
12324                    + "there is no IntentFilterVerifier available!");
12325            return;
12326        }
12327
12328        final int verifierUid = getPackageUid(
12329                mIntentFilterVerifierComponent.getPackageName(),
12330                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12331
12332        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12333        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12334        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12335        mHandler.sendMessage(msg);
12336    }
12337
12338    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12339            PackageParser.Package pkg) {
12340        int size = pkg.activities.size();
12341        if (size == 0) {
12342            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12343                    "No activity, so no need to verify any IntentFilter!");
12344            return;
12345        }
12346
12347        final boolean hasDomainURLs = hasDomainURLs(pkg);
12348        if (!hasDomainURLs) {
12349            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12350                    "No domain URLs, so no need to verify any IntentFilter!");
12351            return;
12352        }
12353
12354        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12355                + " if any IntentFilter from the " + size
12356                + " Activities needs verification ...");
12357
12358        int count = 0;
12359        final String packageName = pkg.packageName;
12360
12361        synchronized (mPackages) {
12362            // If this is a new install and we see that we've already run verification for this
12363            // package, we have nothing to do: it means the state was restored from backup.
12364            if (!replacing) {
12365                IntentFilterVerificationInfo ivi =
12366                        mSettings.getIntentFilterVerificationLPr(packageName);
12367                if (ivi != null) {
12368                    if (DEBUG_DOMAIN_VERIFICATION) {
12369                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12370                                + ivi.getStatusString());
12371                    }
12372                    return;
12373                }
12374            }
12375
12376            // If any filters need to be verified, then all need to be.
12377            boolean needToVerify = false;
12378            for (PackageParser.Activity a : pkg.activities) {
12379                for (ActivityIntentInfo filter : a.intents) {
12380                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12381                        if (DEBUG_DOMAIN_VERIFICATION) {
12382                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12383                        }
12384                        needToVerify = true;
12385                        break;
12386                    }
12387                }
12388            }
12389
12390            if (needToVerify) {
12391                final int verificationId = mIntentFilterVerificationToken++;
12392                for (PackageParser.Activity a : pkg.activities) {
12393                    for (ActivityIntentInfo filter : a.intents) {
12394                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12395                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12396                                    "Verification needed for IntentFilter:" + filter.toString());
12397                            mIntentFilterVerifier.addOneIntentFilterVerification(
12398                                    verifierUid, userId, verificationId, filter, packageName);
12399                            count++;
12400                        }
12401                    }
12402                }
12403            }
12404        }
12405
12406        if (count > 0) {
12407            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12408                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12409                    +  " for userId:" + userId);
12410            mIntentFilterVerifier.startVerifications(userId);
12411        } else {
12412            if (DEBUG_DOMAIN_VERIFICATION) {
12413                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12414            }
12415        }
12416    }
12417
12418    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12419        final ComponentName cn  = filter.activity.getComponentName();
12420        final String packageName = cn.getPackageName();
12421
12422        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12423                packageName);
12424        if (ivi == null) {
12425            return true;
12426        }
12427        int status = ivi.getStatus();
12428        switch (status) {
12429            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12430            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12431                return true;
12432
12433            default:
12434                // Nothing to do
12435                return false;
12436        }
12437    }
12438
12439    private static boolean isMultiArch(PackageSetting ps) {
12440        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12441    }
12442
12443    private static boolean isMultiArch(ApplicationInfo info) {
12444        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12445    }
12446
12447    private static boolean isExternal(PackageParser.Package pkg) {
12448        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12449    }
12450
12451    private static boolean isExternal(PackageSetting ps) {
12452        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12453    }
12454
12455    private static boolean isExternal(ApplicationInfo info) {
12456        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12457    }
12458
12459    private static boolean isSystemApp(PackageParser.Package pkg) {
12460        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12461    }
12462
12463    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12464        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12465    }
12466
12467    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12468        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12469    }
12470
12471    private static boolean isSystemApp(PackageSetting ps) {
12472        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12473    }
12474
12475    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12476        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12477    }
12478
12479    private int packageFlagsToInstallFlags(PackageSetting ps) {
12480        int installFlags = 0;
12481        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12482            // This existing package was an external ASEC install when we have
12483            // the external flag without a UUID
12484            installFlags |= PackageManager.INSTALL_EXTERNAL;
12485        }
12486        if (ps.isForwardLocked()) {
12487            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12488        }
12489        return installFlags;
12490    }
12491
12492    private void deleteTempPackageFiles() {
12493        final FilenameFilter filter = new FilenameFilter() {
12494            public boolean accept(File dir, String name) {
12495                return name.startsWith("vmdl") && name.endsWith(".tmp");
12496            }
12497        };
12498        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12499            file.delete();
12500        }
12501    }
12502
12503    @Override
12504    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12505            int flags) {
12506        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12507                flags);
12508    }
12509
12510    @Override
12511    public void deletePackage(final String packageName,
12512            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12513        mContext.enforceCallingOrSelfPermission(
12514                android.Manifest.permission.DELETE_PACKAGES, null);
12515        Preconditions.checkNotNull(packageName);
12516        Preconditions.checkNotNull(observer);
12517        final int uid = Binder.getCallingUid();
12518        if (UserHandle.getUserId(uid) != userId) {
12519            mContext.enforceCallingPermission(
12520                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12521                    "deletePackage for user " + userId);
12522        }
12523        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12524            try {
12525                observer.onPackageDeleted(packageName,
12526                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12527            } catch (RemoteException re) {
12528            }
12529            return;
12530        }
12531
12532        boolean uninstallBlocked = false;
12533        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12534            int[] users = sUserManager.getUserIds();
12535            for (int i = 0; i < users.length; ++i) {
12536                if (getBlockUninstallForUser(packageName, users[i])) {
12537                    uninstallBlocked = true;
12538                    break;
12539                }
12540            }
12541        } else {
12542            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12543        }
12544        if (uninstallBlocked) {
12545            try {
12546                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12547                        null);
12548            } catch (RemoteException re) {
12549            }
12550            return;
12551        }
12552
12553        if (DEBUG_REMOVE) {
12554            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12555        }
12556        // Queue up an async operation since the package deletion may take a little while.
12557        mHandler.post(new Runnable() {
12558            public void run() {
12559                mHandler.removeCallbacks(this);
12560                final int returnCode = deletePackageX(packageName, userId, flags);
12561                if (observer != null) {
12562                    try {
12563                        observer.onPackageDeleted(packageName, returnCode, null);
12564                    } catch (RemoteException e) {
12565                        Log.i(TAG, "Observer no longer exists.");
12566                    } //end catch
12567                } //end if
12568            } //end run
12569        });
12570    }
12571
12572    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12573        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12574                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12575        try {
12576            if (dpm != null) {
12577                if (dpm.isDeviceOwner(packageName)) {
12578                    return true;
12579                }
12580                int[] users;
12581                if (userId == UserHandle.USER_ALL) {
12582                    users = sUserManager.getUserIds();
12583                } else {
12584                    users = new int[]{userId};
12585                }
12586                for (int i = 0; i < users.length; ++i) {
12587                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12588                        return true;
12589                    }
12590                }
12591            }
12592        } catch (RemoteException e) {
12593        }
12594        return false;
12595    }
12596
12597    /**
12598     *  This method is an internal method that could be get invoked either
12599     *  to delete an installed package or to clean up a failed installation.
12600     *  After deleting an installed package, a broadcast is sent to notify any
12601     *  listeners that the package has been installed. For cleaning up a failed
12602     *  installation, the broadcast is not necessary since the package's
12603     *  installation wouldn't have sent the initial broadcast either
12604     *  The key steps in deleting a package are
12605     *  deleting the package information in internal structures like mPackages,
12606     *  deleting the packages base directories through installd
12607     *  updating mSettings to reflect current status
12608     *  persisting settings for later use
12609     *  sending a broadcast if necessary
12610     */
12611    private int deletePackageX(String packageName, int userId, int flags) {
12612        final PackageRemovedInfo info = new PackageRemovedInfo();
12613        final boolean res;
12614
12615        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12616                ? UserHandle.ALL : new UserHandle(userId);
12617
12618        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12619            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12620            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12621        }
12622
12623        boolean removedForAllUsers = false;
12624        boolean systemUpdate = false;
12625
12626        // for the uninstall-updates case and restricted profiles, remember the per-
12627        // userhandle installed state
12628        int[] allUsers;
12629        boolean[] perUserInstalled;
12630        synchronized (mPackages) {
12631            PackageSetting ps = mSettings.mPackages.get(packageName);
12632            allUsers = sUserManager.getUserIds();
12633            perUserInstalled = new boolean[allUsers.length];
12634            for (int i = 0; i < allUsers.length; i++) {
12635                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12636            }
12637        }
12638
12639        synchronized (mInstallLock) {
12640            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12641            res = deletePackageLI(packageName, removeForUser,
12642                    true, allUsers, perUserInstalled,
12643                    flags | REMOVE_CHATTY, info, true);
12644            systemUpdate = info.isRemovedPackageSystemUpdate;
12645            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12646                removedForAllUsers = true;
12647            }
12648            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12649                    + " removedForAllUsers=" + removedForAllUsers);
12650        }
12651
12652        if (res) {
12653            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12654
12655            // If the removed package was a system update, the old system package
12656            // was re-enabled; we need to broadcast this information
12657            if (systemUpdate) {
12658                Bundle extras = new Bundle(1);
12659                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12660                        ? info.removedAppId : info.uid);
12661                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12662
12663                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12664                        extras, null, null, null);
12665                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12666                        extras, null, null, null);
12667                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12668                        null, packageName, null, null);
12669            }
12670        }
12671        // Force a gc here.
12672        Runtime.getRuntime().gc();
12673        // Delete the resources here after sending the broadcast to let
12674        // other processes clean up before deleting resources.
12675        if (info.args != null) {
12676            synchronized (mInstallLock) {
12677                info.args.doPostDeleteLI(true);
12678            }
12679        }
12680
12681        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12682    }
12683
12684    class PackageRemovedInfo {
12685        String removedPackage;
12686        int uid = -1;
12687        int removedAppId = -1;
12688        int[] removedUsers = null;
12689        boolean isRemovedPackageSystemUpdate = false;
12690        // Clean up resources deleted packages.
12691        InstallArgs args = null;
12692
12693        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12694            Bundle extras = new Bundle(1);
12695            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12696            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12697            if (replacing) {
12698                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12699            }
12700            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12701            if (removedPackage != null) {
12702                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12703                        extras, null, null, removedUsers);
12704                if (fullRemove && !replacing) {
12705                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12706                            extras, null, null, removedUsers);
12707                }
12708            }
12709            if (removedAppId >= 0) {
12710                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12711                        removedUsers);
12712            }
12713        }
12714    }
12715
12716    /*
12717     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12718     * flag is not set, the data directory is removed as well.
12719     * make sure this flag is set for partially installed apps. If not its meaningless to
12720     * delete a partially installed application.
12721     */
12722    private void removePackageDataLI(PackageSetting ps,
12723            int[] allUserHandles, boolean[] perUserInstalled,
12724            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12725        String packageName = ps.name;
12726        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12727        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12728        // Retrieve object to delete permissions for shared user later on
12729        final PackageSetting deletedPs;
12730        // reader
12731        synchronized (mPackages) {
12732            deletedPs = mSettings.mPackages.get(packageName);
12733            if (outInfo != null) {
12734                outInfo.removedPackage = packageName;
12735                outInfo.removedUsers = deletedPs != null
12736                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12737                        : null;
12738            }
12739        }
12740        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12741            removeDataDirsLI(ps.volumeUuid, packageName);
12742            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12743        }
12744        // writer
12745        synchronized (mPackages) {
12746            if (deletedPs != null) {
12747                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12748                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12749                    clearDefaultBrowserIfNeeded(packageName);
12750                    if (outInfo != null) {
12751                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12752                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12753                    }
12754                    updatePermissionsLPw(deletedPs.name, null, 0);
12755                    if (deletedPs.sharedUser != null) {
12756                        // Remove permissions associated with package. Since runtime
12757                        // permissions are per user we have to kill the removed package
12758                        // or packages running under the shared user of the removed
12759                        // package if revoking the permissions requested only by the removed
12760                        // package is successful and this causes a change in gids.
12761                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12762                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12763                                    userId);
12764                            if (userIdToKill == UserHandle.USER_ALL
12765                                    || userIdToKill >= UserHandle.USER_OWNER) {
12766                                // If gids changed for this user, kill all affected packages.
12767                                mHandler.post(new Runnable() {
12768                                    @Override
12769                                    public void run() {
12770                                        // This has to happen with no lock held.
12771                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12772                                                KILL_APP_REASON_GIDS_CHANGED);
12773                                    }
12774                                });
12775                                break;
12776                            }
12777                        }
12778                    }
12779                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12780                }
12781                // make sure to preserve per-user disabled state if this removal was just
12782                // a downgrade of a system app to the factory package
12783                if (allUserHandles != null && perUserInstalled != null) {
12784                    if (DEBUG_REMOVE) {
12785                        Slog.d(TAG, "Propagating install state across downgrade");
12786                    }
12787                    for (int i = 0; i < allUserHandles.length; i++) {
12788                        if (DEBUG_REMOVE) {
12789                            Slog.d(TAG, "    user " + allUserHandles[i]
12790                                    + " => " + perUserInstalled[i]);
12791                        }
12792                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12793                    }
12794                }
12795            }
12796            // can downgrade to reader
12797            if (writeSettings) {
12798                // Save settings now
12799                mSettings.writeLPr();
12800            }
12801        }
12802        if (outInfo != null) {
12803            // A user ID was deleted here. Go through all users and remove it
12804            // from KeyStore.
12805            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12806        }
12807    }
12808
12809    static boolean locationIsPrivileged(File path) {
12810        try {
12811            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12812                    .getCanonicalPath();
12813            return path.getCanonicalPath().startsWith(privilegedAppDir);
12814        } catch (IOException e) {
12815            Slog.e(TAG, "Unable to access code path " + path);
12816        }
12817        return false;
12818    }
12819
12820    /*
12821     * Tries to delete system package.
12822     */
12823    private boolean deleteSystemPackageLI(PackageSetting newPs,
12824            int[] allUserHandles, boolean[] perUserInstalled,
12825            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12826        final boolean applyUserRestrictions
12827                = (allUserHandles != null) && (perUserInstalled != null);
12828        PackageSetting disabledPs = null;
12829        // Confirm if the system package has been updated
12830        // An updated system app can be deleted. This will also have to restore
12831        // the system pkg from system partition
12832        // reader
12833        synchronized (mPackages) {
12834            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12835        }
12836        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12837                + " disabledPs=" + disabledPs);
12838        if (disabledPs == null) {
12839            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12840            return false;
12841        } else if (DEBUG_REMOVE) {
12842            Slog.d(TAG, "Deleting system pkg from data partition");
12843        }
12844        if (DEBUG_REMOVE) {
12845            if (applyUserRestrictions) {
12846                Slog.d(TAG, "Remembering install states:");
12847                for (int i = 0; i < allUserHandles.length; i++) {
12848                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12849                }
12850            }
12851        }
12852        // Delete the updated package
12853        outInfo.isRemovedPackageSystemUpdate = true;
12854        if (disabledPs.versionCode < newPs.versionCode) {
12855            // Delete data for downgrades
12856            flags &= ~PackageManager.DELETE_KEEP_DATA;
12857        } else {
12858            // Preserve data by setting flag
12859            flags |= PackageManager.DELETE_KEEP_DATA;
12860        }
12861        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12862                allUserHandles, perUserInstalled, outInfo, writeSettings);
12863        if (!ret) {
12864            return false;
12865        }
12866        // writer
12867        synchronized (mPackages) {
12868            // Reinstate the old system package
12869            mSettings.enableSystemPackageLPw(newPs.name);
12870            // Remove any native libraries from the upgraded package.
12871            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12872        }
12873        // Install the system package
12874        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12875        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12876        if (locationIsPrivileged(disabledPs.codePath)) {
12877            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12878        }
12879
12880        final PackageParser.Package newPkg;
12881        try {
12882            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12883        } catch (PackageManagerException e) {
12884            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12885            return false;
12886        }
12887
12888        // writer
12889        synchronized (mPackages) {
12890            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12891
12892            // Propagate the permissions state as we do want to drop on the floor
12893            // runtime permissions. The update permissions method below will take
12894            // care of removing obsolete permissions and grant install permissions.
12895            ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState());
12896            updatePermissionsLPw(newPkg.packageName, newPkg,
12897                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12898
12899            if (applyUserRestrictions) {
12900                if (DEBUG_REMOVE) {
12901                    Slog.d(TAG, "Propagating install state across reinstall");
12902                }
12903                for (int i = 0; i < allUserHandles.length; i++) {
12904                    if (DEBUG_REMOVE) {
12905                        Slog.d(TAG, "    user " + allUserHandles[i]
12906                                + " => " + perUserInstalled[i]);
12907                    }
12908                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12909                }
12910                // Regardless of writeSettings we need to ensure that this restriction
12911                // state propagation is persisted
12912                mSettings.writeAllUsersPackageRestrictionsLPr();
12913            }
12914            // can downgrade to reader here
12915            if (writeSettings) {
12916                mSettings.writeLPr();
12917            }
12918        }
12919        return true;
12920    }
12921
12922    private boolean deleteInstalledPackageLI(PackageSetting ps,
12923            boolean deleteCodeAndResources, int flags,
12924            int[] allUserHandles, boolean[] perUserInstalled,
12925            PackageRemovedInfo outInfo, boolean writeSettings) {
12926        if (outInfo != null) {
12927            outInfo.uid = ps.appId;
12928        }
12929
12930        // Delete package data from internal structures and also remove data if flag is set
12931        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12932
12933        // Delete application code and resources
12934        if (deleteCodeAndResources && (outInfo != null)) {
12935            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12936                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12937            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12938        }
12939        return true;
12940    }
12941
12942    @Override
12943    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12944            int userId) {
12945        mContext.enforceCallingOrSelfPermission(
12946                android.Manifest.permission.DELETE_PACKAGES, null);
12947        synchronized (mPackages) {
12948            PackageSetting ps = mSettings.mPackages.get(packageName);
12949            if (ps == null) {
12950                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12951                return false;
12952            }
12953            if (!ps.getInstalled(userId)) {
12954                // Can't block uninstall for an app that is not installed or enabled.
12955                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12956                return false;
12957            }
12958            ps.setBlockUninstall(blockUninstall, userId);
12959            mSettings.writePackageRestrictionsLPr(userId);
12960        }
12961        return true;
12962    }
12963
12964    @Override
12965    public boolean getBlockUninstallForUser(String packageName, int userId) {
12966        synchronized (mPackages) {
12967            PackageSetting ps = mSettings.mPackages.get(packageName);
12968            if (ps == null) {
12969                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12970                return false;
12971            }
12972            return ps.getBlockUninstall(userId);
12973        }
12974    }
12975
12976    /*
12977     * This method handles package deletion in general
12978     */
12979    private boolean deletePackageLI(String packageName, UserHandle user,
12980            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12981            int flags, PackageRemovedInfo outInfo,
12982            boolean writeSettings) {
12983        if (packageName == null) {
12984            Slog.w(TAG, "Attempt to delete null packageName.");
12985            return false;
12986        }
12987        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12988        PackageSetting ps;
12989        boolean dataOnly = false;
12990        int removeUser = -1;
12991        int appId = -1;
12992        synchronized (mPackages) {
12993            ps = mSettings.mPackages.get(packageName);
12994            if (ps == null) {
12995                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12996                return false;
12997            }
12998            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12999                    && user.getIdentifier() != UserHandle.USER_ALL) {
13000                // The caller is asking that the package only be deleted for a single
13001                // user.  To do this, we just mark its uninstalled state and delete
13002                // its data.  If this is a system app, we only allow this to happen if
13003                // they have set the special DELETE_SYSTEM_APP which requests different
13004                // semantics than normal for uninstalling system apps.
13005                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13006                ps.setUserState(user.getIdentifier(),
13007                        COMPONENT_ENABLED_STATE_DEFAULT,
13008                        false, //installed
13009                        true,  //stopped
13010                        true,  //notLaunched
13011                        false, //hidden
13012                        null, null, null,
13013                        false, // blockUninstall
13014                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0);
13015                if (!isSystemApp(ps)) {
13016                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13017                        // Other user still have this package installed, so all
13018                        // we need to do is clear this user's data and save that
13019                        // it is uninstalled.
13020                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13021                        removeUser = user.getIdentifier();
13022                        appId = ps.appId;
13023                        scheduleWritePackageRestrictionsLocked(removeUser);
13024                    } else {
13025                        // We need to set it back to 'installed' so the uninstall
13026                        // broadcasts will be sent correctly.
13027                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13028                        ps.setInstalled(true, user.getIdentifier());
13029                    }
13030                } else {
13031                    // This is a system app, so we assume that the
13032                    // other users still have this package installed, so all
13033                    // we need to do is clear this user's data and save that
13034                    // it is uninstalled.
13035                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13036                    removeUser = user.getIdentifier();
13037                    appId = ps.appId;
13038                    scheduleWritePackageRestrictionsLocked(removeUser);
13039                }
13040            }
13041        }
13042
13043        if (removeUser >= 0) {
13044            // From above, we determined that we are deleting this only
13045            // for a single user.  Continue the work here.
13046            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13047            if (outInfo != null) {
13048                outInfo.removedPackage = packageName;
13049                outInfo.removedAppId = appId;
13050                outInfo.removedUsers = new int[] {removeUser};
13051            }
13052            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13053            removeKeystoreDataIfNeeded(removeUser, appId);
13054            schedulePackageCleaning(packageName, removeUser, false);
13055            synchronized (mPackages) {
13056                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13057                    scheduleWritePackageRestrictionsLocked(removeUser);
13058                }
13059                resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser);
13060            }
13061            return true;
13062        }
13063
13064        if (dataOnly) {
13065            // Delete application data first
13066            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13067            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13068            return true;
13069        }
13070
13071        boolean ret = false;
13072        if (isSystemApp(ps)) {
13073            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13074            // When an updated system application is deleted we delete the existing resources as well and
13075            // fall back to existing code in system partition
13076            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13077                    flags, outInfo, writeSettings);
13078        } else {
13079            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13080            // Kill application pre-emptively especially for apps on sd.
13081            killApplication(packageName, ps.appId, "uninstall pkg");
13082            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13083                    allUserHandles, perUserInstalled,
13084                    outInfo, writeSettings);
13085        }
13086
13087        return ret;
13088    }
13089
13090    private final class ClearStorageConnection implements ServiceConnection {
13091        IMediaContainerService mContainerService;
13092
13093        @Override
13094        public void onServiceConnected(ComponentName name, IBinder service) {
13095            synchronized (this) {
13096                mContainerService = IMediaContainerService.Stub.asInterface(service);
13097                notifyAll();
13098            }
13099        }
13100
13101        @Override
13102        public void onServiceDisconnected(ComponentName name) {
13103        }
13104    }
13105
13106    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13107        final boolean mounted;
13108        if (Environment.isExternalStorageEmulated()) {
13109            mounted = true;
13110        } else {
13111            final String status = Environment.getExternalStorageState();
13112
13113            mounted = status.equals(Environment.MEDIA_MOUNTED)
13114                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13115        }
13116
13117        if (!mounted) {
13118            return;
13119        }
13120
13121        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13122        int[] users;
13123        if (userId == UserHandle.USER_ALL) {
13124            users = sUserManager.getUserIds();
13125        } else {
13126            users = new int[] { userId };
13127        }
13128        final ClearStorageConnection conn = new ClearStorageConnection();
13129        if (mContext.bindServiceAsUser(
13130                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13131            try {
13132                for (int curUser : users) {
13133                    long timeout = SystemClock.uptimeMillis() + 5000;
13134                    synchronized (conn) {
13135                        long now = SystemClock.uptimeMillis();
13136                        while (conn.mContainerService == null && now < timeout) {
13137                            try {
13138                                conn.wait(timeout - now);
13139                            } catch (InterruptedException e) {
13140                            }
13141                        }
13142                    }
13143                    if (conn.mContainerService == null) {
13144                        return;
13145                    }
13146
13147                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13148                    clearDirectory(conn.mContainerService,
13149                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13150                    if (allData) {
13151                        clearDirectory(conn.mContainerService,
13152                                userEnv.buildExternalStorageAppDataDirs(packageName));
13153                        clearDirectory(conn.mContainerService,
13154                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13155                    }
13156                }
13157            } finally {
13158                mContext.unbindService(conn);
13159            }
13160        }
13161    }
13162
13163    @Override
13164    public void clearApplicationUserData(final String packageName,
13165            final IPackageDataObserver observer, final int userId) {
13166        mContext.enforceCallingOrSelfPermission(
13167                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13168        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13169        // Queue up an async operation since the package deletion may take a little while.
13170        mHandler.post(new Runnable() {
13171            public void run() {
13172                mHandler.removeCallbacks(this);
13173                final boolean succeeded;
13174                synchronized (mInstallLock) {
13175                    succeeded = clearApplicationUserDataLI(packageName, userId);
13176                }
13177                clearExternalStorageDataSync(packageName, userId, true);
13178                if (succeeded) {
13179                    // invoke DeviceStorageMonitor's update method to clear any notifications
13180                    DeviceStorageMonitorInternal
13181                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13182                    if (dsm != null) {
13183                        dsm.checkMemory();
13184                    }
13185                }
13186                if(observer != null) {
13187                    try {
13188                        observer.onRemoveCompleted(packageName, succeeded);
13189                    } catch (RemoteException e) {
13190                        Log.i(TAG, "Observer no longer exists.");
13191                    }
13192                } //end if observer
13193            } //end run
13194        });
13195    }
13196
13197    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13198        if (packageName == null) {
13199            Slog.w(TAG, "Attempt to delete null packageName.");
13200            return false;
13201        }
13202
13203        // Try finding details about the requested package
13204        PackageParser.Package pkg;
13205        synchronized (mPackages) {
13206            pkg = mPackages.get(packageName);
13207            if (pkg == null) {
13208                final PackageSetting ps = mSettings.mPackages.get(packageName);
13209                if (ps != null) {
13210                    pkg = ps.pkg;
13211                }
13212            }
13213
13214            if (pkg == null) {
13215                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13216                return false;
13217            }
13218
13219            PackageSetting ps = (PackageSetting) pkg.mExtras;
13220            resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
13221        }
13222
13223        // Always delete data directories for package, even if we found no other
13224        // record of app. This helps users recover from UID mismatches without
13225        // resorting to a full data wipe.
13226        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13227        if (retCode < 0) {
13228            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13229            return false;
13230        }
13231
13232        final int appId = pkg.applicationInfo.uid;
13233        removeKeystoreDataIfNeeded(userId, appId);
13234
13235        // Create a native library symlink only if we have native libraries
13236        // and if the native libraries are 32 bit libraries. We do not provide
13237        // this symlink for 64 bit libraries.
13238        if (pkg.applicationInfo.primaryCpuAbi != null &&
13239                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13240            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13241            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13242                    nativeLibPath, userId) < 0) {
13243                Slog.w(TAG, "Failed linking native library dir");
13244                return false;
13245            }
13246        }
13247
13248        return true;
13249    }
13250
13251    /**
13252     * Reverts user permission state changes (permissions and flags).
13253     *
13254     * @param ps The package for which to reset.
13255     * @param userId The device user for which to do a reset.
13256     */
13257    private void resetUserChangesToRuntimePermissionsAndFlagsLocked(
13258            final PackageSetting ps, final int userId) {
13259        if (ps.pkg == null) {
13260            return;
13261        }
13262
13263        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13264                | FLAG_PERMISSION_USER_FIXED
13265                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13266
13267        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13268                | FLAG_PERMISSION_POLICY_FIXED;
13269
13270        boolean writeInstallPermissions = false;
13271        boolean writeRuntimePermissions = false;
13272
13273        final int permissionCount = ps.pkg.requestedPermissions.size();
13274        for (int i = 0; i < permissionCount; i++) {
13275            String permission = ps.pkg.requestedPermissions.get(i);
13276
13277            BasePermission bp = mSettings.mPermissions.get(permission);
13278            if (bp == null) {
13279                continue;
13280            }
13281
13282            // If shared user we just reset the state to which only this app contributed.
13283            if (ps.sharedUser != null) {
13284                boolean used = false;
13285                final int packageCount = ps.sharedUser.packages.size();
13286                for (int j = 0; j < packageCount; j++) {
13287                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13288                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13289                            && pkg.pkg.requestedPermissions.contains(permission)) {
13290                        used = true;
13291                        break;
13292                    }
13293                }
13294                if (used) {
13295                    continue;
13296                }
13297            }
13298
13299            PermissionsState permissionsState = ps.getPermissionsState();
13300
13301            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13302
13303            // Always clear the user settable flags.
13304            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13305                    bp.name) != null;
13306            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13307                if (hasInstallState) {
13308                    writeInstallPermissions = true;
13309                } else {
13310                    writeRuntimePermissions = true;
13311                }
13312            }
13313
13314            // Below is only runtime permission handling.
13315            if (!bp.isRuntime()) {
13316                continue;
13317            }
13318
13319            // Never clobber system or policy.
13320            if ((oldFlags & policyOrSystemFlags) != 0) {
13321                continue;
13322            }
13323
13324            // If this permission was granted by default, make sure it is.
13325            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13326                if (permissionsState.grantRuntimePermission(bp, userId)
13327                        != PERMISSION_OPERATION_FAILURE) {
13328                    writeRuntimePermissions = true;
13329                }
13330            } else {
13331                // Otherwise, reset the permission.
13332                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13333                switch (revokeResult) {
13334                    case PERMISSION_OPERATION_SUCCESS: {
13335                        writeRuntimePermissions = true;
13336                    } break;
13337
13338                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13339                        writeRuntimePermissions = true;
13340                        // If gids changed for this user, kill all affected packages.
13341                        mHandler.post(new Runnable() {
13342                            @Override
13343                            public void run() {
13344                                // This has to happen with no lock held.
13345                                killSettingPackagesForUser(ps, userId,
13346                                        KILL_APP_REASON_GIDS_CHANGED);
13347                            }
13348                        });
13349                    } break;
13350                }
13351            }
13352        }
13353
13354        // Synchronously write as we are taking permissions away.
13355        if (writeRuntimePermissions) {
13356            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13357        }
13358
13359        // Synchronously write as we are taking permissions away.
13360        if (writeInstallPermissions) {
13361            mSettings.writeLPr();
13362        }
13363    }
13364
13365    /**
13366     * Remove entries from the keystore daemon. Will only remove it if the
13367     * {@code appId} is valid.
13368     */
13369    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13370        if (appId < 0) {
13371            return;
13372        }
13373
13374        final KeyStore keyStore = KeyStore.getInstance();
13375        if (keyStore != null) {
13376            if (userId == UserHandle.USER_ALL) {
13377                for (final int individual : sUserManager.getUserIds()) {
13378                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13379                }
13380            } else {
13381                keyStore.clearUid(UserHandle.getUid(userId, appId));
13382            }
13383        } else {
13384            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13385        }
13386    }
13387
13388    @Override
13389    public void deleteApplicationCacheFiles(final String packageName,
13390            final IPackageDataObserver observer) {
13391        mContext.enforceCallingOrSelfPermission(
13392                android.Manifest.permission.DELETE_CACHE_FILES, null);
13393        // Queue up an async operation since the package deletion may take a little while.
13394        final int userId = UserHandle.getCallingUserId();
13395        mHandler.post(new Runnable() {
13396            public void run() {
13397                mHandler.removeCallbacks(this);
13398                final boolean succeded;
13399                synchronized (mInstallLock) {
13400                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13401                }
13402                clearExternalStorageDataSync(packageName, userId, false);
13403                if (observer != null) {
13404                    try {
13405                        observer.onRemoveCompleted(packageName, succeded);
13406                    } catch (RemoteException e) {
13407                        Log.i(TAG, "Observer no longer exists.");
13408                    }
13409                } //end if observer
13410            } //end run
13411        });
13412    }
13413
13414    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13415        if (packageName == null) {
13416            Slog.w(TAG, "Attempt to delete null packageName.");
13417            return false;
13418        }
13419        PackageParser.Package p;
13420        synchronized (mPackages) {
13421            p = mPackages.get(packageName);
13422        }
13423        if (p == null) {
13424            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13425            return false;
13426        }
13427        final ApplicationInfo applicationInfo = p.applicationInfo;
13428        if (applicationInfo == null) {
13429            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13430            return false;
13431        }
13432        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13433        if (retCode < 0) {
13434            Slog.w(TAG, "Couldn't remove cache files for package: "
13435                       + packageName + " u" + userId);
13436            return false;
13437        }
13438        return true;
13439    }
13440
13441    @Override
13442    public void getPackageSizeInfo(final String packageName, int userHandle,
13443            final IPackageStatsObserver observer) {
13444        mContext.enforceCallingOrSelfPermission(
13445                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13446        if (packageName == null) {
13447            throw new IllegalArgumentException("Attempt to get size of null packageName");
13448        }
13449
13450        PackageStats stats = new PackageStats(packageName, userHandle);
13451
13452        /*
13453         * Queue up an async operation since the package measurement may take a
13454         * little while.
13455         */
13456        Message msg = mHandler.obtainMessage(INIT_COPY);
13457        msg.obj = new MeasureParams(stats, observer);
13458        mHandler.sendMessage(msg);
13459    }
13460
13461    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13462            PackageStats pStats) {
13463        if (packageName == null) {
13464            Slog.w(TAG, "Attempt to get size of null packageName.");
13465            return false;
13466        }
13467        PackageParser.Package p;
13468        boolean dataOnly = false;
13469        String libDirRoot = null;
13470        String asecPath = null;
13471        PackageSetting ps = null;
13472        synchronized (mPackages) {
13473            p = mPackages.get(packageName);
13474            ps = mSettings.mPackages.get(packageName);
13475            if(p == null) {
13476                dataOnly = true;
13477                if((ps == null) || (ps.pkg == null)) {
13478                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13479                    return false;
13480                }
13481                p = ps.pkg;
13482            }
13483            if (ps != null) {
13484                libDirRoot = ps.legacyNativeLibraryPathString;
13485            }
13486            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13487                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13488                if (secureContainerId != null) {
13489                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13490                }
13491            }
13492        }
13493        String publicSrcDir = null;
13494        if(!dataOnly) {
13495            final ApplicationInfo applicationInfo = p.applicationInfo;
13496            if (applicationInfo == null) {
13497                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13498                return false;
13499            }
13500            if (p.isForwardLocked()) {
13501                publicSrcDir = applicationInfo.getBaseResourcePath();
13502            }
13503        }
13504        // TODO: extend to measure size of split APKs
13505        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13506        // not just the first level.
13507        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13508        // just the primary.
13509        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13510        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13511                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13512        if (res < 0) {
13513            return false;
13514        }
13515
13516        // Fix-up for forward-locked applications in ASEC containers.
13517        if (!isExternal(p)) {
13518            pStats.codeSize += pStats.externalCodeSize;
13519            pStats.externalCodeSize = 0L;
13520        }
13521
13522        return true;
13523    }
13524
13525
13526    @Override
13527    public void addPackageToPreferred(String packageName) {
13528        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13529    }
13530
13531    @Override
13532    public void removePackageFromPreferred(String packageName) {
13533        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13534    }
13535
13536    @Override
13537    public List<PackageInfo> getPreferredPackages(int flags) {
13538        return new ArrayList<PackageInfo>();
13539    }
13540
13541    private int getUidTargetSdkVersionLockedLPr(int uid) {
13542        Object obj = mSettings.getUserIdLPr(uid);
13543        if (obj instanceof SharedUserSetting) {
13544            final SharedUserSetting sus = (SharedUserSetting) obj;
13545            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13546            final Iterator<PackageSetting> it = sus.packages.iterator();
13547            while (it.hasNext()) {
13548                final PackageSetting ps = it.next();
13549                if (ps.pkg != null) {
13550                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13551                    if (v < vers) vers = v;
13552                }
13553            }
13554            return vers;
13555        } else if (obj instanceof PackageSetting) {
13556            final PackageSetting ps = (PackageSetting) obj;
13557            if (ps.pkg != null) {
13558                return ps.pkg.applicationInfo.targetSdkVersion;
13559            }
13560        }
13561        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13562    }
13563
13564    @Override
13565    public void addPreferredActivity(IntentFilter filter, int match,
13566            ComponentName[] set, ComponentName activity, int userId) {
13567        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13568                "Adding preferred");
13569    }
13570
13571    private void addPreferredActivityInternal(IntentFilter filter, int match,
13572            ComponentName[] set, ComponentName activity, boolean always, int userId,
13573            String opname) {
13574        // writer
13575        int callingUid = Binder.getCallingUid();
13576        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13577        if (filter.countActions() == 0) {
13578            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13579            return;
13580        }
13581        synchronized (mPackages) {
13582            if (mContext.checkCallingOrSelfPermission(
13583                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13584                    != PackageManager.PERMISSION_GRANTED) {
13585                if (getUidTargetSdkVersionLockedLPr(callingUid)
13586                        < Build.VERSION_CODES.FROYO) {
13587                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13588                            + callingUid);
13589                    return;
13590                }
13591                mContext.enforceCallingOrSelfPermission(
13592                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13593            }
13594
13595            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13596            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13597                    + userId + ":");
13598            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13599            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13600            scheduleWritePackageRestrictionsLocked(userId);
13601        }
13602    }
13603
13604    @Override
13605    public void replacePreferredActivity(IntentFilter filter, int match,
13606            ComponentName[] set, ComponentName activity, int userId) {
13607        if (filter.countActions() != 1) {
13608            throw new IllegalArgumentException(
13609                    "replacePreferredActivity expects filter to have only 1 action.");
13610        }
13611        if (filter.countDataAuthorities() != 0
13612                || filter.countDataPaths() != 0
13613                || filter.countDataSchemes() > 1
13614                || filter.countDataTypes() != 0) {
13615            throw new IllegalArgumentException(
13616                    "replacePreferredActivity expects filter to have no data authorities, " +
13617                    "paths, or types; and at most one scheme.");
13618        }
13619
13620        final int callingUid = Binder.getCallingUid();
13621        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13622        synchronized (mPackages) {
13623            if (mContext.checkCallingOrSelfPermission(
13624                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13625                    != PackageManager.PERMISSION_GRANTED) {
13626                if (getUidTargetSdkVersionLockedLPr(callingUid)
13627                        < Build.VERSION_CODES.FROYO) {
13628                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13629                            + Binder.getCallingUid());
13630                    return;
13631                }
13632                mContext.enforceCallingOrSelfPermission(
13633                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13634            }
13635
13636            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13637            if (pir != null) {
13638                // Get all of the existing entries that exactly match this filter.
13639                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13640                if (existing != null && existing.size() == 1) {
13641                    PreferredActivity cur = existing.get(0);
13642                    if (DEBUG_PREFERRED) {
13643                        Slog.i(TAG, "Checking replace of preferred:");
13644                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13645                        if (!cur.mPref.mAlways) {
13646                            Slog.i(TAG, "  -- CUR; not mAlways!");
13647                        } else {
13648                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13649                            Slog.i(TAG, "  -- CUR: mSet="
13650                                    + Arrays.toString(cur.mPref.mSetComponents));
13651                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13652                            Slog.i(TAG, "  -- NEW: mMatch="
13653                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13654                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13655                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13656                        }
13657                    }
13658                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13659                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13660                            && cur.mPref.sameSet(set)) {
13661                        // Setting the preferred activity to what it happens to be already
13662                        if (DEBUG_PREFERRED) {
13663                            Slog.i(TAG, "Replacing with same preferred activity "
13664                                    + cur.mPref.mShortComponent + " for user "
13665                                    + userId + ":");
13666                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13667                        }
13668                        return;
13669                    }
13670                }
13671
13672                if (existing != null) {
13673                    if (DEBUG_PREFERRED) {
13674                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13675                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13676                    }
13677                    for (int i = 0; i < existing.size(); i++) {
13678                        PreferredActivity pa = existing.get(i);
13679                        if (DEBUG_PREFERRED) {
13680                            Slog.i(TAG, "Removing existing preferred activity "
13681                                    + pa.mPref.mComponent + ":");
13682                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13683                        }
13684                        pir.removeFilter(pa);
13685                    }
13686                }
13687            }
13688            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13689                    "Replacing preferred");
13690        }
13691    }
13692
13693    @Override
13694    public void clearPackagePreferredActivities(String packageName) {
13695        final int uid = Binder.getCallingUid();
13696        // writer
13697        synchronized (mPackages) {
13698            PackageParser.Package pkg = mPackages.get(packageName);
13699            if (pkg == null || pkg.applicationInfo.uid != uid) {
13700                if (mContext.checkCallingOrSelfPermission(
13701                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13702                        != PackageManager.PERMISSION_GRANTED) {
13703                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13704                            < Build.VERSION_CODES.FROYO) {
13705                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13706                                + Binder.getCallingUid());
13707                        return;
13708                    }
13709                    mContext.enforceCallingOrSelfPermission(
13710                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13711                }
13712            }
13713
13714            int user = UserHandle.getCallingUserId();
13715            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13716                scheduleWritePackageRestrictionsLocked(user);
13717            }
13718        }
13719    }
13720
13721    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13722    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13723        ArrayList<PreferredActivity> removed = null;
13724        boolean changed = false;
13725        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13726            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13727            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13728            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13729                continue;
13730            }
13731            Iterator<PreferredActivity> it = pir.filterIterator();
13732            while (it.hasNext()) {
13733                PreferredActivity pa = it.next();
13734                // Mark entry for removal only if it matches the package name
13735                // and the entry is of type "always".
13736                if (packageName == null ||
13737                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13738                                && pa.mPref.mAlways)) {
13739                    if (removed == null) {
13740                        removed = new ArrayList<PreferredActivity>();
13741                    }
13742                    removed.add(pa);
13743                }
13744            }
13745            if (removed != null) {
13746                for (int j=0; j<removed.size(); j++) {
13747                    PreferredActivity pa = removed.get(j);
13748                    pir.removeFilter(pa);
13749                }
13750                changed = true;
13751            }
13752        }
13753        return changed;
13754    }
13755
13756    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13757    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13758        if (userId == UserHandle.USER_ALL) {
13759            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13760                    sUserManager.getUserIds())) {
13761                for (int oneUserId : sUserManager.getUserIds()) {
13762                    scheduleWritePackageRestrictionsLocked(oneUserId);
13763                }
13764            }
13765        } else {
13766            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13767                scheduleWritePackageRestrictionsLocked(userId);
13768            }
13769        }
13770    }
13771
13772
13773    void clearDefaultBrowserIfNeeded(String packageName) {
13774        for (int oneUserId : sUserManager.getUserIds()) {
13775            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13776            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13777            if (packageName.equals(defaultBrowserPackageName)) {
13778                setDefaultBrowserPackageName(null, oneUserId);
13779            }
13780        }
13781    }
13782
13783    @Override
13784    public void resetPreferredActivities(int userId) {
13785        mContext.enforceCallingOrSelfPermission(
13786                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13787        // writer
13788        synchronized (mPackages) {
13789            clearPackagePreferredActivitiesLPw(null, userId);
13790            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13791            applyFactoryDefaultBrowserLPw(userId);
13792            primeDomainVerificationsLPw(userId);
13793
13794            scheduleWritePackageRestrictionsLocked(userId);
13795        }
13796    }
13797
13798    @Override
13799    public int getPreferredActivities(List<IntentFilter> outFilters,
13800            List<ComponentName> outActivities, String packageName) {
13801
13802        int num = 0;
13803        final int userId = UserHandle.getCallingUserId();
13804        // reader
13805        synchronized (mPackages) {
13806            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13807            if (pir != null) {
13808                final Iterator<PreferredActivity> it = pir.filterIterator();
13809                while (it.hasNext()) {
13810                    final PreferredActivity pa = it.next();
13811                    if (packageName == null
13812                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13813                                    && pa.mPref.mAlways)) {
13814                        if (outFilters != null) {
13815                            outFilters.add(new IntentFilter(pa));
13816                        }
13817                        if (outActivities != null) {
13818                            outActivities.add(pa.mPref.mComponent);
13819                        }
13820                    }
13821                }
13822            }
13823        }
13824
13825        return num;
13826    }
13827
13828    @Override
13829    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13830            int userId) {
13831        int callingUid = Binder.getCallingUid();
13832        if (callingUid != Process.SYSTEM_UID) {
13833            throw new SecurityException(
13834                    "addPersistentPreferredActivity can only be run by the system");
13835        }
13836        if (filter.countActions() == 0) {
13837            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13838            return;
13839        }
13840        synchronized (mPackages) {
13841            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13842                    " :");
13843            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13844            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13845                    new PersistentPreferredActivity(filter, activity));
13846            scheduleWritePackageRestrictionsLocked(userId);
13847        }
13848    }
13849
13850    @Override
13851    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13852        int callingUid = Binder.getCallingUid();
13853        if (callingUid != Process.SYSTEM_UID) {
13854            throw new SecurityException(
13855                    "clearPackagePersistentPreferredActivities can only be run by the system");
13856        }
13857        ArrayList<PersistentPreferredActivity> removed = null;
13858        boolean changed = false;
13859        synchronized (mPackages) {
13860            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13861                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13862                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13863                        .valueAt(i);
13864                if (userId != thisUserId) {
13865                    continue;
13866                }
13867                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13868                while (it.hasNext()) {
13869                    PersistentPreferredActivity ppa = it.next();
13870                    // Mark entry for removal only if it matches the package name.
13871                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13872                        if (removed == null) {
13873                            removed = new ArrayList<PersistentPreferredActivity>();
13874                        }
13875                        removed.add(ppa);
13876                    }
13877                }
13878                if (removed != null) {
13879                    for (int j=0; j<removed.size(); j++) {
13880                        PersistentPreferredActivity ppa = removed.get(j);
13881                        ppir.removeFilter(ppa);
13882                    }
13883                    changed = true;
13884                }
13885            }
13886
13887            if (changed) {
13888                scheduleWritePackageRestrictionsLocked(userId);
13889            }
13890        }
13891    }
13892
13893    /**
13894     * Common machinery for picking apart a restored XML blob and passing
13895     * it to a caller-supplied functor to be applied to the running system.
13896     */
13897    private void restoreFromXml(XmlPullParser parser, int userId,
13898            String expectedStartTag, BlobXmlRestorer functor)
13899            throws IOException, XmlPullParserException {
13900        int type;
13901        while ((type = parser.next()) != XmlPullParser.START_TAG
13902                && type != XmlPullParser.END_DOCUMENT) {
13903        }
13904        if (type != XmlPullParser.START_TAG) {
13905            // oops didn't find a start tag?!
13906            if (DEBUG_BACKUP) {
13907                Slog.e(TAG, "Didn't find start tag during restore");
13908            }
13909            return;
13910        }
13911
13912        // this is supposed to be TAG_PREFERRED_BACKUP
13913        if (!expectedStartTag.equals(parser.getName())) {
13914            if (DEBUG_BACKUP) {
13915                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13916            }
13917            return;
13918        }
13919
13920        // skip interfering stuff, then we're aligned with the backing implementation
13921        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13922        functor.apply(parser, userId);
13923    }
13924
13925    private interface BlobXmlRestorer {
13926        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13927    }
13928
13929    /**
13930     * Non-Binder method, support for the backup/restore mechanism: write the
13931     * full set of preferred activities in its canonical XML format.  Returns the
13932     * XML output as a byte array, or null if there is none.
13933     */
13934    @Override
13935    public byte[] getPreferredActivityBackup(int userId) {
13936        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13937            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13938        }
13939
13940        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13941        try {
13942            final XmlSerializer serializer = new FastXmlSerializer();
13943            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13944            serializer.startDocument(null, true);
13945            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13946
13947            synchronized (mPackages) {
13948                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13949            }
13950
13951            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13952            serializer.endDocument();
13953            serializer.flush();
13954        } catch (Exception e) {
13955            if (DEBUG_BACKUP) {
13956                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13957            }
13958            return null;
13959        }
13960
13961        return dataStream.toByteArray();
13962    }
13963
13964    @Override
13965    public void restorePreferredActivities(byte[] backup, int userId) {
13966        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13967            throw new SecurityException("Only the system may call restorePreferredActivities()");
13968        }
13969
13970        try {
13971            final XmlPullParser parser = Xml.newPullParser();
13972            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13973            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13974                    new BlobXmlRestorer() {
13975                        @Override
13976                        public void apply(XmlPullParser parser, int userId)
13977                                throws XmlPullParserException, IOException {
13978                            synchronized (mPackages) {
13979                                mSettings.readPreferredActivitiesLPw(parser, userId);
13980                            }
13981                        }
13982                    } );
13983        } catch (Exception e) {
13984            if (DEBUG_BACKUP) {
13985                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13986            }
13987        }
13988    }
13989
13990    /**
13991     * Non-Binder method, support for the backup/restore mechanism: write the
13992     * default browser (etc) settings in its canonical XML format.  Returns the default
13993     * browser XML representation as a byte array, or null if there is none.
13994     */
13995    @Override
13996    public byte[] getDefaultAppsBackup(int userId) {
13997        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13998            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13999        }
14000
14001        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14002        try {
14003            final XmlSerializer serializer = new FastXmlSerializer();
14004            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14005            serializer.startDocument(null, true);
14006            serializer.startTag(null, TAG_DEFAULT_APPS);
14007
14008            synchronized (mPackages) {
14009                mSettings.writeDefaultAppsLPr(serializer, userId);
14010            }
14011
14012            serializer.endTag(null, TAG_DEFAULT_APPS);
14013            serializer.endDocument();
14014            serializer.flush();
14015        } catch (Exception e) {
14016            if (DEBUG_BACKUP) {
14017                Slog.e(TAG, "Unable to write default apps for backup", e);
14018            }
14019            return null;
14020        }
14021
14022        return dataStream.toByteArray();
14023    }
14024
14025    @Override
14026    public void restoreDefaultApps(byte[] backup, int userId) {
14027        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14028            throw new SecurityException("Only the system may call restoreDefaultApps()");
14029        }
14030
14031        try {
14032            final XmlPullParser parser = Xml.newPullParser();
14033            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14034            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14035                    new BlobXmlRestorer() {
14036                        @Override
14037                        public void apply(XmlPullParser parser, int userId)
14038                                throws XmlPullParserException, IOException {
14039                            synchronized (mPackages) {
14040                                mSettings.readDefaultAppsLPw(parser, userId);
14041                            }
14042                        }
14043                    } );
14044        } catch (Exception e) {
14045            if (DEBUG_BACKUP) {
14046                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14047            }
14048        }
14049    }
14050
14051    @Override
14052    public byte[] getIntentFilterVerificationBackup(int userId) {
14053        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14054            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14055        }
14056
14057        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14058        try {
14059            final XmlSerializer serializer = new FastXmlSerializer();
14060            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14061            serializer.startDocument(null, true);
14062            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14063
14064            synchronized (mPackages) {
14065                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14066            }
14067
14068            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14069            serializer.endDocument();
14070            serializer.flush();
14071        } catch (Exception e) {
14072            if (DEBUG_BACKUP) {
14073                Slog.e(TAG, "Unable to write default apps for backup", e);
14074            }
14075            return null;
14076        }
14077
14078        return dataStream.toByteArray();
14079    }
14080
14081    @Override
14082    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14083        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14084            throw new SecurityException("Only the system may call restorePreferredActivities()");
14085        }
14086
14087        try {
14088            final XmlPullParser parser = Xml.newPullParser();
14089            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14090            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14091                    new BlobXmlRestorer() {
14092                        @Override
14093                        public void apply(XmlPullParser parser, int userId)
14094                                throws XmlPullParserException, IOException {
14095                            synchronized (mPackages) {
14096                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14097                                mSettings.writeLPr();
14098                            }
14099                        }
14100                    } );
14101        } catch (Exception e) {
14102            if (DEBUG_BACKUP) {
14103                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14104            }
14105        }
14106    }
14107
14108    @Override
14109    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14110            int sourceUserId, int targetUserId, int flags) {
14111        mContext.enforceCallingOrSelfPermission(
14112                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14113        int callingUid = Binder.getCallingUid();
14114        enforceOwnerRights(ownerPackage, callingUid);
14115        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14116        if (intentFilter.countActions() == 0) {
14117            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14118            return;
14119        }
14120        synchronized (mPackages) {
14121            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14122                    ownerPackage, targetUserId, flags);
14123            CrossProfileIntentResolver resolver =
14124                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14125            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14126            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14127            if (existing != null) {
14128                int size = existing.size();
14129                for (int i = 0; i < size; i++) {
14130                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14131                        return;
14132                    }
14133                }
14134            }
14135            resolver.addFilter(newFilter);
14136            scheduleWritePackageRestrictionsLocked(sourceUserId);
14137        }
14138    }
14139
14140    @Override
14141    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14142        mContext.enforceCallingOrSelfPermission(
14143                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14144        int callingUid = Binder.getCallingUid();
14145        enforceOwnerRights(ownerPackage, callingUid);
14146        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14147        synchronized (mPackages) {
14148            CrossProfileIntentResolver resolver =
14149                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14150            ArraySet<CrossProfileIntentFilter> set =
14151                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14152            for (CrossProfileIntentFilter filter : set) {
14153                if (filter.getOwnerPackage().equals(ownerPackage)) {
14154                    resolver.removeFilter(filter);
14155                }
14156            }
14157            scheduleWritePackageRestrictionsLocked(sourceUserId);
14158        }
14159    }
14160
14161    // Enforcing that callingUid is owning pkg on userId
14162    private void enforceOwnerRights(String pkg, int callingUid) {
14163        // The system owns everything.
14164        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14165            return;
14166        }
14167        int callingUserId = UserHandle.getUserId(callingUid);
14168        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14169        if (pi == null) {
14170            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14171                    + callingUserId);
14172        }
14173        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14174            throw new SecurityException("Calling uid " + callingUid
14175                    + " does not own package " + pkg);
14176        }
14177    }
14178
14179    @Override
14180    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14181        Intent intent = new Intent(Intent.ACTION_MAIN);
14182        intent.addCategory(Intent.CATEGORY_HOME);
14183
14184        final int callingUserId = UserHandle.getCallingUserId();
14185        List<ResolveInfo> list = queryIntentActivities(intent, null,
14186                PackageManager.GET_META_DATA, callingUserId);
14187        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14188                true, false, false, callingUserId);
14189
14190        allHomeCandidates.clear();
14191        if (list != null) {
14192            for (ResolveInfo ri : list) {
14193                allHomeCandidates.add(ri);
14194            }
14195        }
14196        return (preferred == null || preferred.activityInfo == null)
14197                ? null
14198                : new ComponentName(preferred.activityInfo.packageName,
14199                        preferred.activityInfo.name);
14200    }
14201
14202    @Override
14203    public void setApplicationEnabledSetting(String appPackageName,
14204            int newState, int flags, int userId, String callingPackage) {
14205        if (!sUserManager.exists(userId)) return;
14206        if (callingPackage == null) {
14207            callingPackage = Integer.toString(Binder.getCallingUid());
14208        }
14209        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14210    }
14211
14212    @Override
14213    public void setComponentEnabledSetting(ComponentName componentName,
14214            int newState, int flags, int userId) {
14215        if (!sUserManager.exists(userId)) return;
14216        setEnabledSetting(componentName.getPackageName(),
14217                componentName.getClassName(), newState, flags, userId, null);
14218    }
14219
14220    private void setEnabledSetting(final String packageName, String className, int newState,
14221            final int flags, int userId, String callingPackage) {
14222        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14223              || newState == COMPONENT_ENABLED_STATE_ENABLED
14224              || newState == COMPONENT_ENABLED_STATE_DISABLED
14225              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14226              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14227            throw new IllegalArgumentException("Invalid new component state: "
14228                    + newState);
14229        }
14230        PackageSetting pkgSetting;
14231        final int uid = Binder.getCallingUid();
14232        final int permission = mContext.checkCallingOrSelfPermission(
14233                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14234        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14235        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14236        boolean sendNow = false;
14237        boolean isApp = (className == null);
14238        String componentName = isApp ? packageName : className;
14239        int packageUid = -1;
14240        ArrayList<String> components;
14241
14242        // writer
14243        synchronized (mPackages) {
14244            pkgSetting = mSettings.mPackages.get(packageName);
14245            if (pkgSetting == null) {
14246                if (className == null) {
14247                    throw new IllegalArgumentException(
14248                            "Unknown package: " + packageName);
14249                }
14250                throw new IllegalArgumentException(
14251                        "Unknown component: " + packageName
14252                        + "/" + className);
14253            }
14254            // Allow root and verify that userId is not being specified by a different user
14255            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14256                throw new SecurityException(
14257                        "Permission Denial: attempt to change component state from pid="
14258                        + Binder.getCallingPid()
14259                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14260            }
14261            if (className == null) {
14262                // We're dealing with an application/package level state change
14263                if (pkgSetting.getEnabled(userId) == newState) {
14264                    // Nothing to do
14265                    return;
14266                }
14267                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14268                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14269                    // Don't care about who enables an app.
14270                    callingPackage = null;
14271                }
14272                pkgSetting.setEnabled(newState, userId, callingPackage);
14273                // pkgSetting.pkg.mSetEnabled = newState;
14274            } else {
14275                // We're dealing with a component level state change
14276                // First, verify that this is a valid class name.
14277                PackageParser.Package pkg = pkgSetting.pkg;
14278                if (pkg == null || !pkg.hasComponentClassName(className)) {
14279                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14280                        throw new IllegalArgumentException("Component class " + className
14281                                + " does not exist in " + packageName);
14282                    } else {
14283                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14284                                + className + " does not exist in " + packageName);
14285                    }
14286                }
14287                switch (newState) {
14288                case COMPONENT_ENABLED_STATE_ENABLED:
14289                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14290                        return;
14291                    }
14292                    break;
14293                case COMPONENT_ENABLED_STATE_DISABLED:
14294                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14295                        return;
14296                    }
14297                    break;
14298                case COMPONENT_ENABLED_STATE_DEFAULT:
14299                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14300                        return;
14301                    }
14302                    break;
14303                default:
14304                    Slog.e(TAG, "Invalid new component state: " + newState);
14305                    return;
14306                }
14307            }
14308            scheduleWritePackageRestrictionsLocked(userId);
14309            components = mPendingBroadcasts.get(userId, packageName);
14310            final boolean newPackage = components == null;
14311            if (newPackage) {
14312                components = new ArrayList<String>();
14313            }
14314            if (!components.contains(componentName)) {
14315                components.add(componentName);
14316            }
14317            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14318                sendNow = true;
14319                // Purge entry from pending broadcast list if another one exists already
14320                // since we are sending one right away.
14321                mPendingBroadcasts.remove(userId, packageName);
14322            } else {
14323                if (newPackage) {
14324                    mPendingBroadcasts.put(userId, packageName, components);
14325                }
14326                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14327                    // Schedule a message
14328                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14329                }
14330            }
14331        }
14332
14333        long callingId = Binder.clearCallingIdentity();
14334        try {
14335            if (sendNow) {
14336                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14337                sendPackageChangedBroadcast(packageName,
14338                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14339            }
14340        } finally {
14341            Binder.restoreCallingIdentity(callingId);
14342        }
14343    }
14344
14345    private void sendPackageChangedBroadcast(String packageName,
14346            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14347        if (DEBUG_INSTALL)
14348            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14349                    + componentNames);
14350        Bundle extras = new Bundle(4);
14351        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14352        String nameList[] = new String[componentNames.size()];
14353        componentNames.toArray(nameList);
14354        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14355        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14356        extras.putInt(Intent.EXTRA_UID, packageUid);
14357        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14358                new int[] {UserHandle.getUserId(packageUid)});
14359    }
14360
14361    @Override
14362    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14363        if (!sUserManager.exists(userId)) return;
14364        final int uid = Binder.getCallingUid();
14365        final int permission = mContext.checkCallingOrSelfPermission(
14366                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14367        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14368        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14369        // writer
14370        synchronized (mPackages) {
14371            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14372                    allowedByPermission, uid, userId)) {
14373                scheduleWritePackageRestrictionsLocked(userId);
14374            }
14375        }
14376    }
14377
14378    @Override
14379    public String getInstallerPackageName(String packageName) {
14380        // reader
14381        synchronized (mPackages) {
14382            return mSettings.getInstallerPackageNameLPr(packageName);
14383        }
14384    }
14385
14386    @Override
14387    public int getApplicationEnabledSetting(String packageName, int userId) {
14388        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14389        int uid = Binder.getCallingUid();
14390        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14391        // reader
14392        synchronized (mPackages) {
14393            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14394        }
14395    }
14396
14397    @Override
14398    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14399        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14400        int uid = Binder.getCallingUid();
14401        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14402        // reader
14403        synchronized (mPackages) {
14404            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14405        }
14406    }
14407
14408    @Override
14409    public void enterSafeMode() {
14410        enforceSystemOrRoot("Only the system can request entering safe mode");
14411
14412        if (!mSystemReady) {
14413            mSafeMode = true;
14414        }
14415    }
14416
14417    @Override
14418    public void systemReady() {
14419        mSystemReady = true;
14420
14421        // Read the compatibilty setting when the system is ready.
14422        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14423                mContext.getContentResolver(),
14424                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14425        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14426        if (DEBUG_SETTINGS) {
14427            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14428        }
14429
14430        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14431
14432        synchronized (mPackages) {
14433            // Verify that all of the preferred activity components actually
14434            // exist.  It is possible for applications to be updated and at
14435            // that point remove a previously declared activity component that
14436            // had been set as a preferred activity.  We try to clean this up
14437            // the next time we encounter that preferred activity, but it is
14438            // possible for the user flow to never be able to return to that
14439            // situation so here we do a sanity check to make sure we haven't
14440            // left any junk around.
14441            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14442            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14443                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14444                removed.clear();
14445                for (PreferredActivity pa : pir.filterSet()) {
14446                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14447                        removed.add(pa);
14448                    }
14449                }
14450                if (removed.size() > 0) {
14451                    for (int r=0; r<removed.size(); r++) {
14452                        PreferredActivity pa = removed.get(r);
14453                        Slog.w(TAG, "Removing dangling preferred activity: "
14454                                + pa.mPref.mComponent);
14455                        pir.removeFilter(pa);
14456                    }
14457                    mSettings.writePackageRestrictionsLPr(
14458                            mSettings.mPreferredActivities.keyAt(i));
14459                }
14460            }
14461
14462            for (int userId : UserManagerService.getInstance().getUserIds()) {
14463                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14464                    grantPermissionsUserIds = ArrayUtils.appendInt(
14465                            grantPermissionsUserIds, userId);
14466                }
14467            }
14468        }
14469        sUserManager.systemReady();
14470
14471        // If we upgraded grant all default permissions before kicking off.
14472        for (int userId : grantPermissionsUserIds) {
14473            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14474        }
14475
14476        // Kick off any messages waiting for system ready
14477        if (mPostSystemReadyMessages != null) {
14478            for (Message msg : mPostSystemReadyMessages) {
14479                msg.sendToTarget();
14480            }
14481            mPostSystemReadyMessages = null;
14482        }
14483
14484        // Watch for external volumes that come and go over time
14485        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14486        storage.registerListener(mStorageListener);
14487
14488        mInstallerService.systemReady();
14489        mPackageDexOptimizer.systemReady();
14490
14491        MountServiceInternal mountServiceInternal = LocalServices.getService(
14492                MountServiceInternal.class);
14493        mountServiceInternal.addExternalStoragePolicy(
14494                new MountServiceInternal.ExternalStorageMountPolicy() {
14495            @Override
14496            public int getMountMode(int uid, String packageName) {
14497                if (Process.isIsolated(uid)) {
14498                    return Zygote.MOUNT_EXTERNAL_NONE;
14499                }
14500                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14501                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14502                }
14503                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14504                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14505                }
14506                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14507                    return Zygote.MOUNT_EXTERNAL_READ;
14508                }
14509                return Zygote.MOUNT_EXTERNAL_WRITE;
14510            }
14511
14512            @Override
14513            public boolean hasExternalStorage(int uid, String packageName) {
14514                return true;
14515            }
14516        });
14517    }
14518
14519    @Override
14520    public boolean isSafeMode() {
14521        return mSafeMode;
14522    }
14523
14524    @Override
14525    public boolean hasSystemUidErrors() {
14526        return mHasSystemUidErrors;
14527    }
14528
14529    static String arrayToString(int[] array) {
14530        StringBuffer buf = new StringBuffer(128);
14531        buf.append('[');
14532        if (array != null) {
14533            for (int i=0; i<array.length; i++) {
14534                if (i > 0) buf.append(", ");
14535                buf.append(array[i]);
14536            }
14537        }
14538        buf.append(']');
14539        return buf.toString();
14540    }
14541
14542    static class DumpState {
14543        public static final int DUMP_LIBS = 1 << 0;
14544        public static final int DUMP_FEATURES = 1 << 1;
14545        public static final int DUMP_RESOLVERS = 1 << 2;
14546        public static final int DUMP_PERMISSIONS = 1 << 3;
14547        public static final int DUMP_PACKAGES = 1 << 4;
14548        public static final int DUMP_SHARED_USERS = 1 << 5;
14549        public static final int DUMP_MESSAGES = 1 << 6;
14550        public static final int DUMP_PROVIDERS = 1 << 7;
14551        public static final int DUMP_VERIFIERS = 1 << 8;
14552        public static final int DUMP_PREFERRED = 1 << 9;
14553        public static final int DUMP_PREFERRED_XML = 1 << 10;
14554        public static final int DUMP_KEYSETS = 1 << 11;
14555        public static final int DUMP_VERSION = 1 << 12;
14556        public static final int DUMP_INSTALLS = 1 << 13;
14557        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14558        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14559
14560        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14561
14562        private int mTypes;
14563
14564        private int mOptions;
14565
14566        private boolean mTitlePrinted;
14567
14568        private SharedUserSetting mSharedUser;
14569
14570        public boolean isDumping(int type) {
14571            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14572                return true;
14573            }
14574
14575            return (mTypes & type) != 0;
14576        }
14577
14578        public void setDump(int type) {
14579            mTypes |= type;
14580        }
14581
14582        public boolean isOptionEnabled(int option) {
14583            return (mOptions & option) != 0;
14584        }
14585
14586        public void setOptionEnabled(int option) {
14587            mOptions |= option;
14588        }
14589
14590        public boolean onTitlePrinted() {
14591            final boolean printed = mTitlePrinted;
14592            mTitlePrinted = true;
14593            return printed;
14594        }
14595
14596        public boolean getTitlePrinted() {
14597            return mTitlePrinted;
14598        }
14599
14600        public void setTitlePrinted(boolean enabled) {
14601            mTitlePrinted = enabled;
14602        }
14603
14604        public SharedUserSetting getSharedUser() {
14605            return mSharedUser;
14606        }
14607
14608        public void setSharedUser(SharedUserSetting user) {
14609            mSharedUser = user;
14610        }
14611    }
14612
14613    @Override
14614    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14615        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14616                != PackageManager.PERMISSION_GRANTED) {
14617            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14618                    + Binder.getCallingPid()
14619                    + ", uid=" + Binder.getCallingUid()
14620                    + " without permission "
14621                    + android.Manifest.permission.DUMP);
14622            return;
14623        }
14624
14625        DumpState dumpState = new DumpState();
14626        boolean fullPreferred = false;
14627        boolean checkin = false;
14628
14629        String packageName = null;
14630        ArraySet<String> permissionNames = null;
14631
14632        int opti = 0;
14633        while (opti < args.length) {
14634            String opt = args[opti];
14635            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14636                break;
14637            }
14638            opti++;
14639
14640            if ("-a".equals(opt)) {
14641                // Right now we only know how to print all.
14642            } else if ("-h".equals(opt)) {
14643                pw.println("Package manager dump options:");
14644                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14645                pw.println("    --checkin: dump for a checkin");
14646                pw.println("    -f: print details of intent filters");
14647                pw.println("    -h: print this help");
14648                pw.println("  cmd may be one of:");
14649                pw.println("    l[ibraries]: list known shared libraries");
14650                pw.println("    f[ibraries]: list device features");
14651                pw.println("    k[eysets]: print known keysets");
14652                pw.println("    r[esolvers]: dump intent resolvers");
14653                pw.println("    perm[issions]: dump permissions");
14654                pw.println("    permission [name ...]: dump declaration and use of given permission");
14655                pw.println("    pref[erred]: print preferred package settings");
14656                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14657                pw.println("    prov[iders]: dump content providers");
14658                pw.println("    p[ackages]: dump installed packages");
14659                pw.println("    s[hared-users]: dump shared user IDs");
14660                pw.println("    m[essages]: print collected runtime messages");
14661                pw.println("    v[erifiers]: print package verifier info");
14662                pw.println("    version: print database version info");
14663                pw.println("    write: write current settings now");
14664                pw.println("    <package.name>: info about given package");
14665                pw.println("    installs: details about install sessions");
14666                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14667                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14668                return;
14669            } else if ("--checkin".equals(opt)) {
14670                checkin = true;
14671            } else if ("-f".equals(opt)) {
14672                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14673            } else {
14674                pw.println("Unknown argument: " + opt + "; use -h for help");
14675            }
14676        }
14677
14678        // Is the caller requesting to dump a particular piece of data?
14679        if (opti < args.length) {
14680            String cmd = args[opti];
14681            opti++;
14682            // Is this a package name?
14683            if ("android".equals(cmd) || cmd.contains(".")) {
14684                packageName = cmd;
14685                // When dumping a single package, we always dump all of its
14686                // filter information since the amount of data will be reasonable.
14687                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14688            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14689                dumpState.setDump(DumpState.DUMP_LIBS);
14690            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14691                dumpState.setDump(DumpState.DUMP_FEATURES);
14692            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14693                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14694            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14695                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14696            } else if ("permission".equals(cmd)) {
14697                if (opti >= args.length) {
14698                    pw.println("Error: permission requires permission name");
14699                    return;
14700                }
14701                permissionNames = new ArraySet<>();
14702                while (opti < args.length) {
14703                    permissionNames.add(args[opti]);
14704                    opti++;
14705                }
14706                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14707                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14708            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14709                dumpState.setDump(DumpState.DUMP_PREFERRED);
14710            } else if ("preferred-xml".equals(cmd)) {
14711                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14712                if (opti < args.length && "--full".equals(args[opti])) {
14713                    fullPreferred = true;
14714                    opti++;
14715                }
14716            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14717                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14718            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14719                dumpState.setDump(DumpState.DUMP_PACKAGES);
14720            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14721                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14722            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14723                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14724            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14725                dumpState.setDump(DumpState.DUMP_MESSAGES);
14726            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14727                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14728            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14729                    || "intent-filter-verifiers".equals(cmd)) {
14730                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14731            } else if ("version".equals(cmd)) {
14732                dumpState.setDump(DumpState.DUMP_VERSION);
14733            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14734                dumpState.setDump(DumpState.DUMP_KEYSETS);
14735            } else if ("installs".equals(cmd)) {
14736                dumpState.setDump(DumpState.DUMP_INSTALLS);
14737            } else if ("write".equals(cmd)) {
14738                synchronized (mPackages) {
14739                    mSettings.writeLPr();
14740                    pw.println("Settings written.");
14741                    return;
14742                }
14743            }
14744        }
14745
14746        if (checkin) {
14747            pw.println("vers,1");
14748        }
14749
14750        // reader
14751        synchronized (mPackages) {
14752            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14753                if (!checkin) {
14754                    if (dumpState.onTitlePrinted())
14755                        pw.println();
14756                    pw.println("Database versions:");
14757                    pw.print("  SDK Version:");
14758                    pw.print(" internal=");
14759                    pw.print(mSettings.mInternalSdkPlatform);
14760                    pw.print(" external=");
14761                    pw.println(mSettings.mExternalSdkPlatform);
14762                    pw.print("  DB Version:");
14763                    pw.print(" internal=");
14764                    pw.print(mSettings.mInternalDatabaseVersion);
14765                    pw.print(" external=");
14766                    pw.println(mSettings.mExternalDatabaseVersion);
14767                }
14768            }
14769
14770            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14771                if (!checkin) {
14772                    if (dumpState.onTitlePrinted())
14773                        pw.println();
14774                    pw.println("Verifiers:");
14775                    pw.print("  Required: ");
14776                    pw.print(mRequiredVerifierPackage);
14777                    pw.print(" (uid=");
14778                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14779                    pw.println(")");
14780                } else if (mRequiredVerifierPackage != null) {
14781                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14782                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14783                }
14784            }
14785
14786            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14787                    packageName == null) {
14788                if (mIntentFilterVerifierComponent != null) {
14789                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14790                    if (!checkin) {
14791                        if (dumpState.onTitlePrinted())
14792                            pw.println();
14793                        pw.println("Intent Filter Verifier:");
14794                        pw.print("  Using: ");
14795                        pw.print(verifierPackageName);
14796                        pw.print(" (uid=");
14797                        pw.print(getPackageUid(verifierPackageName, 0));
14798                        pw.println(")");
14799                    } else if (verifierPackageName != null) {
14800                        pw.print("ifv,"); pw.print(verifierPackageName);
14801                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14802                    }
14803                } else {
14804                    pw.println();
14805                    pw.println("No Intent Filter Verifier available!");
14806                }
14807            }
14808
14809            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14810                boolean printedHeader = false;
14811                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14812                while (it.hasNext()) {
14813                    String name = it.next();
14814                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14815                    if (!checkin) {
14816                        if (!printedHeader) {
14817                            if (dumpState.onTitlePrinted())
14818                                pw.println();
14819                            pw.println("Libraries:");
14820                            printedHeader = true;
14821                        }
14822                        pw.print("  ");
14823                    } else {
14824                        pw.print("lib,");
14825                    }
14826                    pw.print(name);
14827                    if (!checkin) {
14828                        pw.print(" -> ");
14829                    }
14830                    if (ent.path != null) {
14831                        if (!checkin) {
14832                            pw.print("(jar) ");
14833                            pw.print(ent.path);
14834                        } else {
14835                            pw.print(",jar,");
14836                            pw.print(ent.path);
14837                        }
14838                    } else {
14839                        if (!checkin) {
14840                            pw.print("(apk) ");
14841                            pw.print(ent.apk);
14842                        } else {
14843                            pw.print(",apk,");
14844                            pw.print(ent.apk);
14845                        }
14846                    }
14847                    pw.println();
14848                }
14849            }
14850
14851            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14852                if (dumpState.onTitlePrinted())
14853                    pw.println();
14854                if (!checkin) {
14855                    pw.println("Features:");
14856                }
14857                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14858                while (it.hasNext()) {
14859                    String name = it.next();
14860                    if (!checkin) {
14861                        pw.print("  ");
14862                    } else {
14863                        pw.print("feat,");
14864                    }
14865                    pw.println(name);
14866                }
14867            }
14868
14869            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14870                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14871                        : "Activity Resolver Table:", "  ", packageName,
14872                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14873                    dumpState.setTitlePrinted(true);
14874                }
14875                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14876                        : "Receiver Resolver Table:", "  ", packageName,
14877                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14878                    dumpState.setTitlePrinted(true);
14879                }
14880                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14881                        : "Service Resolver Table:", "  ", packageName,
14882                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14883                    dumpState.setTitlePrinted(true);
14884                }
14885                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14886                        : "Provider Resolver Table:", "  ", packageName,
14887                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14888                    dumpState.setTitlePrinted(true);
14889                }
14890            }
14891
14892            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14893                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14894                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14895                    int user = mSettings.mPreferredActivities.keyAt(i);
14896                    if (pir.dump(pw,
14897                            dumpState.getTitlePrinted()
14898                                ? "\nPreferred Activities User " + user + ":"
14899                                : "Preferred Activities User " + user + ":", "  ",
14900                            packageName, true, false)) {
14901                        dumpState.setTitlePrinted(true);
14902                    }
14903                }
14904            }
14905
14906            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14907                pw.flush();
14908                FileOutputStream fout = new FileOutputStream(fd);
14909                BufferedOutputStream str = new BufferedOutputStream(fout);
14910                XmlSerializer serializer = new FastXmlSerializer();
14911                try {
14912                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14913                    serializer.startDocument(null, true);
14914                    serializer.setFeature(
14915                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14916                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14917                    serializer.endDocument();
14918                    serializer.flush();
14919                } catch (IllegalArgumentException e) {
14920                    pw.println("Failed writing: " + e);
14921                } catch (IllegalStateException e) {
14922                    pw.println("Failed writing: " + e);
14923                } catch (IOException e) {
14924                    pw.println("Failed writing: " + e);
14925                }
14926            }
14927
14928            if (!checkin
14929                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14930                    && packageName == null) {
14931                pw.println();
14932                int count = mSettings.mPackages.size();
14933                if (count == 0) {
14934                    pw.println("No applications!");
14935                    pw.println();
14936                } else {
14937                    final String prefix = "  ";
14938                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14939                    if (allPackageSettings.size() == 0) {
14940                        pw.println("No domain preferred apps!");
14941                        pw.println();
14942                    } else {
14943                        pw.println("App verification status:");
14944                        pw.println();
14945                        count = 0;
14946                        for (PackageSetting ps : allPackageSettings) {
14947                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14948                            if (ivi == null || ivi.getPackageName() == null) continue;
14949                            pw.println(prefix + "Package: " + ivi.getPackageName());
14950                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14951                            pw.println(prefix + "Status:  " + ivi.getStatusString());
14952                            pw.println();
14953                            count++;
14954                        }
14955                        if (count == 0) {
14956                            pw.println(prefix + "No app verification established.");
14957                            pw.println();
14958                        }
14959                        for (int userId : sUserManager.getUserIds()) {
14960                            pw.println("App linkages for user " + userId + ":");
14961                            pw.println();
14962                            count = 0;
14963                            for (PackageSetting ps : allPackageSettings) {
14964                                final long status = ps.getDomainVerificationStatusForUser(userId);
14965                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14966                                    continue;
14967                                }
14968                                pw.println(prefix + "Package: " + ps.name);
14969                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
14970                                String statusStr = IntentFilterVerificationInfo.
14971                                        getStatusStringFromValue(status);
14972                                pw.println(prefix + "Status:  " + statusStr);
14973                                pw.println();
14974                                count++;
14975                            }
14976                            if (count == 0) {
14977                                pw.println(prefix + "No configured app linkages.");
14978                                pw.println();
14979                            }
14980                        }
14981                    }
14982                }
14983            }
14984
14985            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14986                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14987                if (packageName == null && permissionNames == null) {
14988                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14989                        if (iperm == 0) {
14990                            if (dumpState.onTitlePrinted())
14991                                pw.println();
14992                            pw.println("AppOp Permissions:");
14993                        }
14994                        pw.print("  AppOp Permission ");
14995                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14996                        pw.println(":");
14997                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14998                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14999                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15000                        }
15001                    }
15002                }
15003            }
15004
15005            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15006                boolean printedSomething = false;
15007                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15008                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15009                        continue;
15010                    }
15011                    if (!printedSomething) {
15012                        if (dumpState.onTitlePrinted())
15013                            pw.println();
15014                        pw.println("Registered ContentProviders:");
15015                        printedSomething = true;
15016                    }
15017                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15018                    pw.print("    "); pw.println(p.toString());
15019                }
15020                printedSomething = false;
15021                for (Map.Entry<String, PackageParser.Provider> entry :
15022                        mProvidersByAuthority.entrySet()) {
15023                    PackageParser.Provider p = entry.getValue();
15024                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15025                        continue;
15026                    }
15027                    if (!printedSomething) {
15028                        if (dumpState.onTitlePrinted())
15029                            pw.println();
15030                        pw.println("ContentProvider Authorities:");
15031                        printedSomething = true;
15032                    }
15033                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15034                    pw.print("    "); pw.println(p.toString());
15035                    if (p.info != null && p.info.applicationInfo != null) {
15036                        final String appInfo = p.info.applicationInfo.toString();
15037                        pw.print("      applicationInfo="); pw.println(appInfo);
15038                    }
15039                }
15040            }
15041
15042            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15043                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15044            }
15045
15046            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15047                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15048            }
15049
15050            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15051                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15052            }
15053
15054            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15055                // XXX should handle packageName != null by dumping only install data that
15056                // the given package is involved with.
15057                if (dumpState.onTitlePrinted()) pw.println();
15058                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15059            }
15060
15061            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15062                if (dumpState.onTitlePrinted()) pw.println();
15063                mSettings.dumpReadMessagesLPr(pw, dumpState);
15064
15065                pw.println();
15066                pw.println("Package warning messages:");
15067                BufferedReader in = null;
15068                String line = null;
15069                try {
15070                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15071                    while ((line = in.readLine()) != null) {
15072                        if (line.contains("ignored: updated version")) continue;
15073                        pw.println(line);
15074                    }
15075                } catch (IOException ignored) {
15076                } finally {
15077                    IoUtils.closeQuietly(in);
15078                }
15079            }
15080
15081            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15082                BufferedReader in = null;
15083                String line = null;
15084                try {
15085                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15086                    while ((line = in.readLine()) != null) {
15087                        if (line.contains("ignored: updated version")) continue;
15088                        pw.print("msg,");
15089                        pw.println(line);
15090                    }
15091                } catch (IOException ignored) {
15092                } finally {
15093                    IoUtils.closeQuietly(in);
15094                }
15095            }
15096        }
15097    }
15098
15099    private String dumpDomainString(String packageName) {
15100        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15101        List<IntentFilter> filters = getAllIntentFilters(packageName);
15102
15103        ArraySet<String> result = new ArraySet<>();
15104        if (iviList.size() > 0) {
15105            for (IntentFilterVerificationInfo ivi : iviList) {
15106                for (String host : ivi.getDomains()) {
15107                    result.add(host);
15108                }
15109            }
15110        }
15111        if (filters != null && filters.size() > 0) {
15112            for (IntentFilter filter : filters) {
15113                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15114                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15115                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15116                    result.addAll(filter.getHostsList());
15117                }
15118            }
15119        }
15120
15121        StringBuilder sb = new StringBuilder(result.size() * 16);
15122        for (String domain : result) {
15123            if (sb.length() > 0) sb.append(" ");
15124            sb.append(domain);
15125        }
15126        return sb.toString();
15127    }
15128
15129    // ------- apps on sdcard specific code -------
15130    static final boolean DEBUG_SD_INSTALL = false;
15131
15132    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15133
15134    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15135
15136    private boolean mMediaMounted = false;
15137
15138    static String getEncryptKey() {
15139        try {
15140            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15141                    SD_ENCRYPTION_KEYSTORE_NAME);
15142            if (sdEncKey == null) {
15143                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15144                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15145                if (sdEncKey == null) {
15146                    Slog.e(TAG, "Failed to create encryption keys");
15147                    return null;
15148                }
15149            }
15150            return sdEncKey;
15151        } catch (NoSuchAlgorithmException nsae) {
15152            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15153            return null;
15154        } catch (IOException ioe) {
15155            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15156            return null;
15157        }
15158    }
15159
15160    /*
15161     * Update media status on PackageManager.
15162     */
15163    @Override
15164    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15165        int callingUid = Binder.getCallingUid();
15166        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15167            throw new SecurityException("Media status can only be updated by the system");
15168        }
15169        // reader; this apparently protects mMediaMounted, but should probably
15170        // be a different lock in that case.
15171        synchronized (mPackages) {
15172            Log.i(TAG, "Updating external media status from "
15173                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15174                    + (mediaStatus ? "mounted" : "unmounted"));
15175            if (DEBUG_SD_INSTALL)
15176                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15177                        + ", mMediaMounted=" + mMediaMounted);
15178            if (mediaStatus == mMediaMounted) {
15179                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15180                        : 0, -1);
15181                mHandler.sendMessage(msg);
15182                return;
15183            }
15184            mMediaMounted = mediaStatus;
15185        }
15186        // Queue up an async operation since the package installation may take a
15187        // little while.
15188        mHandler.post(new Runnable() {
15189            public void run() {
15190                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15191            }
15192        });
15193    }
15194
15195    /**
15196     * Called by MountService when the initial ASECs to scan are available.
15197     * Should block until all the ASEC containers are finished being scanned.
15198     */
15199    public void scanAvailableAsecs() {
15200        updateExternalMediaStatusInner(true, false, false);
15201        if (mShouldRestoreconData) {
15202            SELinuxMMAC.setRestoreconDone();
15203            mShouldRestoreconData = false;
15204        }
15205    }
15206
15207    /*
15208     * Collect information of applications on external media, map them against
15209     * existing containers and update information based on current mount status.
15210     * Please note that we always have to report status if reportStatus has been
15211     * set to true especially when unloading packages.
15212     */
15213    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15214            boolean externalStorage) {
15215        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15216        int[] uidArr = EmptyArray.INT;
15217
15218        final String[] list = PackageHelper.getSecureContainerList();
15219        if (ArrayUtils.isEmpty(list)) {
15220            Log.i(TAG, "No secure containers found");
15221        } else {
15222            // Process list of secure containers and categorize them
15223            // as active or stale based on their package internal state.
15224
15225            // reader
15226            synchronized (mPackages) {
15227                for (String cid : list) {
15228                    // Leave stages untouched for now; installer service owns them
15229                    if (PackageInstallerService.isStageName(cid)) continue;
15230
15231                    if (DEBUG_SD_INSTALL)
15232                        Log.i(TAG, "Processing container " + cid);
15233                    String pkgName = getAsecPackageName(cid);
15234                    if (pkgName == null) {
15235                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15236                        continue;
15237                    }
15238                    if (DEBUG_SD_INSTALL)
15239                        Log.i(TAG, "Looking for pkg : " + pkgName);
15240
15241                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15242                    if (ps == null) {
15243                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15244                        continue;
15245                    }
15246
15247                    /*
15248                     * Skip packages that are not external if we're unmounting
15249                     * external storage.
15250                     */
15251                    if (externalStorage && !isMounted && !isExternal(ps)) {
15252                        continue;
15253                    }
15254
15255                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15256                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15257                    // The package status is changed only if the code path
15258                    // matches between settings and the container id.
15259                    if (ps.codePathString != null
15260                            && ps.codePathString.startsWith(args.getCodePath())) {
15261                        if (DEBUG_SD_INSTALL) {
15262                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15263                                    + " at code path: " + ps.codePathString);
15264                        }
15265
15266                        // We do have a valid package installed on sdcard
15267                        processCids.put(args, ps.codePathString);
15268                        final int uid = ps.appId;
15269                        if (uid != -1) {
15270                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15271                        }
15272                    } else {
15273                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15274                                + ps.codePathString);
15275                    }
15276                }
15277            }
15278
15279            Arrays.sort(uidArr);
15280        }
15281
15282        // Process packages with valid entries.
15283        if (isMounted) {
15284            if (DEBUG_SD_INSTALL)
15285                Log.i(TAG, "Loading packages");
15286            loadMediaPackages(processCids, uidArr);
15287            startCleaningPackages();
15288            mInstallerService.onSecureContainersAvailable();
15289        } else {
15290            if (DEBUG_SD_INSTALL)
15291                Log.i(TAG, "Unloading packages");
15292            unloadMediaPackages(processCids, uidArr, reportStatus);
15293        }
15294    }
15295
15296    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15297            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15298        final int size = infos.size();
15299        final String[] packageNames = new String[size];
15300        final int[] packageUids = new int[size];
15301        for (int i = 0; i < size; i++) {
15302            final ApplicationInfo info = infos.get(i);
15303            packageNames[i] = info.packageName;
15304            packageUids[i] = info.uid;
15305        }
15306        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15307                finishedReceiver);
15308    }
15309
15310    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15311            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15312        sendResourcesChangedBroadcast(mediaStatus, replacing,
15313                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15314    }
15315
15316    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15317            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15318        int size = pkgList.length;
15319        if (size > 0) {
15320            // Send broadcasts here
15321            Bundle extras = new Bundle();
15322            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15323            if (uidArr != null) {
15324                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15325            }
15326            if (replacing) {
15327                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15328            }
15329            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15330                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15331            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15332        }
15333    }
15334
15335   /*
15336     * Look at potentially valid container ids from processCids If package
15337     * information doesn't match the one on record or package scanning fails,
15338     * the cid is added to list of removeCids. We currently don't delete stale
15339     * containers.
15340     */
15341    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15342        ArrayList<String> pkgList = new ArrayList<String>();
15343        Set<AsecInstallArgs> keys = processCids.keySet();
15344
15345        for (AsecInstallArgs args : keys) {
15346            String codePath = processCids.get(args);
15347            if (DEBUG_SD_INSTALL)
15348                Log.i(TAG, "Loading container : " + args.cid);
15349            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15350            try {
15351                // Make sure there are no container errors first.
15352                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15353                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15354                            + " when installing from sdcard");
15355                    continue;
15356                }
15357                // Check code path here.
15358                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15359                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15360                            + " does not match one in settings " + codePath);
15361                    continue;
15362                }
15363                // Parse package
15364                int parseFlags = mDefParseFlags;
15365                if (args.isExternalAsec()) {
15366                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15367                }
15368                if (args.isFwdLocked()) {
15369                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15370                }
15371
15372                synchronized (mInstallLock) {
15373                    PackageParser.Package pkg = null;
15374                    try {
15375                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15376                    } catch (PackageManagerException e) {
15377                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15378                    }
15379                    // Scan the package
15380                    if (pkg != null) {
15381                        /*
15382                         * TODO why is the lock being held? doPostInstall is
15383                         * called in other places without the lock. This needs
15384                         * to be straightened out.
15385                         */
15386                        // writer
15387                        synchronized (mPackages) {
15388                            retCode = PackageManager.INSTALL_SUCCEEDED;
15389                            pkgList.add(pkg.packageName);
15390                            // Post process args
15391                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15392                                    pkg.applicationInfo.uid);
15393                        }
15394                    } else {
15395                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15396                    }
15397                }
15398
15399            } finally {
15400                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15401                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15402                }
15403            }
15404        }
15405        // writer
15406        synchronized (mPackages) {
15407            // If the platform SDK has changed since the last time we booted,
15408            // we need to re-grant app permission to catch any new ones that
15409            // appear. This is really a hack, and means that apps can in some
15410            // cases get permissions that the user didn't initially explicitly
15411            // allow... it would be nice to have some better way to handle
15412            // this situation.
15413            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15414            if (regrantPermissions)
15415                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15416                        + mSdkVersion + "; regranting permissions for external storage");
15417            mSettings.mExternalSdkPlatform = mSdkVersion;
15418
15419            // Make sure group IDs have been assigned, and any permission
15420            // changes in other apps are accounted for
15421            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15422                    | (regrantPermissions
15423                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15424                            : 0));
15425
15426            mSettings.updateExternalDatabaseVersion();
15427
15428            // can downgrade to reader
15429            // Persist settings
15430            mSettings.writeLPr();
15431        }
15432        // Send a broadcast to let everyone know we are done processing
15433        if (pkgList.size() > 0) {
15434            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15435        }
15436    }
15437
15438   /*
15439     * Utility method to unload a list of specified containers
15440     */
15441    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15442        // Just unmount all valid containers.
15443        for (AsecInstallArgs arg : cidArgs) {
15444            synchronized (mInstallLock) {
15445                arg.doPostDeleteLI(false);
15446           }
15447       }
15448   }
15449
15450    /*
15451     * Unload packages mounted on external media. This involves deleting package
15452     * data from internal structures, sending broadcasts about diabled packages,
15453     * gc'ing to free up references, unmounting all secure containers
15454     * corresponding to packages on external media, and posting a
15455     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15456     * that we always have to post this message if status has been requested no
15457     * matter what.
15458     */
15459    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15460            final boolean reportStatus) {
15461        if (DEBUG_SD_INSTALL)
15462            Log.i(TAG, "unloading media packages");
15463        ArrayList<String> pkgList = new ArrayList<String>();
15464        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15465        final Set<AsecInstallArgs> keys = processCids.keySet();
15466        for (AsecInstallArgs args : keys) {
15467            String pkgName = args.getPackageName();
15468            if (DEBUG_SD_INSTALL)
15469                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15470            // Delete package internally
15471            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15472            synchronized (mInstallLock) {
15473                boolean res = deletePackageLI(pkgName, null, false, null, null,
15474                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15475                if (res) {
15476                    pkgList.add(pkgName);
15477                } else {
15478                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15479                    failedList.add(args);
15480                }
15481            }
15482        }
15483
15484        // reader
15485        synchronized (mPackages) {
15486            // We didn't update the settings after removing each package;
15487            // write them now for all packages.
15488            mSettings.writeLPr();
15489        }
15490
15491        // We have to absolutely send UPDATED_MEDIA_STATUS only
15492        // after confirming that all the receivers processed the ordered
15493        // broadcast when packages get disabled, force a gc to clean things up.
15494        // and unload all the containers.
15495        if (pkgList.size() > 0) {
15496            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15497                    new IIntentReceiver.Stub() {
15498                public void performReceive(Intent intent, int resultCode, String data,
15499                        Bundle extras, boolean ordered, boolean sticky,
15500                        int sendingUser) throws RemoteException {
15501                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15502                            reportStatus ? 1 : 0, 1, keys);
15503                    mHandler.sendMessage(msg);
15504                }
15505            });
15506        } else {
15507            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15508                    keys);
15509            mHandler.sendMessage(msg);
15510        }
15511    }
15512
15513    private void loadPrivatePackages(VolumeInfo vol) {
15514        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15515        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15516        synchronized (mInstallLock) {
15517        synchronized (mPackages) {
15518            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15519            for (PackageSetting ps : packages) {
15520                final PackageParser.Package pkg;
15521                try {
15522                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15523                    loaded.add(pkg.applicationInfo);
15524                } catch (PackageManagerException e) {
15525                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15526                }
15527            }
15528
15529            // TODO: regrant any permissions that changed based since original install
15530
15531            mSettings.writeLPr();
15532        }
15533        }
15534
15535        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15536        sendResourcesChangedBroadcast(true, false, loaded, null);
15537    }
15538
15539    private void unloadPrivatePackages(VolumeInfo vol) {
15540        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15541        synchronized (mInstallLock) {
15542        synchronized (mPackages) {
15543            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15544            for (PackageSetting ps : packages) {
15545                if (ps.pkg == null) continue;
15546
15547                final ApplicationInfo info = ps.pkg.applicationInfo;
15548                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15549                if (deletePackageLI(ps.name, null, false, null, null,
15550                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15551                    unloaded.add(info);
15552                } else {
15553                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15554                }
15555            }
15556
15557            mSettings.writeLPr();
15558        }
15559        }
15560
15561        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15562        sendResourcesChangedBroadcast(false, false, unloaded, null);
15563    }
15564
15565    /**
15566     * Examine all users present on given mounted volume, and destroy data
15567     * belonging to users that are no longer valid, or whose user ID has been
15568     * recycled.
15569     */
15570    private void reconcileUsers(String volumeUuid) {
15571        final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
15572        if (ArrayUtils.isEmpty(files)) {
15573            Slog.d(TAG, "No users found on " + volumeUuid);
15574            return;
15575        }
15576
15577        for (File file : files) {
15578            if (!file.isDirectory()) continue;
15579
15580            final int userId;
15581            final UserInfo info;
15582            try {
15583                userId = Integer.parseInt(file.getName());
15584                info = sUserManager.getUserInfo(userId);
15585            } catch (NumberFormatException e) {
15586                Slog.w(TAG, "Invalid user directory " + file);
15587                continue;
15588            }
15589
15590            boolean destroyUser = false;
15591            if (info == null) {
15592                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15593                        + " because no matching user was found");
15594                destroyUser = true;
15595            } else {
15596                try {
15597                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15598                } catch (IOException e) {
15599                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15600                            + " because we failed to enforce serial number: " + e);
15601                    destroyUser = true;
15602                }
15603            }
15604
15605            if (destroyUser) {
15606                synchronized (mInstallLock) {
15607                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15608                }
15609            }
15610        }
15611
15612        final UserManager um = mContext.getSystemService(UserManager.class);
15613        for (UserInfo user : um.getUsers()) {
15614            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15615            if (userDir.exists()) continue;
15616
15617            try {
15618                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15619                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15620            } catch (IOException e) {
15621                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15622            }
15623        }
15624    }
15625
15626    /**
15627     * Examine all apps present on given mounted volume, and destroy apps that
15628     * aren't expected, either due to uninstallation or reinstallation on
15629     * another volume.
15630     */
15631    private void reconcileApps(String volumeUuid) {
15632        final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
15633        if (ArrayUtils.isEmpty(files)) {
15634            Slog.d(TAG, "No apps found on " + volumeUuid);
15635            return;
15636        }
15637
15638        for (File file : files) {
15639            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15640                    && !PackageInstallerService.isStageName(file.getName());
15641            if (!isPackage) {
15642                // Ignore entries which are not packages
15643                continue;
15644            }
15645
15646            boolean destroyApp = false;
15647            String packageName = null;
15648            try {
15649                final PackageLite pkg = PackageParser.parsePackageLite(file,
15650                        PackageParser.PARSE_MUST_BE_APK);
15651                packageName = pkg.packageName;
15652
15653                synchronized (mPackages) {
15654                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15655                    if (ps == null) {
15656                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15657                                + volumeUuid + " because we found no install record");
15658                        destroyApp = true;
15659                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15660                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15661                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15662                        destroyApp = true;
15663                    }
15664                }
15665
15666            } catch (PackageParserException e) {
15667                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15668                destroyApp = true;
15669            }
15670
15671            if (destroyApp) {
15672                synchronized (mInstallLock) {
15673                    if (packageName != null) {
15674                        removeDataDirsLI(volumeUuid, packageName);
15675                    }
15676                    if (file.isDirectory()) {
15677                        mInstaller.rmPackageDir(file.getAbsolutePath());
15678                    } else {
15679                        file.delete();
15680                    }
15681                }
15682            }
15683        }
15684    }
15685
15686    private void unfreezePackage(String packageName) {
15687        synchronized (mPackages) {
15688            final PackageSetting ps = mSettings.mPackages.get(packageName);
15689            if (ps != null) {
15690                ps.frozen = false;
15691            }
15692        }
15693    }
15694
15695    @Override
15696    public int movePackage(final String packageName, final String volumeUuid) {
15697        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15698
15699        final int moveId = mNextMoveId.getAndIncrement();
15700        try {
15701            movePackageInternal(packageName, volumeUuid, moveId);
15702        } catch (PackageManagerException e) {
15703            Slog.w(TAG, "Failed to move " + packageName, e);
15704            mMoveCallbacks.notifyStatusChanged(moveId,
15705                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15706        }
15707        return moveId;
15708    }
15709
15710    private void movePackageInternal(final String packageName, final String volumeUuid,
15711            final int moveId) throws PackageManagerException {
15712        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15713        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15714        final PackageManager pm = mContext.getPackageManager();
15715
15716        final boolean currentAsec;
15717        final String currentVolumeUuid;
15718        final File codeFile;
15719        final String installerPackageName;
15720        final String packageAbiOverride;
15721        final int appId;
15722        final String seinfo;
15723        final String label;
15724
15725        // reader
15726        synchronized (mPackages) {
15727            final PackageParser.Package pkg = mPackages.get(packageName);
15728            final PackageSetting ps = mSettings.mPackages.get(packageName);
15729            if (pkg == null || ps == null) {
15730                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15731            }
15732
15733            if (pkg.applicationInfo.isSystemApp()) {
15734                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15735                        "Cannot move system application");
15736            }
15737
15738            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15739                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15740                        "Package already moved to " + volumeUuid);
15741            }
15742
15743            final File probe = new File(pkg.codePath);
15744            final File probeOat = new File(probe, "oat");
15745            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15746                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15747                        "Move only supported for modern cluster style installs");
15748            }
15749
15750            if (ps.frozen) {
15751                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15752                        "Failed to move already frozen package");
15753            }
15754            ps.frozen = true;
15755
15756            currentAsec = pkg.applicationInfo.isForwardLocked()
15757                    || pkg.applicationInfo.isExternalAsec();
15758            currentVolumeUuid = ps.volumeUuid;
15759            codeFile = new File(pkg.codePath);
15760            installerPackageName = ps.installerPackageName;
15761            packageAbiOverride = ps.cpuAbiOverrideString;
15762            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15763            seinfo = pkg.applicationInfo.seinfo;
15764            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15765        }
15766
15767        // Now that we're guarded by frozen state, kill app during move
15768        killApplication(packageName, appId, "move pkg");
15769
15770        final Bundle extras = new Bundle();
15771        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15772        extras.putString(Intent.EXTRA_TITLE, label);
15773        mMoveCallbacks.notifyCreated(moveId, extras);
15774
15775        int installFlags;
15776        final boolean moveCompleteApp;
15777        final File measurePath;
15778
15779        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15780            installFlags = INSTALL_INTERNAL;
15781            moveCompleteApp = !currentAsec;
15782            measurePath = Environment.getDataAppDirectory(volumeUuid);
15783        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15784            installFlags = INSTALL_EXTERNAL;
15785            moveCompleteApp = false;
15786            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15787        } else {
15788            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15789            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15790                    || !volume.isMountedWritable()) {
15791                unfreezePackage(packageName);
15792                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15793                        "Move location not mounted private volume");
15794            }
15795
15796            Preconditions.checkState(!currentAsec);
15797
15798            installFlags = INSTALL_INTERNAL;
15799            moveCompleteApp = true;
15800            measurePath = Environment.getDataAppDirectory(volumeUuid);
15801        }
15802
15803        final PackageStats stats = new PackageStats(null, -1);
15804        synchronized (mInstaller) {
15805            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15806                unfreezePackage(packageName);
15807                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15808                        "Failed to measure package size");
15809            }
15810        }
15811
15812        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15813                + stats.dataSize);
15814
15815        final long startFreeBytes = measurePath.getFreeSpace();
15816        final long sizeBytes;
15817        if (moveCompleteApp) {
15818            sizeBytes = stats.codeSize + stats.dataSize;
15819        } else {
15820            sizeBytes = stats.codeSize;
15821        }
15822
15823        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15824            unfreezePackage(packageName);
15825            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15826                    "Not enough free space to move");
15827        }
15828
15829        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15830
15831        final CountDownLatch installedLatch = new CountDownLatch(1);
15832        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15833            @Override
15834            public void onUserActionRequired(Intent intent) throws RemoteException {
15835                throw new IllegalStateException();
15836            }
15837
15838            @Override
15839            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15840                    Bundle extras) throws RemoteException {
15841                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15842                        + PackageManager.installStatusToString(returnCode, msg));
15843
15844                installedLatch.countDown();
15845
15846                // Regardless of success or failure of the move operation,
15847                // always unfreeze the package
15848                unfreezePackage(packageName);
15849
15850                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15851                switch (status) {
15852                    case PackageInstaller.STATUS_SUCCESS:
15853                        mMoveCallbacks.notifyStatusChanged(moveId,
15854                                PackageManager.MOVE_SUCCEEDED);
15855                        break;
15856                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15857                        mMoveCallbacks.notifyStatusChanged(moveId,
15858                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15859                        break;
15860                    default:
15861                        mMoveCallbacks.notifyStatusChanged(moveId,
15862                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15863                        break;
15864                }
15865            }
15866        };
15867
15868        final MoveInfo move;
15869        if (moveCompleteApp) {
15870            // Kick off a thread to report progress estimates
15871            new Thread() {
15872                @Override
15873                public void run() {
15874                    while (true) {
15875                        try {
15876                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15877                                break;
15878                            }
15879                        } catch (InterruptedException ignored) {
15880                        }
15881
15882                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15883                        final int progress = 10 + (int) MathUtils.constrain(
15884                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15885                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15886                    }
15887                }
15888            }.start();
15889
15890            final String dataAppName = codeFile.getName();
15891            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15892                    dataAppName, appId, seinfo);
15893        } else {
15894            move = null;
15895        }
15896
15897        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15898
15899        final Message msg = mHandler.obtainMessage(INIT_COPY);
15900        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15901        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15902                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
15903        mHandler.sendMessage(msg);
15904    }
15905
15906    @Override
15907    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15908        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15909
15910        final int realMoveId = mNextMoveId.getAndIncrement();
15911        final Bundle extras = new Bundle();
15912        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15913        mMoveCallbacks.notifyCreated(realMoveId, extras);
15914
15915        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15916            @Override
15917            public void onCreated(int moveId, Bundle extras) {
15918                // Ignored
15919            }
15920
15921            @Override
15922            public void onStatusChanged(int moveId, int status, long estMillis) {
15923                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15924            }
15925        };
15926
15927        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15928        storage.setPrimaryStorageUuid(volumeUuid, callback);
15929        return realMoveId;
15930    }
15931
15932    @Override
15933    public int getMoveStatus(int moveId) {
15934        mContext.enforceCallingOrSelfPermission(
15935                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15936        return mMoveCallbacks.mLastStatus.get(moveId);
15937    }
15938
15939    @Override
15940    public void registerMoveCallback(IPackageMoveObserver callback) {
15941        mContext.enforceCallingOrSelfPermission(
15942                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15943        mMoveCallbacks.register(callback);
15944    }
15945
15946    @Override
15947    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15948        mContext.enforceCallingOrSelfPermission(
15949                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15950        mMoveCallbacks.unregister(callback);
15951    }
15952
15953    @Override
15954    public boolean setInstallLocation(int loc) {
15955        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15956                null);
15957        if (getInstallLocation() == loc) {
15958            return true;
15959        }
15960        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15961                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15962            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15963                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15964            return true;
15965        }
15966        return false;
15967   }
15968
15969    @Override
15970    public int getInstallLocation() {
15971        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15972                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15973                PackageHelper.APP_INSTALL_AUTO);
15974    }
15975
15976    /** Called by UserManagerService */
15977    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15978        mDirtyUsers.remove(userHandle);
15979        mSettings.removeUserLPw(userHandle);
15980        mPendingBroadcasts.remove(userHandle);
15981        if (mInstaller != null) {
15982            // Technically, we shouldn't be doing this with the package lock
15983            // held.  However, this is very rare, and there is already so much
15984            // other disk I/O going on, that we'll let it slide for now.
15985            final StorageManager storage = mContext.getSystemService(StorageManager.class);
15986            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
15987                final String volumeUuid = vol.getFsUuid();
15988                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15989                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15990            }
15991        }
15992        mUserNeedsBadging.delete(userHandle);
15993        removeUnusedPackagesLILPw(userManager, userHandle);
15994    }
15995
15996    /**
15997     * We're removing userHandle and would like to remove any downloaded packages
15998     * that are no longer in use by any other user.
15999     * @param userHandle the user being removed
16000     */
16001    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16002        final boolean DEBUG_CLEAN_APKS = false;
16003        int [] users = userManager.getUserIdsLPr();
16004        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16005        while (psit.hasNext()) {
16006            PackageSetting ps = psit.next();
16007            if (ps.pkg == null) {
16008                continue;
16009            }
16010            final String packageName = ps.pkg.packageName;
16011            // Skip over if system app
16012            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16013                continue;
16014            }
16015            if (DEBUG_CLEAN_APKS) {
16016                Slog.i(TAG, "Checking package " + packageName);
16017            }
16018            boolean keep = false;
16019            for (int i = 0; i < users.length; i++) {
16020                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16021                    keep = true;
16022                    if (DEBUG_CLEAN_APKS) {
16023                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16024                                + users[i]);
16025                    }
16026                    break;
16027                }
16028            }
16029            if (!keep) {
16030                if (DEBUG_CLEAN_APKS) {
16031                    Slog.i(TAG, "  Removing package " + packageName);
16032                }
16033                mHandler.post(new Runnable() {
16034                    public void run() {
16035                        deletePackageX(packageName, userHandle, 0);
16036                    } //end run
16037                });
16038            }
16039        }
16040    }
16041
16042    /** Called by UserManagerService */
16043    void createNewUserLILPw(int userHandle) {
16044        if (mInstaller != null) {
16045            mInstaller.createUserConfig(userHandle);
16046            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16047            applyFactoryDefaultBrowserLPw(userHandle);
16048            primeDomainVerificationsLPw(userHandle);
16049        }
16050    }
16051
16052    void newUserCreated(final int userHandle) {
16053        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16054    }
16055
16056    @Override
16057    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16058        mContext.enforceCallingOrSelfPermission(
16059                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16060                "Only package verification agents can read the verifier device identity");
16061
16062        synchronized (mPackages) {
16063            return mSettings.getVerifierDeviceIdentityLPw();
16064        }
16065    }
16066
16067    @Override
16068    public void setPermissionEnforced(String permission, boolean enforced) {
16069        // TODO: Now that we no longer change GID for storage, this should to away.
16070        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16071                "setPermissionEnforced");
16072        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16073            synchronized (mPackages) {
16074                if (mSettings.mReadExternalStorageEnforced == null
16075                        || mSettings.mReadExternalStorageEnforced != enforced) {
16076                    mSettings.mReadExternalStorageEnforced = enforced;
16077                    mSettings.writeLPr();
16078                }
16079            }
16080            // kill any non-foreground processes so we restart them and
16081            // grant/revoke the GID.
16082            final IActivityManager am = ActivityManagerNative.getDefault();
16083            if (am != null) {
16084                final long token = Binder.clearCallingIdentity();
16085                try {
16086                    am.killProcessesBelowForeground("setPermissionEnforcement");
16087                } catch (RemoteException e) {
16088                } finally {
16089                    Binder.restoreCallingIdentity(token);
16090                }
16091            }
16092        } else {
16093            throw new IllegalArgumentException("No selective enforcement for " + permission);
16094        }
16095    }
16096
16097    @Override
16098    @Deprecated
16099    public boolean isPermissionEnforced(String permission) {
16100        return true;
16101    }
16102
16103    @Override
16104    public boolean isStorageLow() {
16105        final long token = Binder.clearCallingIdentity();
16106        try {
16107            final DeviceStorageMonitorInternal
16108                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16109            if (dsm != null) {
16110                return dsm.isMemoryLow();
16111            } else {
16112                return false;
16113            }
16114        } finally {
16115            Binder.restoreCallingIdentity(token);
16116        }
16117    }
16118
16119    @Override
16120    public IPackageInstaller getPackageInstaller() {
16121        return mInstallerService;
16122    }
16123
16124    private boolean userNeedsBadging(int userId) {
16125        int index = mUserNeedsBadging.indexOfKey(userId);
16126        if (index < 0) {
16127            final UserInfo userInfo;
16128            final long token = Binder.clearCallingIdentity();
16129            try {
16130                userInfo = sUserManager.getUserInfo(userId);
16131            } finally {
16132                Binder.restoreCallingIdentity(token);
16133            }
16134            final boolean b;
16135            if (userInfo != null && userInfo.isManagedProfile()) {
16136                b = true;
16137            } else {
16138                b = false;
16139            }
16140            mUserNeedsBadging.put(userId, b);
16141            return b;
16142        }
16143        return mUserNeedsBadging.valueAt(index);
16144    }
16145
16146    @Override
16147    public KeySet getKeySetByAlias(String packageName, String alias) {
16148        if (packageName == null || alias == null) {
16149            return null;
16150        }
16151        synchronized(mPackages) {
16152            final PackageParser.Package pkg = mPackages.get(packageName);
16153            if (pkg == null) {
16154                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16155                throw new IllegalArgumentException("Unknown package: " + packageName);
16156            }
16157            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16158            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16159        }
16160    }
16161
16162    @Override
16163    public KeySet getSigningKeySet(String packageName) {
16164        if (packageName == null) {
16165            return null;
16166        }
16167        synchronized(mPackages) {
16168            final PackageParser.Package pkg = mPackages.get(packageName);
16169            if (pkg == null) {
16170                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16171                throw new IllegalArgumentException("Unknown package: " + packageName);
16172            }
16173            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16174                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16175                throw new SecurityException("May not access signing KeySet of other apps.");
16176            }
16177            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16178            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16179        }
16180    }
16181
16182    @Override
16183    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16184        if (packageName == null || ks == null) {
16185            return false;
16186        }
16187        synchronized(mPackages) {
16188            final PackageParser.Package pkg = mPackages.get(packageName);
16189            if (pkg == null) {
16190                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16191                throw new IllegalArgumentException("Unknown package: " + packageName);
16192            }
16193            IBinder ksh = ks.getToken();
16194            if (ksh instanceof KeySetHandle) {
16195                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16196                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16197            }
16198            return false;
16199        }
16200    }
16201
16202    @Override
16203    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16204        if (packageName == null || ks == null) {
16205            return false;
16206        }
16207        synchronized(mPackages) {
16208            final PackageParser.Package pkg = mPackages.get(packageName);
16209            if (pkg == null) {
16210                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16211                throw new IllegalArgumentException("Unknown package: " + packageName);
16212            }
16213            IBinder ksh = ks.getToken();
16214            if (ksh instanceof KeySetHandle) {
16215                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16216                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16217            }
16218            return false;
16219        }
16220    }
16221
16222    public void getUsageStatsIfNoPackageUsageInfo() {
16223        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16224            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16225            if (usm == null) {
16226                throw new IllegalStateException("UsageStatsManager must be initialized");
16227            }
16228            long now = System.currentTimeMillis();
16229            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16230            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16231                String packageName = entry.getKey();
16232                PackageParser.Package pkg = mPackages.get(packageName);
16233                if (pkg == null) {
16234                    continue;
16235                }
16236                UsageStats usage = entry.getValue();
16237                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16238                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16239            }
16240        }
16241    }
16242
16243    /**
16244     * Check and throw if the given before/after packages would be considered a
16245     * downgrade.
16246     */
16247    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16248            throws PackageManagerException {
16249        if (after.versionCode < before.mVersionCode) {
16250            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16251                    "Update version code " + after.versionCode + " is older than current "
16252                    + before.mVersionCode);
16253        } else if (after.versionCode == before.mVersionCode) {
16254            if (after.baseRevisionCode < before.baseRevisionCode) {
16255                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16256                        "Update base revision code " + after.baseRevisionCode
16257                        + " is older than current " + before.baseRevisionCode);
16258            }
16259
16260            if (!ArrayUtils.isEmpty(after.splitNames)) {
16261                for (int i = 0; i < after.splitNames.length; i++) {
16262                    final String splitName = after.splitNames[i];
16263                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16264                    if (j != -1) {
16265                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16266                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16267                                    "Update split " + splitName + " revision code "
16268                                    + after.splitRevisionCodes[i] + " is older than current "
16269                                    + before.splitRevisionCodes[j]);
16270                        }
16271                    }
16272                }
16273            }
16274        }
16275    }
16276
16277    private static class MoveCallbacks extends Handler {
16278        private static final int MSG_CREATED = 1;
16279        private static final int MSG_STATUS_CHANGED = 2;
16280
16281        private final RemoteCallbackList<IPackageMoveObserver>
16282                mCallbacks = new RemoteCallbackList<>();
16283
16284        private final SparseIntArray mLastStatus = new SparseIntArray();
16285
16286        public MoveCallbacks(Looper looper) {
16287            super(looper);
16288        }
16289
16290        public void register(IPackageMoveObserver callback) {
16291            mCallbacks.register(callback);
16292        }
16293
16294        public void unregister(IPackageMoveObserver callback) {
16295            mCallbacks.unregister(callback);
16296        }
16297
16298        @Override
16299        public void handleMessage(Message msg) {
16300            final SomeArgs args = (SomeArgs) msg.obj;
16301            final int n = mCallbacks.beginBroadcast();
16302            for (int i = 0; i < n; i++) {
16303                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16304                try {
16305                    invokeCallback(callback, msg.what, args);
16306                } catch (RemoteException ignored) {
16307                }
16308            }
16309            mCallbacks.finishBroadcast();
16310            args.recycle();
16311        }
16312
16313        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16314                throws RemoteException {
16315            switch (what) {
16316                case MSG_CREATED: {
16317                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16318                    break;
16319                }
16320                case MSG_STATUS_CHANGED: {
16321                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16322                    break;
16323                }
16324            }
16325        }
16326
16327        private void notifyCreated(int moveId, Bundle extras) {
16328            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16329
16330            final SomeArgs args = SomeArgs.obtain();
16331            args.argi1 = moveId;
16332            args.arg2 = extras;
16333            obtainMessage(MSG_CREATED, args).sendToTarget();
16334        }
16335
16336        private void notifyStatusChanged(int moveId, int status) {
16337            notifyStatusChanged(moveId, status, -1);
16338        }
16339
16340        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16341            Slog.v(TAG, "Move " + moveId + " status " + status);
16342
16343            final SomeArgs args = SomeArgs.obtain();
16344            args.argi1 = moveId;
16345            args.argi2 = status;
16346            args.arg3 = estMillis;
16347            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16348
16349            synchronized (mLastStatus) {
16350                mLastStatus.put(moveId, status);
16351            }
16352        }
16353    }
16354
16355    private final class OnPermissionChangeListeners extends Handler {
16356        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16357
16358        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16359                new RemoteCallbackList<>();
16360
16361        public OnPermissionChangeListeners(Looper looper) {
16362            super(looper);
16363        }
16364
16365        @Override
16366        public void handleMessage(Message msg) {
16367            switch (msg.what) {
16368                case MSG_ON_PERMISSIONS_CHANGED: {
16369                    final int uid = msg.arg1;
16370                    handleOnPermissionsChanged(uid);
16371                } break;
16372            }
16373        }
16374
16375        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16376            mPermissionListeners.register(listener);
16377
16378        }
16379
16380        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16381            mPermissionListeners.unregister(listener);
16382        }
16383
16384        public void onPermissionsChanged(int uid) {
16385            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16386                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16387            }
16388        }
16389
16390        private void handleOnPermissionsChanged(int uid) {
16391            final int count = mPermissionListeners.beginBroadcast();
16392            try {
16393                for (int i = 0; i < count; i++) {
16394                    IOnPermissionsChangeListener callback = mPermissionListeners
16395                            .getBroadcastItem(i);
16396                    try {
16397                        callback.onPermissionsChanged(uid);
16398                    } catch (RemoteException e) {
16399                        Log.e(TAG, "Permission listener is dead", e);
16400                    }
16401                }
16402            } finally {
16403                mPermissionListeners.finishBroadcast();
16404            }
16405        }
16406    }
16407
16408    private class PackageManagerInternalImpl extends PackageManagerInternal {
16409        @Override
16410        public void setLocationPackagesProvider(PackagesProvider provider) {
16411            synchronized (mPackages) {
16412                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16413            }
16414        }
16415
16416        @Override
16417        public void setImePackagesProvider(PackagesProvider provider) {
16418            synchronized (mPackages) {
16419                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16420            }
16421        }
16422
16423        @Override
16424        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16425            synchronized (mPackages) {
16426                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16427            }
16428        }
16429
16430        @Override
16431        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16432            synchronized (mPackages) {
16433                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16434            }
16435        }
16436
16437        @Override
16438        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16439            synchronized (mPackages) {
16440                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16441            }
16442        }
16443
16444        @Override
16445        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16446            synchronized (mPackages) {
16447                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16448            }
16449        }
16450
16451        @Override
16452        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16453            synchronized (mPackages) {
16454                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16455                        packageName, userId);
16456            }
16457        }
16458
16459        @Override
16460        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16461            synchronized (mPackages) {
16462                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16463                        packageName, userId);
16464            }
16465        }
16466    }
16467
16468    @Override
16469    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16470        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16471        synchronized (mPackages) {
16472            final long identity = Binder.clearCallingIdentity();
16473            try {
16474                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16475                        packageNames, userId);
16476            } finally {
16477                Binder.restoreCallingIdentity(identity);
16478            }
16479        }
16480    }
16481
16482    private static void enforceSystemOrPhoneCaller(String tag) {
16483        int callingUid = Binder.getCallingUid();
16484        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16485            throw new SecurityException(
16486                    "Cannot call " + tag + " from UID " + callingUid);
16487        }
16488    }
16489}
16490