PackageManagerService.java revision 56ebb257085ffed21c98ba98ced959ffe6afaca3
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.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
60import static android.content.pm.PackageManager.MATCH_ALL;
61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
65import static android.content.pm.PackageManager.PERMISSION_DENIED;
66import static android.content.pm.PackageManager.PERMISSION_GRANTED;
67import static android.content.pm.PackageParser.isApkFile;
68import static android.os.Process.PACKAGE_INFO_GID;
69import static android.os.Process.SYSTEM_UID;
70import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
71import static android.system.OsConstants.O_CREAT;
72import static android.system.OsConstants.O_RDWR;
73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
74import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
75import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
76import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
77import static com.android.internal.util.ArrayUtils.appendInt;
78import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
79import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
80import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
81import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
82import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
83import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
87
88import android.Manifest;
89import android.app.ActivityManager;
90import android.app.ActivityManagerNative;
91import android.app.AppGlobals;
92import android.app.IActivityManager;
93import android.app.admin.IDevicePolicyManager;
94import android.app.backup.IBackupManager;
95import android.app.usage.UsageStats;
96import android.app.usage.UsageStatsManager;
97import android.content.BroadcastReceiver;
98import android.content.ComponentName;
99import android.content.Context;
100import android.content.IIntentReceiver;
101import android.content.Intent;
102import android.content.IntentFilter;
103import android.content.IntentSender;
104import android.content.IntentSender.SendIntentException;
105import android.content.ServiceConnection;
106import android.content.pm.ActivityInfo;
107import android.content.pm.ApplicationInfo;
108import android.content.pm.FeatureInfo;
109import android.content.pm.IOnPermissionsChangeListener;
110import android.content.pm.IPackageDataObserver;
111import android.content.pm.IPackageDeleteObserver;
112import android.content.pm.IPackageDeleteObserver2;
113import android.content.pm.IPackageInstallObserver2;
114import android.content.pm.IPackageInstaller;
115import android.content.pm.IPackageManager;
116import android.content.pm.IPackageMoveObserver;
117import android.content.pm.IPackageStatsObserver;
118import android.content.pm.InstrumentationInfo;
119import android.content.pm.IntentFilterVerificationInfo;
120import android.content.pm.KeySet;
121import android.content.pm.ManifestDigest;
122import android.content.pm.PackageCleanItem;
123import android.content.pm.PackageInfo;
124import android.content.pm.PackageInfoLite;
125import android.content.pm.PackageInstaller;
126import android.content.pm.PackageManager;
127import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
128import android.content.pm.PackageManagerInternal;
129import android.content.pm.PackageParser;
130import android.content.pm.PackageParser.ActivityIntentInfo;
131import android.content.pm.PackageParser.PackageLite;
132import android.content.pm.PackageParser.PackageParserException;
133import android.content.pm.PackageStats;
134import android.content.pm.PackageUserState;
135import android.content.pm.ParceledListSlice;
136import android.content.pm.PermissionGroupInfo;
137import android.content.pm.PermissionInfo;
138import android.content.pm.ProviderInfo;
139import android.content.pm.ResolveInfo;
140import android.content.pm.ServiceInfo;
141import android.content.pm.Signature;
142import android.content.pm.UserInfo;
143import android.content.pm.VerificationParams;
144import android.content.pm.VerifierDeviceIdentity;
145import android.content.pm.VerifierInfo;
146import android.content.res.Resources;
147import android.hardware.display.DisplayManager;
148import android.net.Uri;
149import android.os.Debug;
150import android.os.Binder;
151import android.os.Build;
152import android.os.Bundle;
153import android.os.Environment;
154import android.os.Environment.UserEnvironment;
155import android.os.FileUtils;
156import android.os.Handler;
157import android.os.IBinder;
158import android.os.Looper;
159import android.os.Message;
160import android.os.Parcel;
161import android.os.ParcelFileDescriptor;
162import android.os.Process;
163import android.os.RemoteCallbackList;
164import android.os.RemoteException;
165import android.os.SELinux;
166import android.os.ServiceManager;
167import android.os.SystemClock;
168import android.os.SystemProperties;
169import android.os.Trace;
170import android.os.UserHandle;
171import android.os.UserManager;
172import android.os.storage.IMountService;
173import android.os.storage.MountServiceInternal;
174import android.os.storage.StorageEventListener;
175import android.os.storage.StorageManager;
176import android.os.storage.VolumeInfo;
177import android.os.storage.VolumeRecord;
178import android.security.KeyStore;
179import android.security.SystemKeyStore;
180import android.system.ErrnoException;
181import android.system.Os;
182import android.system.StructStat;
183import android.text.TextUtils;
184import android.text.format.DateUtils;
185import android.util.ArrayMap;
186import android.util.ArraySet;
187import android.util.AtomicFile;
188import android.util.DisplayMetrics;
189import android.util.EventLog;
190import android.util.ExceptionUtils;
191import android.util.Log;
192import android.util.LogPrinter;
193import android.util.MathUtils;
194import android.util.PrintStreamPrinter;
195import android.util.Slog;
196import android.util.SparseArray;
197import android.util.SparseBooleanArray;
198import android.util.SparseIntArray;
199import android.util.Xml;
200import android.view.Display;
201
202import dalvik.system.DexFile;
203import dalvik.system.VMRuntime;
204
205import libcore.io.IoUtils;
206import libcore.util.EmptyArray;
207
208import com.android.internal.R;
209import com.android.internal.annotations.GuardedBy;
210import com.android.internal.app.IMediaContainerService;
211import com.android.internal.app.ResolverActivity;
212import com.android.internal.content.NativeLibraryHelper;
213import com.android.internal.content.PackageHelper;
214import com.android.internal.os.IParcelFileDescriptorFactory;
215import com.android.internal.os.SomeArgs;
216import com.android.internal.os.Zygote;
217import com.android.internal.util.ArrayUtils;
218import com.android.internal.util.FastPrintWriter;
219import com.android.internal.util.FastXmlSerializer;
220import com.android.internal.util.IndentingPrintWriter;
221import com.android.internal.util.Preconditions;
222import com.android.server.EventLogTags;
223import com.android.server.FgThread;
224import com.android.server.IntentResolver;
225import com.android.server.LocalServices;
226import com.android.server.ServiceThread;
227import com.android.server.SystemConfig;
228import com.android.server.Watchdog;
229import com.android.server.pm.PermissionsState.PermissionState;
230import com.android.server.pm.Settings.DatabaseVersion;
231import com.android.server.pm.Settings.VersionInfo;
232import com.android.server.storage.DeviceStorageMonitorInternal;
233
234import org.xmlpull.v1.XmlPullParser;
235import org.xmlpull.v1.XmlPullParserException;
236import org.xmlpull.v1.XmlSerializer;
237
238import java.io.BufferedInputStream;
239import java.io.BufferedOutputStream;
240import java.io.BufferedReader;
241import java.io.ByteArrayInputStream;
242import java.io.ByteArrayOutputStream;
243import java.io.File;
244import java.io.FileDescriptor;
245import java.io.FileNotFoundException;
246import java.io.FileOutputStream;
247import java.io.FileReader;
248import java.io.FilenameFilter;
249import java.io.IOException;
250import java.io.InputStream;
251import java.io.PrintWriter;
252import java.nio.charset.StandardCharsets;
253import java.security.NoSuchAlgorithmException;
254import java.security.PublicKey;
255import java.security.cert.CertificateEncodingException;
256import java.security.cert.CertificateException;
257import java.text.SimpleDateFormat;
258import java.util.ArrayList;
259import java.util.Arrays;
260import java.util.Collection;
261import java.util.Collections;
262import java.util.Comparator;
263import java.util.Date;
264import java.util.Iterator;
265import java.util.List;
266import java.util.Map;
267import java.util.Objects;
268import java.util.Set;
269import java.util.concurrent.CountDownLatch;
270import java.util.concurrent.TimeUnit;
271import java.util.concurrent.atomic.AtomicBoolean;
272import java.util.concurrent.atomic.AtomicInteger;
273import java.util.concurrent.atomic.AtomicLong;
274
275/**
276 * Keep track of all those .apks everywhere.
277 *
278 * This is very central to the platform's security; please run the unit
279 * tests whenever making modifications here:
280 *
281runtest -c android.content.pm.PackageManagerTests frameworks-core
282 *
283 * {@hide}
284 */
285public class PackageManagerService extends IPackageManager.Stub {
286    static final String TAG = "PackageManager";
287    static final boolean DEBUG_SETTINGS = false;
288    static final boolean DEBUG_PREFERRED = false;
289    static final boolean DEBUG_UPGRADE = false;
290    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
291    private static final boolean DEBUG_BACKUP = false;
292    private static final boolean DEBUG_INSTALL = false;
293    private static final boolean DEBUG_REMOVE = false;
294    private static final boolean DEBUG_BROADCASTS = false;
295    private static final boolean DEBUG_SHOW_INFO = false;
296    private static final boolean DEBUG_PACKAGE_INFO = false;
297    private static final boolean DEBUG_INTENT_MATCHING = false;
298    private static final boolean DEBUG_PACKAGE_SCANNING = false;
299    private static final boolean DEBUG_VERIFY = false;
300    private static final boolean DEBUG_DEXOPT = false;
301    private static final boolean DEBUG_ABI_SELECTION = false;
302
303    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
304
305    private static final int RADIO_UID = Process.PHONE_UID;
306    private static final int LOG_UID = Process.LOG_UID;
307    private static final int NFC_UID = Process.NFC_UID;
308    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
309    private static final int SHELL_UID = Process.SHELL_UID;
310
311    // Cap the size of permission trees that 3rd party apps can define
312    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
313
314    // Suffix used during package installation when copying/moving
315    // package apks to install directory.
316    private static final String INSTALL_PACKAGE_SUFFIX = "-";
317
318    static final int SCAN_NO_DEX = 1<<1;
319    static final int SCAN_FORCE_DEX = 1<<2;
320    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
321    static final int SCAN_NEW_INSTALL = 1<<4;
322    static final int SCAN_NO_PATHS = 1<<5;
323    static final int SCAN_UPDATE_TIME = 1<<6;
324    static final int SCAN_DEFER_DEX = 1<<7;
325    static final int SCAN_BOOTING = 1<<8;
326    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
327    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
328    static final int SCAN_REPLACING = 1<<11;
329    static final int SCAN_REQUIRE_KNOWN = 1<<12;
330    static final int SCAN_MOVE = 1<<13;
331    static final int SCAN_INITIAL = 1<<14;
332
333    static final int REMOVE_CHATTY = 1<<16;
334
335    private static final int[] EMPTY_INT_ARRAY = new int[0];
336
337    /**
338     * Timeout (in milliseconds) after which the watchdog should declare that
339     * our handler thread is wedged.  The usual default for such things is one
340     * minute but we sometimes do very lengthy I/O operations on this thread,
341     * such as installing multi-gigabyte applications, so ours needs to be longer.
342     */
343    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
344
345    /**
346     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
347     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
348     * settings entry if available, otherwise we use the hardcoded default.  If it's been
349     * more than this long since the last fstrim, we force one during the boot sequence.
350     *
351     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
352     * one gets run at the next available charging+idle time.  This final mandatory
353     * no-fstrim check kicks in only of the other scheduling criteria is never met.
354     */
355    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
356
357    /**
358     * Whether verification is enabled by default.
359     */
360    private static final boolean DEFAULT_VERIFY_ENABLE = true;
361
362    /**
363     * The default maximum time to wait for the verification agent to return in
364     * milliseconds.
365     */
366    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
367
368    /**
369     * The default response for package verification timeout.
370     *
371     * This can be either PackageManager.VERIFICATION_ALLOW or
372     * PackageManager.VERIFICATION_REJECT.
373     */
374    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
375
376    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
377
378    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
379            DEFAULT_CONTAINER_PACKAGE,
380            "com.android.defcontainer.DefaultContainerService");
381
382    private static final String KILL_APP_REASON_GIDS_CHANGED =
383            "permission grant or revoke changed gids";
384
385    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
386            "permissions revoked";
387
388    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
389
390    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
391
392    /** Permission grant: not grant the permission. */
393    private static final int GRANT_DENIED = 1;
394
395    /** Permission grant: grant the permission as an install permission. */
396    private static final int GRANT_INSTALL = 2;
397
398    /** Permission grant: grant the permission as an install permission for a legacy app. */
399    private static final int GRANT_INSTALL_LEGACY = 3;
400
401    /** Permission grant: grant the permission as a runtime one. */
402    private static final int GRANT_RUNTIME = 4;
403
404    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
405    private static final int GRANT_UPGRADE = 5;
406
407    /** Canonical intent used to identify what counts as a "web browser" app */
408    private static final Intent sBrowserIntent;
409    static {
410        sBrowserIntent = new Intent();
411        sBrowserIntent.setAction(Intent.ACTION_VIEW);
412        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
413        sBrowserIntent.setData(Uri.parse("http:"));
414    }
415
416    final ServiceThread mHandlerThread;
417
418    final PackageHandler mHandler;
419
420    /**
421     * Messages for {@link #mHandler} that need to wait for system ready before
422     * being dispatched.
423     */
424    private ArrayList<Message> mPostSystemReadyMessages;
425
426    final int mSdkVersion = Build.VERSION.SDK_INT;
427
428    final Context mContext;
429    final boolean mFactoryTest;
430    final boolean mOnlyCore;
431    final boolean mLazyDexOpt;
432    final long mDexOptLRUThresholdInMills;
433    final DisplayMetrics mMetrics;
434    final int mDefParseFlags;
435    final String[] mSeparateProcesses;
436    final boolean mIsUpgrade;
437
438    // This is where all application persistent data goes.
439    final File mAppDataDir;
440
441    // This is where all application persistent data goes for secondary users.
442    final File mUserAppDataDir;
443
444    /** The location for ASEC container files on internal storage. */
445    final String mAsecInternalPath;
446
447    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
448    // LOCK HELD.  Can be called with mInstallLock held.
449    @GuardedBy("mInstallLock")
450    final Installer mInstaller;
451
452    /** Directory where installed third-party apps stored */
453    final File mAppInstallDir;
454
455    /**
456     * Directory to which applications installed internally have their
457     * 32 bit native libraries copied.
458     */
459    private File mAppLib32InstallDir;
460
461    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
462    // apps.
463    final File mDrmAppPrivateInstallDir;
464
465    // ----------------------------------------------------------------
466
467    // Lock for state used when installing and doing other long running
468    // operations.  Methods that must be called with this lock held have
469    // the suffix "LI".
470    final Object mInstallLock = new Object();
471
472    // ----------------------------------------------------------------
473
474    // Keys are String (package name), values are Package.  This also serves
475    // as the lock for the global state.  Methods that must be called with
476    // this lock held have the prefix "LP".
477    @GuardedBy("mPackages")
478    final ArrayMap<String, PackageParser.Package> mPackages =
479            new ArrayMap<String, PackageParser.Package>();
480
481    // Tracks available target package names -> overlay package paths.
482    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
483        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
484
485    /**
486     * Tracks new system packages [received in an OTA] that we expect to
487     * find updated user-installed versions. Keys are package name, values
488     * are package location.
489     */
490    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
491
492    /**
493     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
494     */
495    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
496    /**
497     * Whether or not system app permissions should be promoted from install to runtime.
498     */
499    boolean mPromoteSystemApps;
500
501    final Settings mSettings;
502    boolean mRestoredSettings;
503
504    // System configuration read by SystemConfig.
505    final int[] mGlobalGids;
506    final SparseArray<ArraySet<String>> mSystemPermissions;
507    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
508
509    // If mac_permissions.xml was found for seinfo labeling.
510    boolean mFoundPolicyFile;
511
512    // If a recursive restorecon of /data/data/<pkg> is needed.
513    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
514
515    public static final class SharedLibraryEntry {
516        public final String path;
517        public final String apk;
518
519        SharedLibraryEntry(String _path, String _apk) {
520            path = _path;
521            apk = _apk;
522        }
523    }
524
525    // Currently known shared libraries.
526    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
527            new ArrayMap<String, SharedLibraryEntry>();
528
529    // All available activities, for your resolving pleasure.
530    final ActivityIntentResolver mActivities =
531            new ActivityIntentResolver();
532
533    // All available receivers, for your resolving pleasure.
534    final ActivityIntentResolver mReceivers =
535            new ActivityIntentResolver();
536
537    // All available services, for your resolving pleasure.
538    final ServiceIntentResolver mServices = new ServiceIntentResolver();
539
540    // All available providers, for your resolving pleasure.
541    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
542
543    // Mapping from provider base names (first directory in content URI codePath)
544    // to the provider information.
545    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
546            new ArrayMap<String, PackageParser.Provider>();
547
548    // Mapping from instrumentation class names to info about them.
549    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
550            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
551
552    // Mapping from permission names to info about them.
553    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
554            new ArrayMap<String, PackageParser.PermissionGroup>();
555
556    // Packages whose data we have transfered into another package, thus
557    // should no longer exist.
558    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
559
560    // Broadcast actions that are only available to the system.
561    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
562
563    /** List of packages waiting for verification. */
564    final SparseArray<PackageVerificationState> mPendingVerification
565            = new SparseArray<PackageVerificationState>();
566
567    /** Set of packages associated with each app op permission. */
568    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
569
570    final PackageInstallerService mInstallerService;
571
572    private final PackageDexOptimizer mPackageDexOptimizer;
573
574    private AtomicInteger mNextMoveId = new AtomicInteger();
575    private final MoveCallbacks mMoveCallbacks;
576
577    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
578
579    // Cache of users who need badging.
580    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
581
582    /** Token for keys in mPendingVerification. */
583    private int mPendingVerificationToken = 0;
584
585    volatile boolean mSystemReady;
586    volatile boolean mSafeMode;
587    volatile boolean mHasSystemUidErrors;
588
589    ApplicationInfo mAndroidApplication;
590    final ActivityInfo mResolveActivity = new ActivityInfo();
591    final ResolveInfo mResolveInfo = new ResolveInfo();
592    ComponentName mResolveComponentName;
593    PackageParser.Package mPlatformPackage;
594    ComponentName mCustomResolverComponentName;
595
596    boolean mResolverReplaced = false;
597
598    private final ComponentName mIntentFilterVerifierComponent;
599    private int mIntentFilterVerificationToken = 0;
600
601    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
602            = new SparseArray<IntentFilterVerificationState>();
603
604    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
605            new DefaultPermissionGrantPolicy(this);
606
607    private static class IFVerificationParams {
608        PackageParser.Package pkg;
609        boolean replacing;
610        int userId;
611        int verifierUid;
612
613        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
614                int _userId, int _verifierUid) {
615            pkg = _pkg;
616            replacing = _replacing;
617            userId = _userId;
618            replacing = _replacing;
619            verifierUid = _verifierUid;
620        }
621    }
622
623    private interface IntentFilterVerifier<T extends IntentFilter> {
624        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
625                                               T filter, String packageName);
626        void startVerifications(int userId);
627        void receiveVerificationResponse(int verificationId);
628    }
629
630    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
631        private Context mContext;
632        private ComponentName mIntentFilterVerifierComponent;
633        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
634
635        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
636            mContext = context;
637            mIntentFilterVerifierComponent = verifierComponent;
638        }
639
640        private String getDefaultScheme() {
641            return IntentFilter.SCHEME_HTTPS;
642        }
643
644        @Override
645        public void startVerifications(int userId) {
646            // Launch verifications requests
647            int count = mCurrentIntentFilterVerifications.size();
648            for (int n=0; n<count; n++) {
649                int verificationId = mCurrentIntentFilterVerifications.get(n);
650                final IntentFilterVerificationState ivs =
651                        mIntentFilterVerificationStates.get(verificationId);
652
653                String packageName = ivs.getPackageName();
654
655                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
656                final int filterCount = filters.size();
657                ArraySet<String> domainsSet = new ArraySet<>();
658                for (int m=0; m<filterCount; m++) {
659                    PackageParser.ActivityIntentInfo filter = filters.get(m);
660                    domainsSet.addAll(filter.getHostsList());
661                }
662                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
663                synchronized (mPackages) {
664                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
665                            packageName, domainsList) != null) {
666                        scheduleWriteSettingsLocked();
667                    }
668                }
669                sendVerificationRequest(userId, verificationId, ivs);
670            }
671            mCurrentIntentFilterVerifications.clear();
672        }
673
674        private void sendVerificationRequest(int userId, int verificationId,
675                IntentFilterVerificationState ivs) {
676
677            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
678            verificationIntent.putExtra(
679                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
680                    verificationId);
681            verificationIntent.putExtra(
682                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
683                    getDefaultScheme());
684            verificationIntent.putExtra(
685                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
686                    ivs.getHostsString());
687            verificationIntent.putExtra(
688                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
689                    ivs.getPackageName());
690            verificationIntent.setComponent(mIntentFilterVerifierComponent);
691            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
692
693            UserHandle user = new UserHandle(userId);
694            mContext.sendBroadcastAsUser(verificationIntent, user);
695            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
696                    "Sending IntentFilter verification broadcast");
697        }
698
699        public void receiveVerificationResponse(int verificationId) {
700            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
701
702            final boolean verified = ivs.isVerified();
703
704            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
705            final int count = filters.size();
706            if (DEBUG_DOMAIN_VERIFICATION) {
707                Slog.i(TAG, "Received verification response " + verificationId
708                        + " for " + count + " filters, verified=" + verified);
709            }
710            for (int n=0; n<count; n++) {
711                PackageParser.ActivityIntentInfo filter = filters.get(n);
712                filter.setVerified(verified);
713
714                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
715                        + " verified with result:" + verified + " and hosts:"
716                        + ivs.getHostsString());
717            }
718
719            mIntentFilterVerificationStates.remove(verificationId);
720
721            final String packageName = ivs.getPackageName();
722            IntentFilterVerificationInfo ivi = null;
723
724            synchronized (mPackages) {
725                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
726            }
727            if (ivi == null) {
728                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
729                        + verificationId + " packageName:" + packageName);
730                return;
731            }
732            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
733                    "Updating IntentFilterVerificationInfo for package " + packageName
734                            +" verificationId:" + verificationId);
735
736            synchronized (mPackages) {
737                if (verified) {
738                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
739                } else {
740                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
741                }
742                scheduleWriteSettingsLocked();
743
744                final int userId = ivs.getUserId();
745                if (userId != UserHandle.USER_ALL) {
746                    final int userStatus =
747                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
748
749                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
750                    boolean needUpdate = false;
751
752                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
753                    // already been set by the User thru the Disambiguation dialog
754                    switch (userStatus) {
755                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
756                            if (verified) {
757                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
758                            } else {
759                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
760                            }
761                            needUpdate = true;
762                            break;
763
764                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
765                            if (verified) {
766                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
767                                needUpdate = true;
768                            }
769                            break;
770
771                        default:
772                            // Nothing to do
773                    }
774
775                    if (needUpdate) {
776                        mSettings.updateIntentFilterVerificationStatusLPw(
777                                packageName, updatedStatus, userId);
778                        scheduleWritePackageRestrictionsLocked(userId);
779                    }
780                }
781            }
782        }
783
784        @Override
785        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
786                    ActivityIntentInfo filter, String packageName) {
787            if (!hasValidDomains(filter)) {
788                return false;
789            }
790            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
791            if (ivs == null) {
792                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
793                        packageName);
794            }
795            if (DEBUG_DOMAIN_VERIFICATION) {
796                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
797            }
798            ivs.addFilter(filter);
799            return true;
800        }
801
802        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
803                int userId, int verificationId, String packageName) {
804            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
805                    verifierUid, userId, packageName);
806            ivs.setPendingState();
807            synchronized (mPackages) {
808                mIntentFilterVerificationStates.append(verificationId, ivs);
809                mCurrentIntentFilterVerifications.add(verificationId);
810            }
811            return ivs;
812        }
813    }
814
815    private static boolean hasValidDomains(ActivityIntentInfo filter) {
816        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
817                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
818                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
819    }
820
821    private IntentFilterVerifier mIntentFilterVerifier;
822
823    // Set of pending broadcasts for aggregating enable/disable of components.
824    static class PendingPackageBroadcasts {
825        // for each user id, a map of <package name -> components within that package>
826        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
827
828        public PendingPackageBroadcasts() {
829            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
830        }
831
832        public ArrayList<String> get(int userId, String packageName) {
833            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
834            return packages.get(packageName);
835        }
836
837        public void put(int userId, String packageName, ArrayList<String> components) {
838            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
839            packages.put(packageName, components);
840        }
841
842        public void remove(int userId, String packageName) {
843            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
844            if (packages != null) {
845                packages.remove(packageName);
846            }
847        }
848
849        public void remove(int userId) {
850            mUidMap.remove(userId);
851        }
852
853        public int userIdCount() {
854            return mUidMap.size();
855        }
856
857        public int userIdAt(int n) {
858            return mUidMap.keyAt(n);
859        }
860
861        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
862            return mUidMap.get(userId);
863        }
864
865        public int size() {
866            // total number of pending broadcast entries across all userIds
867            int num = 0;
868            for (int i = 0; i< mUidMap.size(); i++) {
869                num += mUidMap.valueAt(i).size();
870            }
871            return num;
872        }
873
874        public void clear() {
875            mUidMap.clear();
876        }
877
878        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
879            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
880            if (map == null) {
881                map = new ArrayMap<String, ArrayList<String>>();
882                mUidMap.put(userId, map);
883            }
884            return map;
885        }
886    }
887    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
888
889    // Service Connection to remote media container service to copy
890    // package uri's from external media onto secure containers
891    // or internal storage.
892    private IMediaContainerService mContainerService = null;
893
894    static final int SEND_PENDING_BROADCAST = 1;
895    static final int MCS_BOUND = 3;
896    static final int END_COPY = 4;
897    static final int INIT_COPY = 5;
898    static final int MCS_UNBIND = 6;
899    static final int START_CLEANING_PACKAGE = 7;
900    static final int FIND_INSTALL_LOC = 8;
901    static final int POST_INSTALL = 9;
902    static final int MCS_RECONNECT = 10;
903    static final int MCS_GIVE_UP = 11;
904    static final int UPDATED_MEDIA_STATUS = 12;
905    static final int WRITE_SETTINGS = 13;
906    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
907    static final int PACKAGE_VERIFIED = 15;
908    static final int CHECK_PENDING_VERIFICATION = 16;
909    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
910    static final int INTENT_FILTER_VERIFIED = 18;
911
912    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
913
914    // Delay time in millisecs
915    static final int BROADCAST_DELAY = 10 * 1000;
916
917    static UserManagerService sUserManager;
918
919    // Stores a list of users whose package restrictions file needs to be updated
920    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
921
922    final private DefaultContainerConnection mDefContainerConn =
923            new DefaultContainerConnection();
924    class DefaultContainerConnection implements ServiceConnection {
925        public void onServiceConnected(ComponentName name, IBinder service) {
926            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
927            IMediaContainerService imcs =
928                IMediaContainerService.Stub.asInterface(service);
929            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
930        }
931
932        public void onServiceDisconnected(ComponentName name) {
933            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
934        }
935    }
936
937    // Recordkeeping of restore-after-install operations that are currently in flight
938    // between the Package Manager and the Backup Manager
939    class PostInstallData {
940        public InstallArgs args;
941        public PackageInstalledInfo res;
942
943        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
944            args = _a;
945            res = _r;
946        }
947    }
948
949    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
950    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
951
952    // XML tags for backup/restore of various bits of state
953    private static final String TAG_PREFERRED_BACKUP = "pa";
954    private static final String TAG_DEFAULT_APPS = "da";
955    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
956
957    final String mRequiredVerifierPackage;
958    final String mRequiredInstallerPackage;
959
960    private final PackageUsage mPackageUsage = new PackageUsage();
961
962    private class PackageUsage {
963        private static final int WRITE_INTERVAL
964            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
965
966        private final Object mFileLock = new Object();
967        private final AtomicLong mLastWritten = new AtomicLong(0);
968        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
969
970        private boolean mIsHistoricalPackageUsageAvailable = true;
971
972        boolean isHistoricalPackageUsageAvailable() {
973            return mIsHistoricalPackageUsageAvailable;
974        }
975
976        void write(boolean force) {
977            if (force) {
978                writeInternal();
979                return;
980            }
981            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
982                && !DEBUG_DEXOPT) {
983                return;
984            }
985            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
986                new Thread("PackageUsage_DiskWriter") {
987                    @Override
988                    public void run() {
989                        try {
990                            writeInternal();
991                        } finally {
992                            mBackgroundWriteRunning.set(false);
993                        }
994                    }
995                }.start();
996            }
997        }
998
999        private void writeInternal() {
1000            synchronized (mPackages) {
1001                synchronized (mFileLock) {
1002                    AtomicFile file = getFile();
1003                    FileOutputStream f = null;
1004                    try {
1005                        f = file.startWrite();
1006                        BufferedOutputStream out = new BufferedOutputStream(f);
1007                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1008                        StringBuilder sb = new StringBuilder();
1009                        for (PackageParser.Package pkg : mPackages.values()) {
1010                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1011                                continue;
1012                            }
1013                            sb.setLength(0);
1014                            sb.append(pkg.packageName);
1015                            sb.append(' ');
1016                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1017                            sb.append('\n');
1018                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1019                        }
1020                        out.flush();
1021                        file.finishWrite(f);
1022                    } catch (IOException e) {
1023                        if (f != null) {
1024                            file.failWrite(f);
1025                        }
1026                        Log.e(TAG, "Failed to write package usage times", e);
1027                    }
1028                }
1029            }
1030            mLastWritten.set(SystemClock.elapsedRealtime());
1031        }
1032
1033        void readLP() {
1034            synchronized (mFileLock) {
1035                AtomicFile file = getFile();
1036                BufferedInputStream in = null;
1037                try {
1038                    in = new BufferedInputStream(file.openRead());
1039                    StringBuffer sb = new StringBuffer();
1040                    while (true) {
1041                        String packageName = readToken(in, sb, ' ');
1042                        if (packageName == null) {
1043                            break;
1044                        }
1045                        String timeInMillisString = readToken(in, sb, '\n');
1046                        if (timeInMillisString == null) {
1047                            throw new IOException("Failed to find last usage time for package "
1048                                                  + packageName);
1049                        }
1050                        PackageParser.Package pkg = mPackages.get(packageName);
1051                        if (pkg == null) {
1052                            continue;
1053                        }
1054                        long timeInMillis;
1055                        try {
1056                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1057                        } catch (NumberFormatException e) {
1058                            throw new IOException("Failed to parse " + timeInMillisString
1059                                                  + " as a long.", e);
1060                        }
1061                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1062                    }
1063                } catch (FileNotFoundException expected) {
1064                    mIsHistoricalPackageUsageAvailable = false;
1065                } catch (IOException e) {
1066                    Log.w(TAG, "Failed to read package usage times", e);
1067                } finally {
1068                    IoUtils.closeQuietly(in);
1069                }
1070            }
1071            mLastWritten.set(SystemClock.elapsedRealtime());
1072        }
1073
1074        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1075                throws IOException {
1076            sb.setLength(0);
1077            while (true) {
1078                int ch = in.read();
1079                if (ch == -1) {
1080                    if (sb.length() == 0) {
1081                        return null;
1082                    }
1083                    throw new IOException("Unexpected EOF");
1084                }
1085                if (ch == endOfToken) {
1086                    return sb.toString();
1087                }
1088                sb.append((char)ch);
1089            }
1090        }
1091
1092        private AtomicFile getFile() {
1093            File dataDir = Environment.getDataDirectory();
1094            File systemDir = new File(dataDir, "system");
1095            File fname = new File(systemDir, "package-usage.list");
1096            return new AtomicFile(fname);
1097        }
1098    }
1099
1100    class PackageHandler extends Handler {
1101        private boolean mBound = false;
1102        final ArrayList<HandlerParams> mPendingInstalls =
1103            new ArrayList<HandlerParams>();
1104
1105        private boolean connectToService() {
1106            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1107                    " DefaultContainerService");
1108            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1109            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1110            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1111                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1112                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1113                mBound = true;
1114                return true;
1115            }
1116            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1117            return false;
1118        }
1119
1120        private void disconnectService() {
1121            mContainerService = null;
1122            mBound = false;
1123            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1124            mContext.unbindService(mDefContainerConn);
1125            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1126        }
1127
1128        PackageHandler(Looper looper) {
1129            super(looper);
1130        }
1131
1132        public void handleMessage(Message msg) {
1133            try {
1134                doHandleMessage(msg);
1135            } finally {
1136                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1137            }
1138        }
1139
1140        void doHandleMessage(Message msg) {
1141            switch (msg.what) {
1142                case INIT_COPY: {
1143                    HandlerParams params = (HandlerParams) msg.obj;
1144                    int idx = mPendingInstalls.size();
1145                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1146                    // If a bind was already initiated we dont really
1147                    // need to do anything. The pending install
1148                    // will be processed later on.
1149                    if (!mBound) {
1150                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1151                                System.identityHashCode(mHandler));
1152                        // If this is the only one pending we might
1153                        // have to bind to the service again.
1154                        if (!connectToService()) {
1155                            Slog.e(TAG, "Failed to bind to media container service");
1156                            params.serviceError();
1157                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1158                                    System.identityHashCode(mHandler));
1159                            if (params.traceMethod != null) {
1160                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1161                                        params.traceCookie);
1162                            }
1163                            return;
1164                        } else {
1165                            // Once we bind to the service, the first
1166                            // pending request will be processed.
1167                            mPendingInstalls.add(idx, params);
1168                        }
1169                    } else {
1170                        mPendingInstalls.add(idx, params);
1171                        // Already bound to the service. Just make
1172                        // sure we trigger off processing the first request.
1173                        if (idx == 0) {
1174                            mHandler.sendEmptyMessage(MCS_BOUND);
1175                        }
1176                    }
1177                    break;
1178                }
1179                case MCS_BOUND: {
1180                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1181                    if (msg.obj != null) {
1182                        mContainerService = (IMediaContainerService) msg.obj;
1183                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1184                                System.identityHashCode(mHandler));
1185                    }
1186                    if (mContainerService == null) {
1187                        if (!mBound) {
1188                            // Something seriously wrong since we are not bound and we are not
1189                            // waiting for connection. Bail out.
1190                            Slog.e(TAG, "Cannot bind to media container service");
1191                            for (HandlerParams params : mPendingInstalls) {
1192                                // Indicate service bind error
1193                                params.serviceError();
1194                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1195                                        System.identityHashCode(params));
1196                                if (params.traceMethod != null) {
1197                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1198                                            params.traceMethod, params.traceCookie);
1199                                }
1200                                return;
1201                            }
1202                            mPendingInstalls.clear();
1203                        } else {
1204                            Slog.w(TAG, "Waiting to connect to media container service");
1205                        }
1206                    } else if (mPendingInstalls.size() > 0) {
1207                        HandlerParams params = mPendingInstalls.get(0);
1208                        if (params != null) {
1209                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1210                                    System.identityHashCode(params));
1211                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1212                            if (params.startCopy()) {
1213                                // We are done...  look for more work or to
1214                                // go idle.
1215                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1216                                        "Checking for more work or unbind...");
1217                                // Delete pending install
1218                                if (mPendingInstalls.size() > 0) {
1219                                    mPendingInstalls.remove(0);
1220                                }
1221                                if (mPendingInstalls.size() == 0) {
1222                                    if (mBound) {
1223                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1224                                                "Posting delayed MCS_UNBIND");
1225                                        removeMessages(MCS_UNBIND);
1226                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1227                                        // Unbind after a little delay, to avoid
1228                                        // continual thrashing.
1229                                        sendMessageDelayed(ubmsg, 10000);
1230                                    }
1231                                } else {
1232                                    // There are more pending requests in queue.
1233                                    // Just post MCS_BOUND message to trigger processing
1234                                    // of next pending install.
1235                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1236                                            "Posting MCS_BOUND for next work");
1237                                    mHandler.sendEmptyMessage(MCS_BOUND);
1238                                }
1239                            }
1240                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1241                        }
1242                    } else {
1243                        // Should never happen ideally.
1244                        Slog.w(TAG, "Empty queue");
1245                    }
1246                    break;
1247                }
1248                case MCS_RECONNECT: {
1249                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1250                    if (mPendingInstalls.size() > 0) {
1251                        if (mBound) {
1252                            disconnectService();
1253                        }
1254                        if (!connectToService()) {
1255                            Slog.e(TAG, "Failed to bind to media container service");
1256                            for (HandlerParams params : mPendingInstalls) {
1257                                // Indicate service bind error
1258                                params.serviceError();
1259                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1260                                        System.identityHashCode(params));
1261                            }
1262                            mPendingInstalls.clear();
1263                        }
1264                    }
1265                    break;
1266                }
1267                case MCS_UNBIND: {
1268                    // If there is no actual work left, then time to unbind.
1269                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1270
1271                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1272                        if (mBound) {
1273                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1274
1275                            disconnectService();
1276                        }
1277                    } else if (mPendingInstalls.size() > 0) {
1278                        // There are more pending requests in queue.
1279                        // Just post MCS_BOUND message to trigger processing
1280                        // of next pending install.
1281                        mHandler.sendEmptyMessage(MCS_BOUND);
1282                    }
1283
1284                    break;
1285                }
1286                case MCS_GIVE_UP: {
1287                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1288                    HandlerParams params = mPendingInstalls.remove(0);
1289                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1290                            System.identityHashCode(params));
1291                    break;
1292                }
1293                case SEND_PENDING_BROADCAST: {
1294                    String packages[];
1295                    ArrayList<String> components[];
1296                    int size = 0;
1297                    int uids[];
1298                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1299                    synchronized (mPackages) {
1300                        if (mPendingBroadcasts == null) {
1301                            return;
1302                        }
1303                        size = mPendingBroadcasts.size();
1304                        if (size <= 0) {
1305                            // Nothing to be done. Just return
1306                            return;
1307                        }
1308                        packages = new String[size];
1309                        components = new ArrayList[size];
1310                        uids = new int[size];
1311                        int i = 0;  // filling out the above arrays
1312
1313                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1314                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1315                            Iterator<Map.Entry<String, ArrayList<String>>> it
1316                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1317                                            .entrySet().iterator();
1318                            while (it.hasNext() && i < size) {
1319                                Map.Entry<String, ArrayList<String>> ent = it.next();
1320                                packages[i] = ent.getKey();
1321                                components[i] = ent.getValue();
1322                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1323                                uids[i] = (ps != null)
1324                                        ? UserHandle.getUid(packageUserId, ps.appId)
1325                                        : -1;
1326                                i++;
1327                            }
1328                        }
1329                        size = i;
1330                        mPendingBroadcasts.clear();
1331                    }
1332                    // Send broadcasts
1333                    for (int i = 0; i < size; i++) {
1334                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1335                    }
1336                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1337                    break;
1338                }
1339                case START_CLEANING_PACKAGE: {
1340                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1341                    final String packageName = (String)msg.obj;
1342                    final int userId = msg.arg1;
1343                    final boolean andCode = msg.arg2 != 0;
1344                    synchronized (mPackages) {
1345                        if (userId == UserHandle.USER_ALL) {
1346                            int[] users = sUserManager.getUserIds();
1347                            for (int user : users) {
1348                                mSettings.addPackageToCleanLPw(
1349                                        new PackageCleanItem(user, packageName, andCode));
1350                            }
1351                        } else {
1352                            mSettings.addPackageToCleanLPw(
1353                                    new PackageCleanItem(userId, packageName, andCode));
1354                        }
1355                    }
1356                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1357                    startCleaningPackages();
1358                } break;
1359                case POST_INSTALL: {
1360                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1361                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1362                    mRunningInstalls.delete(msg.arg1);
1363                    boolean deleteOld = false;
1364
1365                    if (data != null) {
1366                        InstallArgs args = data.args;
1367                        PackageInstalledInfo res = data.res;
1368
1369                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1370                            final String packageName = res.pkg.applicationInfo.packageName;
1371                            res.removedInfo.sendBroadcast(false, true, false);
1372                            Bundle extras = new Bundle(1);
1373                            extras.putInt(Intent.EXTRA_UID, res.uid);
1374
1375                            // Now that we successfully installed the package, grant runtime
1376                            // permissions if requested before broadcasting the install.
1377                            if ((args.installFlags
1378                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1379                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1380                                        args.installGrantPermissions);
1381                            }
1382
1383                            // Determine the set of users who are adding this
1384                            // package for the first time vs. those who are seeing
1385                            // an update.
1386                            int[] firstUsers;
1387                            int[] updateUsers = new int[0];
1388                            if (res.origUsers == null || res.origUsers.length == 0) {
1389                                firstUsers = res.newUsers;
1390                            } else {
1391                                firstUsers = new int[0];
1392                                for (int i=0; i<res.newUsers.length; i++) {
1393                                    int user = res.newUsers[i];
1394                                    boolean isNew = true;
1395                                    for (int j=0; j<res.origUsers.length; j++) {
1396                                        if (res.origUsers[j] == user) {
1397                                            isNew = false;
1398                                            break;
1399                                        }
1400                                    }
1401                                    if (isNew) {
1402                                        int[] newFirst = new int[firstUsers.length+1];
1403                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1404                                                firstUsers.length);
1405                                        newFirst[firstUsers.length] = user;
1406                                        firstUsers = newFirst;
1407                                    } else {
1408                                        int[] newUpdate = new int[updateUsers.length+1];
1409                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1410                                                updateUsers.length);
1411                                        newUpdate[updateUsers.length] = user;
1412                                        updateUsers = newUpdate;
1413                                    }
1414                                }
1415                            }
1416                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1417                                    packageName, extras, null, null, firstUsers);
1418                            final boolean update = res.removedInfo.removedPackage != null;
1419                            if (update) {
1420                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1421                            }
1422                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1423                                    packageName, extras, null, null, updateUsers);
1424                            if (update) {
1425                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1426                                        packageName, extras, null, null, updateUsers);
1427                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1428                                        null, null, packageName, null, updateUsers);
1429
1430                                // treat asec-hosted packages like removable media on upgrade
1431                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1432                                    if (DEBUG_INSTALL) {
1433                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1434                                                + " is ASEC-hosted -> AVAILABLE");
1435                                    }
1436                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1437                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1438                                    pkgList.add(packageName);
1439                                    sendResourcesChangedBroadcast(true, true,
1440                                            pkgList,uidArray, null);
1441                                }
1442                            }
1443                            if (res.removedInfo.args != null) {
1444                                // Remove the replaced package's older resources safely now
1445                                deleteOld = true;
1446                            }
1447
1448                            // If this app is a browser and it's newly-installed for some
1449                            // users, clear any default-browser state in those users
1450                            if (firstUsers.length > 0) {
1451                                // the app's nature doesn't depend on the user, so we can just
1452                                // check its browser nature in any user and generalize.
1453                                if (packageIsBrowser(packageName, firstUsers[0])) {
1454                                    synchronized (mPackages) {
1455                                        for (int userId : firstUsers) {
1456                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1457                                        }
1458                                    }
1459                                }
1460                            }
1461                            // Log current value of "unknown sources" setting
1462                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1463                                getUnknownSourcesSettings());
1464                        }
1465                        // Force a gc to clear up things
1466                        Runtime.getRuntime().gc();
1467                        // We delete after a gc for applications  on sdcard.
1468                        if (deleteOld) {
1469                            synchronized (mInstallLock) {
1470                                res.removedInfo.args.doPostDeleteLI(true);
1471                            }
1472                        }
1473                        if (args.observer != null) {
1474                            try {
1475                                Bundle extras = extrasForInstallResult(res);
1476                                args.observer.onPackageInstalled(res.name, res.returnCode,
1477                                        res.returnMsg, extras);
1478                            } catch (RemoteException e) {
1479                                Slog.i(TAG, "Observer no longer exists.");
1480                            }
1481                        }
1482                        if (args.traceMethod != null) {
1483                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1484                                    args.traceCookie);
1485                        }
1486                        return;
1487                    } else {
1488                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1489                    }
1490
1491                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1492                } break;
1493                case UPDATED_MEDIA_STATUS: {
1494                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1495                    boolean reportStatus = msg.arg1 == 1;
1496                    boolean doGc = msg.arg2 == 1;
1497                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1498                    if (doGc) {
1499                        // Force a gc to clear up stale containers.
1500                        Runtime.getRuntime().gc();
1501                    }
1502                    if (msg.obj != null) {
1503                        @SuppressWarnings("unchecked")
1504                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1505                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1506                        // Unload containers
1507                        unloadAllContainers(args);
1508                    }
1509                    if (reportStatus) {
1510                        try {
1511                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1512                            PackageHelper.getMountService().finishMediaUpdate();
1513                        } catch (RemoteException e) {
1514                            Log.e(TAG, "MountService not running?");
1515                        }
1516                    }
1517                } break;
1518                case WRITE_SETTINGS: {
1519                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1520                    synchronized (mPackages) {
1521                        removeMessages(WRITE_SETTINGS);
1522                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1523                        mSettings.writeLPr();
1524                        mDirtyUsers.clear();
1525                    }
1526                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1527                } break;
1528                case WRITE_PACKAGE_RESTRICTIONS: {
1529                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1530                    synchronized (mPackages) {
1531                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1532                        for (int userId : mDirtyUsers) {
1533                            mSettings.writePackageRestrictionsLPr(userId);
1534                        }
1535                        mDirtyUsers.clear();
1536                    }
1537                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1538                } break;
1539                case CHECK_PENDING_VERIFICATION: {
1540                    final int verificationId = msg.arg1;
1541                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1542
1543                    if ((state != null) && !state.timeoutExtended()) {
1544                        final InstallArgs args = state.getInstallArgs();
1545                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1546
1547                        Slog.i(TAG, "Verification timed out for " + originUri);
1548                        mPendingVerification.remove(verificationId);
1549
1550                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1551
1552                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1553                            Slog.i(TAG, "Continuing with installation of " + originUri);
1554                            state.setVerifierResponse(Binder.getCallingUid(),
1555                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1556                            broadcastPackageVerified(verificationId, originUri,
1557                                    PackageManager.VERIFICATION_ALLOW,
1558                                    state.getInstallArgs().getUser());
1559                            try {
1560                                ret = args.copyApk(mContainerService, true);
1561                            } catch (RemoteException e) {
1562                                Slog.e(TAG, "Could not contact the ContainerService");
1563                            }
1564                        } else {
1565                            broadcastPackageVerified(verificationId, originUri,
1566                                    PackageManager.VERIFICATION_REJECT,
1567                                    state.getInstallArgs().getUser());
1568                        }
1569
1570                        Trace.asyncTraceEnd(
1571                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1572
1573                        processPendingInstall(args, ret);
1574                        mHandler.sendEmptyMessage(MCS_UNBIND);
1575                    }
1576                    break;
1577                }
1578                case PACKAGE_VERIFIED: {
1579                    final int verificationId = msg.arg1;
1580
1581                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1582                    if (state == null) {
1583                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1584                        break;
1585                    }
1586
1587                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1588
1589                    state.setVerifierResponse(response.callerUid, response.code);
1590
1591                    if (state.isVerificationComplete()) {
1592                        mPendingVerification.remove(verificationId);
1593
1594                        final InstallArgs args = state.getInstallArgs();
1595                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1596
1597                        int ret;
1598                        if (state.isInstallAllowed()) {
1599                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1600                            broadcastPackageVerified(verificationId, originUri,
1601                                    response.code, state.getInstallArgs().getUser());
1602                            try {
1603                                ret = args.copyApk(mContainerService, true);
1604                            } catch (RemoteException e) {
1605                                Slog.e(TAG, "Could not contact the ContainerService");
1606                            }
1607                        } else {
1608                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1609                        }
1610
1611                        Trace.asyncTraceEnd(
1612                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1613
1614                        processPendingInstall(args, ret);
1615                        mHandler.sendEmptyMessage(MCS_UNBIND);
1616                    }
1617
1618                    break;
1619                }
1620                case START_INTENT_FILTER_VERIFICATIONS: {
1621                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1622                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1623                            params.replacing, params.pkg);
1624                    break;
1625                }
1626                case INTENT_FILTER_VERIFIED: {
1627                    final int verificationId = msg.arg1;
1628
1629                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1630                            verificationId);
1631                    if (state == null) {
1632                        Slog.w(TAG, "Invalid IntentFilter verification token "
1633                                + verificationId + " received");
1634                        break;
1635                    }
1636
1637                    final int userId = state.getUserId();
1638
1639                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1640                            "Processing IntentFilter verification with token:"
1641                            + verificationId + " and userId:" + userId);
1642
1643                    final IntentFilterVerificationResponse response =
1644                            (IntentFilterVerificationResponse) msg.obj;
1645
1646                    state.setVerifierResponse(response.callerUid, response.code);
1647
1648                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1649                            "IntentFilter verification with token:" + verificationId
1650                            + " and userId:" + userId
1651                            + " is settings verifier response with response code:"
1652                            + response.code);
1653
1654                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1655                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1656                                + response.getFailedDomainsString());
1657                    }
1658
1659                    if (state.isVerificationComplete()) {
1660                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1661                    } else {
1662                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1663                                "IntentFilter verification with token:" + verificationId
1664                                + " was not said to be complete");
1665                    }
1666
1667                    break;
1668                }
1669            }
1670        }
1671    }
1672
1673    private StorageEventListener mStorageListener = new StorageEventListener() {
1674        @Override
1675        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1676            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1677                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1678                    final String volumeUuid = vol.getFsUuid();
1679
1680                    // Clean up any users or apps that were removed or recreated
1681                    // while this volume was missing
1682                    reconcileUsers(volumeUuid);
1683                    reconcileApps(volumeUuid);
1684
1685                    // Clean up any install sessions that expired or were
1686                    // cancelled while this volume was missing
1687                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1688
1689                    loadPrivatePackages(vol);
1690
1691                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1692                    unloadPrivatePackages(vol);
1693                }
1694            }
1695
1696            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1697                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1698                    updateExternalMediaStatus(true, false);
1699                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1700                    updateExternalMediaStatus(false, false);
1701                }
1702            }
1703        }
1704
1705        @Override
1706        public void onVolumeForgotten(String fsUuid) {
1707            if (TextUtils.isEmpty(fsUuid)) {
1708                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1709                return;
1710            }
1711
1712            // Remove any apps installed on the forgotten volume
1713            synchronized (mPackages) {
1714                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1715                for (PackageSetting ps : packages) {
1716                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1717                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1718                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1719                }
1720
1721                mSettings.onVolumeForgotten(fsUuid);
1722                mSettings.writeLPr();
1723            }
1724        }
1725    };
1726
1727    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1728            String[] grantedPermissions) {
1729        if (userId >= UserHandle.USER_OWNER) {
1730            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1731        } else if (userId == UserHandle.USER_ALL) {
1732            final int[] userIds;
1733            synchronized (mPackages) {
1734                userIds = UserManagerService.getInstance().getUserIds();
1735            }
1736            for (int someUserId : userIds) {
1737                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1738            }
1739        }
1740
1741        // We could have touched GID membership, so flush out packages.list
1742        synchronized (mPackages) {
1743            mSettings.writePackageListLPr();
1744        }
1745    }
1746
1747    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1748            String[] grantedPermissions) {
1749        SettingBase sb = (SettingBase) pkg.mExtras;
1750        if (sb == null) {
1751            return;
1752        }
1753
1754        PermissionsState permissionsState = sb.getPermissionsState();
1755
1756        for (String permission : pkg.requestedPermissions) {
1757            BasePermission bp = mSettings.mPermissions.get(permission);
1758            if (bp != null && bp.isRuntime() && (grantedPermissions == null
1759                    || ArrayUtils.contains(grantedPermissions, permission))) {
1760                permissionsState.grantRuntimePermission(bp, userId);
1761            }
1762        }
1763    }
1764
1765    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1766        Bundle extras = null;
1767        switch (res.returnCode) {
1768            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1769                extras = new Bundle();
1770                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1771                        res.origPermission);
1772                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1773                        res.origPackage);
1774                break;
1775            }
1776            case PackageManager.INSTALL_SUCCEEDED: {
1777                extras = new Bundle();
1778                extras.putBoolean(Intent.EXTRA_REPLACING,
1779                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1780                break;
1781            }
1782        }
1783        return extras;
1784    }
1785
1786    void scheduleWriteSettingsLocked() {
1787        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1788            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1789        }
1790    }
1791
1792    void scheduleWritePackageRestrictionsLocked(int userId) {
1793        if (!sUserManager.exists(userId)) return;
1794        mDirtyUsers.add(userId);
1795        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1796            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1797        }
1798    }
1799
1800    public static PackageManagerService main(Context context, Installer installer,
1801            boolean factoryTest, boolean onlyCore) {
1802        PackageManagerService m = new PackageManagerService(context, installer,
1803                factoryTest, onlyCore);
1804        ServiceManager.addService("package", m);
1805        return m;
1806    }
1807
1808    static String[] splitString(String str, char sep) {
1809        int count = 1;
1810        int i = 0;
1811        while ((i=str.indexOf(sep, i)) >= 0) {
1812            count++;
1813            i++;
1814        }
1815
1816        String[] res = new String[count];
1817        i=0;
1818        count = 0;
1819        int lastI=0;
1820        while ((i=str.indexOf(sep, i)) >= 0) {
1821            res[count] = str.substring(lastI, i);
1822            count++;
1823            i++;
1824            lastI = i;
1825        }
1826        res[count] = str.substring(lastI, str.length());
1827        return res;
1828    }
1829
1830    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1831        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1832                Context.DISPLAY_SERVICE);
1833        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1834    }
1835
1836    public PackageManagerService(Context context, Installer installer,
1837            boolean factoryTest, boolean onlyCore) {
1838        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1839                SystemClock.uptimeMillis());
1840
1841        if (mSdkVersion <= 0) {
1842            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1843        }
1844
1845        mContext = context;
1846        mFactoryTest = factoryTest;
1847        mOnlyCore = onlyCore;
1848        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1849        mMetrics = new DisplayMetrics();
1850        mSettings = new Settings(mPackages);
1851        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1852                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1853        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1854                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1855        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1856                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1857        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1858                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1859        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1860                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1861        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1862                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1863
1864        // TODO: add a property to control this?
1865        long dexOptLRUThresholdInMinutes;
1866        if (mLazyDexOpt) {
1867            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1868        } else {
1869            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1870        }
1871        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1872
1873        String separateProcesses = SystemProperties.get("debug.separate_processes");
1874        if (separateProcesses != null && separateProcesses.length() > 0) {
1875            if ("*".equals(separateProcesses)) {
1876                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1877                mSeparateProcesses = null;
1878                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1879            } else {
1880                mDefParseFlags = 0;
1881                mSeparateProcesses = separateProcesses.split(",");
1882                Slog.w(TAG, "Running with debug.separate_processes: "
1883                        + separateProcesses);
1884            }
1885        } else {
1886            mDefParseFlags = 0;
1887            mSeparateProcesses = null;
1888        }
1889
1890        mInstaller = installer;
1891        mPackageDexOptimizer = new PackageDexOptimizer(this);
1892        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1893
1894        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1895                FgThread.get().getLooper());
1896
1897        getDefaultDisplayMetrics(context, mMetrics);
1898
1899        SystemConfig systemConfig = SystemConfig.getInstance();
1900        mGlobalGids = systemConfig.getGlobalGids();
1901        mSystemPermissions = systemConfig.getSystemPermissions();
1902        mAvailableFeatures = systemConfig.getAvailableFeatures();
1903
1904        synchronized (mInstallLock) {
1905        // writer
1906        synchronized (mPackages) {
1907            mHandlerThread = new ServiceThread(TAG,
1908                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1909            mHandlerThread.start();
1910            mHandler = new PackageHandler(mHandlerThread.getLooper());
1911            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1912
1913            File dataDir = Environment.getDataDirectory();
1914            mAppDataDir = new File(dataDir, "data");
1915            mAppInstallDir = new File(dataDir, "app");
1916            mAppLib32InstallDir = new File(dataDir, "app-lib");
1917            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1918            mUserAppDataDir = new File(dataDir, "user");
1919            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1920
1921            sUserManager = new UserManagerService(context, this,
1922                    mInstallLock, mPackages);
1923
1924            // Propagate permission configuration in to package manager.
1925            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1926                    = systemConfig.getPermissions();
1927            for (int i=0; i<permConfig.size(); i++) {
1928                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1929                BasePermission bp = mSettings.mPermissions.get(perm.name);
1930                if (bp == null) {
1931                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1932                    mSettings.mPermissions.put(perm.name, bp);
1933                }
1934                if (perm.gids != null) {
1935                    bp.setGids(perm.gids, perm.perUser);
1936                }
1937            }
1938
1939            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1940            for (int i=0; i<libConfig.size(); i++) {
1941                mSharedLibraries.put(libConfig.keyAt(i),
1942                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1943            }
1944
1945            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1946
1947            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
1948
1949            String customResolverActivity = Resources.getSystem().getString(
1950                    R.string.config_customResolverActivity);
1951            if (TextUtils.isEmpty(customResolverActivity)) {
1952                customResolverActivity = null;
1953            } else {
1954                mCustomResolverComponentName = ComponentName.unflattenFromString(
1955                        customResolverActivity);
1956            }
1957
1958            long startTime = SystemClock.uptimeMillis();
1959
1960            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1961                    startTime);
1962
1963            // Set flag to monitor and not change apk file paths when
1964            // scanning install directories.
1965            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1966
1967            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1968
1969            /**
1970             * Add everything in the in the boot class path to the
1971             * list of process files because dexopt will have been run
1972             * if necessary during zygote startup.
1973             */
1974            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1975            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1976
1977            if (bootClassPath != null) {
1978                String[] bootClassPathElements = splitString(bootClassPath, ':');
1979                for (String element : bootClassPathElements) {
1980                    alreadyDexOpted.add(element);
1981                }
1982            } else {
1983                Slog.w(TAG, "No BOOTCLASSPATH found!");
1984            }
1985
1986            if (systemServerClassPath != null) {
1987                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1988                for (String element : systemServerClassPathElements) {
1989                    alreadyDexOpted.add(element);
1990                }
1991            } else {
1992                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1993            }
1994
1995            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1996            final String[] dexCodeInstructionSets =
1997                    getDexCodeInstructionSets(
1998                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1999
2000            /**
2001             * Ensure all external libraries have had dexopt run on them.
2002             */
2003            if (mSharedLibraries.size() > 0) {
2004                // NOTE: For now, we're compiling these system "shared libraries"
2005                // (and framework jars) into all available architectures. It's possible
2006                // to compile them only when we come across an app that uses them (there's
2007                // already logic for that in scanPackageLI) but that adds some complexity.
2008                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2009                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2010                        final String lib = libEntry.path;
2011                        if (lib == null) {
2012                            continue;
2013                        }
2014
2015                        try {
2016                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2017                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2018                                alreadyDexOpted.add(lib);
2019                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2020                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2021                            }
2022                        } catch (FileNotFoundException e) {
2023                            Slog.w(TAG, "Library not found: " + lib);
2024                        } catch (IOException e) {
2025                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2026                                    + e.getMessage());
2027                        }
2028                    }
2029                }
2030            }
2031
2032            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2033
2034            // Gross hack for now: we know this file doesn't contain any
2035            // code, so don't dexopt it to avoid the resulting log spew.
2036            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
2037
2038            // Gross hack for now: we know this file is only part of
2039            // the boot class path for art, so don't dexopt it to
2040            // avoid the resulting log spew.
2041            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
2042
2043            /**
2044             * There are a number of commands implemented in Java, which
2045             * we currently need to do the dexopt on so that they can be
2046             * run from a non-root shell.
2047             */
2048            String[] frameworkFiles = frameworkDir.list();
2049            if (frameworkFiles != null) {
2050                // TODO: We could compile these only for the most preferred ABI. We should
2051                // first double check that the dex files for these commands are not referenced
2052                // by other system apps.
2053                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2054                    for (int i=0; i<frameworkFiles.length; i++) {
2055                        File libPath = new File(frameworkDir, frameworkFiles[i]);
2056                        String path = libPath.getPath();
2057                        // Skip the file if we already did it.
2058                        if (alreadyDexOpted.contains(path)) {
2059                            continue;
2060                        }
2061                        // Skip the file if it is not a type we want to dexopt.
2062                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2063                            continue;
2064                        }
2065                        try {
2066                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2067                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2068                                mInstaller.dexopt(path, Process.SYSTEM_UID, dexCodeInstructionSet,
2069                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2070                            }
2071                        } catch (FileNotFoundException e) {
2072                            Slog.w(TAG, "Jar not found: " + path);
2073                        } catch (IOException e) {
2074                            Slog.w(TAG, "Exception reading jar: " + path, e);
2075                        }
2076                    }
2077                }
2078            }
2079
2080            final VersionInfo ver = mSettings.getInternalVersion();
2081            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2082            // when upgrading from pre-M, promote system app permissions from install to runtime
2083            mPromoteSystemApps =
2084                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2085
2086            // save off the names of pre-existing system packages prior to scanning; we don't
2087            // want to automatically grant runtime permissions for new system apps
2088            if (mPromoteSystemApps) {
2089                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2090                while (pkgSettingIter.hasNext()) {
2091                    PackageSetting ps = pkgSettingIter.next();
2092                    if (isSystemApp(ps)) {
2093                        mExistingSystemPackages.add(ps.name);
2094                    }
2095                }
2096            }
2097
2098            // Collect vendor overlay packages.
2099            // (Do this before scanning any apps.)
2100            // For security and version matching reason, only consider
2101            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2102            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2103            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2104                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2105
2106            // Find base frameworks (resource packages without code).
2107            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2108                    | PackageParser.PARSE_IS_SYSTEM_DIR
2109                    | PackageParser.PARSE_IS_PRIVILEGED,
2110                    scanFlags | SCAN_NO_DEX, 0);
2111
2112            // Collected privileged system packages.
2113            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2114            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2115                    | PackageParser.PARSE_IS_SYSTEM_DIR
2116                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2117
2118            // Collect ordinary system packages.
2119            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2120            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2121                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2122
2123            // Collect all vendor packages.
2124            File vendorAppDir = new File("/vendor/app");
2125            try {
2126                vendorAppDir = vendorAppDir.getCanonicalFile();
2127            } catch (IOException e) {
2128                // failed to look up canonical path, continue with original one
2129            }
2130            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2131                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2132
2133            // Collect all OEM packages.
2134            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2135            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2136                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2137
2138            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2139            mInstaller.moveFiles();
2140
2141            // Prune any system packages that no longer exist.
2142            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2143            if (!mOnlyCore) {
2144                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2145                while (psit.hasNext()) {
2146                    PackageSetting ps = psit.next();
2147
2148                    /*
2149                     * If this is not a system app, it can't be a
2150                     * disable system app.
2151                     */
2152                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2153                        continue;
2154                    }
2155
2156                    /*
2157                     * If the package is scanned, it's not erased.
2158                     */
2159                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2160                    if (scannedPkg != null) {
2161                        /*
2162                         * If the system app is both scanned and in the
2163                         * disabled packages list, then it must have been
2164                         * added via OTA. Remove it from the currently
2165                         * scanned package so the previously user-installed
2166                         * application can be scanned.
2167                         */
2168                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2169                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2170                                    + ps.name + "; removing system app.  Last known codePath="
2171                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2172                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2173                                    + scannedPkg.mVersionCode);
2174                            removePackageLI(ps, true);
2175                            mExpectingBetter.put(ps.name, ps.codePath);
2176                        }
2177
2178                        continue;
2179                    }
2180
2181                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2182                        psit.remove();
2183                        logCriticalInfo(Log.WARN, "System package " + ps.name
2184                                + " no longer exists; wiping its data");
2185                        removeDataDirsLI(null, ps.name);
2186                    } else {
2187                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2188                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2189                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2190                        }
2191                    }
2192                }
2193            }
2194
2195            //look for any incomplete package installations
2196            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2197            //clean up list
2198            for(int i = 0; i < deletePkgsList.size(); i++) {
2199                //clean up here
2200                cleanupInstallFailedPackage(deletePkgsList.get(i));
2201            }
2202            //delete tmp files
2203            deleteTempPackageFiles();
2204
2205            // Remove any shared userIDs that have no associated packages
2206            mSettings.pruneSharedUsersLPw();
2207
2208            if (!mOnlyCore) {
2209                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2210                        SystemClock.uptimeMillis());
2211                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2212
2213                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2214                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2215
2216                /**
2217                 * Remove disable package settings for any updated system
2218                 * apps that were removed via an OTA. If they're not a
2219                 * previously-updated app, remove them completely.
2220                 * Otherwise, just revoke their system-level permissions.
2221                 */
2222                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2223                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2224                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2225
2226                    String msg;
2227                    if (deletedPkg == null) {
2228                        msg = "Updated system package " + deletedAppName
2229                                + " no longer exists; wiping its data";
2230                        removeDataDirsLI(null, deletedAppName);
2231                    } else {
2232                        msg = "Updated system app + " + deletedAppName
2233                                + " no longer present; removing system privileges for "
2234                                + deletedAppName;
2235
2236                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2237
2238                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2239                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2240                    }
2241                    logCriticalInfo(Log.WARN, msg);
2242                }
2243
2244                /**
2245                 * Make sure all system apps that we expected to appear on
2246                 * the userdata partition actually showed up. If they never
2247                 * appeared, crawl back and revive the system version.
2248                 */
2249                for (int i = 0; i < mExpectingBetter.size(); i++) {
2250                    final String packageName = mExpectingBetter.keyAt(i);
2251                    if (!mPackages.containsKey(packageName)) {
2252                        final File scanFile = mExpectingBetter.valueAt(i);
2253
2254                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2255                                + " but never showed up; reverting to system");
2256
2257                        final int reparseFlags;
2258                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2259                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2260                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2261                                    | PackageParser.PARSE_IS_PRIVILEGED;
2262                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2263                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2264                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2265                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2266                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2267                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2268                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2269                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2270                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2271                        } else {
2272                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2273                            continue;
2274                        }
2275
2276                        mSettings.enableSystemPackageLPw(packageName);
2277
2278                        try {
2279                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2280                        } catch (PackageManagerException e) {
2281                            Slog.e(TAG, "Failed to parse original system package: "
2282                                    + e.getMessage());
2283                        }
2284                    }
2285                }
2286            }
2287            mExpectingBetter.clear();
2288
2289            // Now that we know all of the shared libraries, update all clients to have
2290            // the correct library paths.
2291            updateAllSharedLibrariesLPw();
2292
2293            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2294                // NOTE: We ignore potential failures here during a system scan (like
2295                // the rest of the commands above) because there's precious little we
2296                // can do about it. A settings error is reported, though.
2297                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2298                        false /* force dexopt */, false /* defer dexopt */,
2299                        false /* boot complete */);
2300            }
2301
2302            // Now that we know all the packages we are keeping,
2303            // read and update their last usage times.
2304            mPackageUsage.readLP();
2305
2306            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2307                    SystemClock.uptimeMillis());
2308            Slog.i(TAG, "Time to scan packages: "
2309                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2310                    + " seconds");
2311
2312            // If the platform SDK has changed since the last time we booted,
2313            // we need to re-grant app permission to catch any new ones that
2314            // appear.  This is really a hack, and means that apps can in some
2315            // cases get permissions that the user didn't initially explicitly
2316            // allow...  it would be nice to have some better way to handle
2317            // this situation.
2318            int updateFlags = UPDATE_PERMISSIONS_ALL;
2319            if (ver.sdkVersion != mSdkVersion) {
2320                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2321                        + mSdkVersion + "; regranting permissions for internal storage");
2322                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2323            }
2324            updatePermissionsLPw(null, null, updateFlags);
2325            ver.sdkVersion = mSdkVersion;
2326
2327            // If this is the first boot or an update from pre-M, and it is a normal
2328            // boot, then we need to initialize the default preferred apps across
2329            // all defined users.
2330            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2331                for (UserInfo user : sUserManager.getUsers(true)) {
2332                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2333                    applyFactoryDefaultBrowserLPw(user.id);
2334                    primeDomainVerificationsLPw(user.id);
2335                }
2336            }
2337
2338            // If this is first boot after an OTA, and a normal boot, then
2339            // we need to clear code cache directories.
2340            if (mIsUpgrade && !onlyCore) {
2341                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2342                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2343                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2344                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2345                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2346                    }
2347                }
2348                ver.fingerprint = Build.FINGERPRINT;
2349            }
2350
2351            checkDefaultBrowser();
2352
2353            // clear only after permissions and other defaults have been updated
2354            mExistingSystemPackages.clear();
2355            mPromoteSystemApps = false;
2356
2357            // All the changes are done during package scanning.
2358            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2359
2360            // can downgrade to reader
2361            mSettings.writeLPr();
2362
2363            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2364                    SystemClock.uptimeMillis());
2365
2366            mRequiredVerifierPackage = getRequiredVerifierLPr();
2367            mRequiredInstallerPackage = getRequiredInstallerLPr();
2368
2369            mInstallerService = new PackageInstallerService(context, this);
2370
2371            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2372            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2373                    mIntentFilterVerifierComponent);
2374
2375        } // synchronized (mPackages)
2376        } // synchronized (mInstallLock)
2377
2378        // Now after opening every single application zip, make sure they
2379        // are all flushed.  Not really needed, but keeps things nice and
2380        // tidy.
2381        Runtime.getRuntime().gc();
2382
2383        // Expose private service for system components to use.
2384        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2385    }
2386
2387    @Override
2388    public boolean isFirstBoot() {
2389        return !mRestoredSettings;
2390    }
2391
2392    @Override
2393    public boolean isOnlyCoreApps() {
2394        return mOnlyCore;
2395    }
2396
2397    @Override
2398    public boolean isUpgrade() {
2399        return mIsUpgrade;
2400    }
2401
2402    private String getRequiredVerifierLPr() {
2403        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2404        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2405                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2406
2407        String requiredVerifier = null;
2408
2409        final int N = receivers.size();
2410        for (int i = 0; i < N; i++) {
2411            final ResolveInfo info = receivers.get(i);
2412
2413            if (info.activityInfo == null) {
2414                continue;
2415            }
2416
2417            final String packageName = info.activityInfo.packageName;
2418
2419            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2420                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2421                continue;
2422            }
2423
2424            if (requiredVerifier != null) {
2425                throw new RuntimeException("There can be only one required verifier");
2426            }
2427
2428            requiredVerifier = packageName;
2429        }
2430
2431        return requiredVerifier;
2432    }
2433
2434    private String getRequiredInstallerLPr() {
2435        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2436        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2437        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2438
2439        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2440                PACKAGE_MIME_TYPE, 0, 0);
2441
2442        String requiredInstaller = null;
2443
2444        final int N = installers.size();
2445        for (int i = 0; i < N; i++) {
2446            final ResolveInfo info = installers.get(i);
2447            final String packageName = info.activityInfo.packageName;
2448
2449            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2450                continue;
2451            }
2452
2453            if (requiredInstaller != null) {
2454                throw new RuntimeException("There must be one required installer");
2455            }
2456
2457            requiredInstaller = packageName;
2458        }
2459
2460        if (requiredInstaller == null) {
2461            throw new RuntimeException("There must be one required installer");
2462        }
2463
2464        return requiredInstaller;
2465    }
2466
2467    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2468        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2469        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2470                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2471
2472        ComponentName verifierComponentName = null;
2473
2474        int priority = -1000;
2475        final int N = receivers.size();
2476        for (int i = 0; i < N; i++) {
2477            final ResolveInfo info = receivers.get(i);
2478
2479            if (info.activityInfo == null) {
2480                continue;
2481            }
2482
2483            final String packageName = info.activityInfo.packageName;
2484
2485            final PackageSetting ps = mSettings.mPackages.get(packageName);
2486            if (ps == null) {
2487                continue;
2488            }
2489
2490            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2491                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2492                continue;
2493            }
2494
2495            // Select the IntentFilterVerifier with the highest priority
2496            if (priority < info.priority) {
2497                priority = info.priority;
2498                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2499                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2500                        + verifierComponentName + " with priority: " + info.priority);
2501            }
2502        }
2503
2504        return verifierComponentName;
2505    }
2506
2507    private void primeDomainVerificationsLPw(int userId) {
2508        if (DEBUG_DOMAIN_VERIFICATION) {
2509            Slog.d(TAG, "Priming domain verifications in user " + userId);
2510        }
2511
2512        SystemConfig systemConfig = SystemConfig.getInstance();
2513        ArraySet<String> packages = systemConfig.getLinkedApps();
2514        ArraySet<String> domains = new ArraySet<String>();
2515
2516        for (String packageName : packages) {
2517            PackageParser.Package pkg = mPackages.get(packageName);
2518            if (pkg != null) {
2519                if (!pkg.isSystemApp()) {
2520                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2521                    continue;
2522                }
2523
2524                domains.clear();
2525                for (PackageParser.Activity a : pkg.activities) {
2526                    for (ActivityIntentInfo filter : a.intents) {
2527                        if (hasValidDomains(filter)) {
2528                            domains.addAll(filter.getHostsList());
2529                        }
2530                    }
2531                }
2532
2533                if (domains.size() > 0) {
2534                    if (DEBUG_DOMAIN_VERIFICATION) {
2535                        Slog.v(TAG, "      + " + packageName);
2536                    }
2537                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2538                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2539                    // and then 'always' in the per-user state actually used for intent resolution.
2540                    final IntentFilterVerificationInfo ivi;
2541                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2542                            new ArrayList<String>(domains));
2543                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2544                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2545                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2546                } else {
2547                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2548                            + "' does not handle web links");
2549                }
2550            } else {
2551                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2552            }
2553        }
2554
2555        scheduleWritePackageRestrictionsLocked(userId);
2556        scheduleWriteSettingsLocked();
2557    }
2558
2559    private void applyFactoryDefaultBrowserLPw(int userId) {
2560        // The default browser app's package name is stored in a string resource,
2561        // with a product-specific overlay used for vendor customization.
2562        String browserPkg = mContext.getResources().getString(
2563                com.android.internal.R.string.default_browser);
2564        if (!TextUtils.isEmpty(browserPkg)) {
2565            // non-empty string => required to be a known package
2566            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2567            if (ps == null) {
2568                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2569                browserPkg = null;
2570            } else {
2571                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2572            }
2573        }
2574
2575        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2576        // default.  If there's more than one, just leave everything alone.
2577        if (browserPkg == null) {
2578            calculateDefaultBrowserLPw(userId);
2579        }
2580    }
2581
2582    private void calculateDefaultBrowserLPw(int userId) {
2583        List<String> allBrowsers = resolveAllBrowserApps(userId);
2584        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2585        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2586    }
2587
2588    private List<String> resolveAllBrowserApps(int userId) {
2589        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2590        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2591                PackageManager.MATCH_ALL, userId);
2592
2593        final int count = list.size();
2594        List<String> result = new ArrayList<String>(count);
2595        for (int i=0; i<count; i++) {
2596            ResolveInfo info = list.get(i);
2597            if (info.activityInfo == null
2598                    || !info.handleAllWebDataURI
2599                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2600                    || result.contains(info.activityInfo.packageName)) {
2601                continue;
2602            }
2603            result.add(info.activityInfo.packageName);
2604        }
2605
2606        return result;
2607    }
2608
2609    private boolean packageIsBrowser(String packageName, int userId) {
2610        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2611                PackageManager.MATCH_ALL, userId);
2612        final int N = list.size();
2613        for (int i = 0; i < N; i++) {
2614            ResolveInfo info = list.get(i);
2615            if (packageName.equals(info.activityInfo.packageName)) {
2616                return true;
2617            }
2618        }
2619        return false;
2620    }
2621
2622    private void checkDefaultBrowser() {
2623        final int myUserId = UserHandle.myUserId();
2624        final String packageName = getDefaultBrowserPackageName(myUserId);
2625        if (packageName != null) {
2626            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2627            if (info == null) {
2628                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2629                synchronized (mPackages) {
2630                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2631                }
2632            }
2633        }
2634    }
2635
2636    @Override
2637    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2638            throws RemoteException {
2639        try {
2640            return super.onTransact(code, data, reply, flags);
2641        } catch (RuntimeException e) {
2642            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2643                Slog.wtf(TAG, "Package Manager Crash", e);
2644            }
2645            throw e;
2646        }
2647    }
2648
2649    void cleanupInstallFailedPackage(PackageSetting ps) {
2650        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2651
2652        removeDataDirsLI(ps.volumeUuid, ps.name);
2653        if (ps.codePath != null) {
2654            if (ps.codePath.isDirectory()) {
2655                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2656            } else {
2657                ps.codePath.delete();
2658            }
2659        }
2660        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2661            if (ps.resourcePath.isDirectory()) {
2662                FileUtils.deleteContents(ps.resourcePath);
2663            }
2664            ps.resourcePath.delete();
2665        }
2666        mSettings.removePackageLPw(ps.name);
2667    }
2668
2669    static int[] appendInts(int[] cur, int[] add) {
2670        if (add == null) return cur;
2671        if (cur == null) return add;
2672        final int N = add.length;
2673        for (int i=0; i<N; i++) {
2674            cur = appendInt(cur, add[i]);
2675        }
2676        return cur;
2677    }
2678
2679    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2680        if (!sUserManager.exists(userId)) return null;
2681        final PackageSetting ps = (PackageSetting) p.mExtras;
2682        if (ps == null) {
2683            return null;
2684        }
2685
2686        final PermissionsState permissionsState = ps.getPermissionsState();
2687
2688        final int[] gids = permissionsState.computeGids(userId);
2689        final Set<String> permissions = permissionsState.getPermissions(userId);
2690        final PackageUserState state = ps.readUserState(userId);
2691
2692        return PackageParser.generatePackageInfo(p, gids, flags,
2693                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2694    }
2695
2696    @Override
2697    public boolean isPackageFrozen(String packageName) {
2698        synchronized (mPackages) {
2699            final PackageSetting ps = mSettings.mPackages.get(packageName);
2700            if (ps != null) {
2701                return ps.frozen;
2702            }
2703        }
2704        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2705        return true;
2706    }
2707
2708    @Override
2709    public boolean isPackageAvailable(String packageName, int userId) {
2710        if (!sUserManager.exists(userId)) return false;
2711        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2712        synchronized (mPackages) {
2713            PackageParser.Package p = mPackages.get(packageName);
2714            if (p != null) {
2715                final PackageSetting ps = (PackageSetting) p.mExtras;
2716                if (ps != null) {
2717                    final PackageUserState state = ps.readUserState(userId);
2718                    if (state != null) {
2719                        return PackageParser.isAvailable(state);
2720                    }
2721                }
2722            }
2723        }
2724        return false;
2725    }
2726
2727    @Override
2728    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2729        if (!sUserManager.exists(userId)) return null;
2730        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2731        // reader
2732        synchronized (mPackages) {
2733            PackageParser.Package p = mPackages.get(packageName);
2734            if (DEBUG_PACKAGE_INFO)
2735                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2736            if (p != null) {
2737                return generatePackageInfo(p, flags, userId);
2738            }
2739            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2740                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2741            }
2742        }
2743        return null;
2744    }
2745
2746    @Override
2747    public String[] currentToCanonicalPackageNames(String[] names) {
2748        String[] out = new String[names.length];
2749        // reader
2750        synchronized (mPackages) {
2751            for (int i=names.length-1; i>=0; i--) {
2752                PackageSetting ps = mSettings.mPackages.get(names[i]);
2753                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2754            }
2755        }
2756        return out;
2757    }
2758
2759    @Override
2760    public String[] canonicalToCurrentPackageNames(String[] names) {
2761        String[] out = new String[names.length];
2762        // reader
2763        synchronized (mPackages) {
2764            for (int i=names.length-1; i>=0; i--) {
2765                String cur = mSettings.mRenamedPackages.get(names[i]);
2766                out[i] = cur != null ? cur : names[i];
2767            }
2768        }
2769        return out;
2770    }
2771
2772    @Override
2773    public int getPackageUid(String packageName, int userId) {
2774        if (!sUserManager.exists(userId)) return -1;
2775        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2776
2777        // reader
2778        synchronized (mPackages) {
2779            PackageParser.Package p = mPackages.get(packageName);
2780            if(p != null) {
2781                return UserHandle.getUid(userId, p.applicationInfo.uid);
2782            }
2783            PackageSetting ps = mSettings.mPackages.get(packageName);
2784            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2785                return -1;
2786            }
2787            p = ps.pkg;
2788            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2789        }
2790    }
2791
2792    @Override
2793    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2794        if (!sUserManager.exists(userId)) {
2795            return null;
2796        }
2797
2798        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2799                "getPackageGids");
2800
2801        // reader
2802        synchronized (mPackages) {
2803            PackageParser.Package p = mPackages.get(packageName);
2804            if (DEBUG_PACKAGE_INFO) {
2805                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2806            }
2807            if (p != null) {
2808                PackageSetting ps = (PackageSetting) p.mExtras;
2809                return ps.getPermissionsState().computeGids(userId);
2810            }
2811        }
2812
2813        return null;
2814    }
2815
2816    static PermissionInfo generatePermissionInfo(
2817            BasePermission bp, int flags) {
2818        if (bp.perm != null) {
2819            return PackageParser.generatePermissionInfo(bp.perm, flags);
2820        }
2821        PermissionInfo pi = new PermissionInfo();
2822        pi.name = bp.name;
2823        pi.packageName = bp.sourcePackage;
2824        pi.nonLocalizedLabel = bp.name;
2825        pi.protectionLevel = bp.protectionLevel;
2826        return pi;
2827    }
2828
2829    @Override
2830    public PermissionInfo getPermissionInfo(String name, int flags) {
2831        // reader
2832        synchronized (mPackages) {
2833            final BasePermission p = mSettings.mPermissions.get(name);
2834            if (p != null) {
2835                return generatePermissionInfo(p, flags);
2836            }
2837            return null;
2838        }
2839    }
2840
2841    @Override
2842    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2843        // reader
2844        synchronized (mPackages) {
2845            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2846            for (BasePermission p : mSettings.mPermissions.values()) {
2847                if (group == null) {
2848                    if (p.perm == null || p.perm.info.group == null) {
2849                        out.add(generatePermissionInfo(p, flags));
2850                    }
2851                } else {
2852                    if (p.perm != null && group.equals(p.perm.info.group)) {
2853                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2854                    }
2855                }
2856            }
2857
2858            if (out.size() > 0) {
2859                return out;
2860            }
2861            return mPermissionGroups.containsKey(group) ? out : null;
2862        }
2863    }
2864
2865    @Override
2866    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2867        // reader
2868        synchronized (mPackages) {
2869            return PackageParser.generatePermissionGroupInfo(
2870                    mPermissionGroups.get(name), flags);
2871        }
2872    }
2873
2874    @Override
2875    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2876        // reader
2877        synchronized (mPackages) {
2878            final int N = mPermissionGroups.size();
2879            ArrayList<PermissionGroupInfo> out
2880                    = new ArrayList<PermissionGroupInfo>(N);
2881            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2882                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2883            }
2884            return out;
2885        }
2886    }
2887
2888    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2889            int userId) {
2890        if (!sUserManager.exists(userId)) return null;
2891        PackageSetting ps = mSettings.mPackages.get(packageName);
2892        if (ps != null) {
2893            if (ps.pkg == null) {
2894                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2895                        flags, userId);
2896                if (pInfo != null) {
2897                    return pInfo.applicationInfo;
2898                }
2899                return null;
2900            }
2901            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2902                    ps.readUserState(userId), userId);
2903        }
2904        return null;
2905    }
2906
2907    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2908            int userId) {
2909        if (!sUserManager.exists(userId)) return null;
2910        PackageSetting ps = mSettings.mPackages.get(packageName);
2911        if (ps != null) {
2912            PackageParser.Package pkg = ps.pkg;
2913            if (pkg == null) {
2914                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2915                    return null;
2916                }
2917                // Only data remains, so we aren't worried about code paths
2918                pkg = new PackageParser.Package(packageName);
2919                pkg.applicationInfo.packageName = packageName;
2920                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2921                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2922                pkg.applicationInfo.dataDir = Environment
2923                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2924                        .getAbsolutePath();
2925                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2926                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2927            }
2928            return generatePackageInfo(pkg, flags, userId);
2929        }
2930        return null;
2931    }
2932
2933    @Override
2934    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2935        if (!sUserManager.exists(userId)) return null;
2936        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2937        // writer
2938        synchronized (mPackages) {
2939            PackageParser.Package p = mPackages.get(packageName);
2940            if (DEBUG_PACKAGE_INFO) Log.v(
2941                    TAG, "getApplicationInfo " + packageName
2942                    + ": " + p);
2943            if (p != null) {
2944                PackageSetting ps = mSettings.mPackages.get(packageName);
2945                if (ps == null) return null;
2946                // Note: isEnabledLP() does not apply here - always return info
2947                return PackageParser.generateApplicationInfo(
2948                        p, flags, ps.readUserState(userId), userId);
2949            }
2950            if ("android".equals(packageName)||"system".equals(packageName)) {
2951                return mAndroidApplication;
2952            }
2953            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2954                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2955            }
2956        }
2957        return null;
2958    }
2959
2960    @Override
2961    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2962            final IPackageDataObserver observer) {
2963        mContext.enforceCallingOrSelfPermission(
2964                android.Manifest.permission.CLEAR_APP_CACHE, null);
2965        // Queue up an async operation since clearing cache may take a little while.
2966        mHandler.post(new Runnable() {
2967            public void run() {
2968                mHandler.removeCallbacks(this);
2969                int retCode = -1;
2970                synchronized (mInstallLock) {
2971                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2972                    if (retCode < 0) {
2973                        Slog.w(TAG, "Couldn't clear application caches");
2974                    }
2975                }
2976                if (observer != null) {
2977                    try {
2978                        observer.onRemoveCompleted(null, (retCode >= 0));
2979                    } catch (RemoteException e) {
2980                        Slog.w(TAG, "RemoveException when invoking call back");
2981                    }
2982                }
2983            }
2984        });
2985    }
2986
2987    @Override
2988    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2989            final IntentSender pi) {
2990        mContext.enforceCallingOrSelfPermission(
2991                android.Manifest.permission.CLEAR_APP_CACHE, null);
2992        // Queue up an async operation since clearing cache may take a little while.
2993        mHandler.post(new Runnable() {
2994            public void run() {
2995                mHandler.removeCallbacks(this);
2996                int retCode = -1;
2997                synchronized (mInstallLock) {
2998                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2999                    if (retCode < 0) {
3000                        Slog.w(TAG, "Couldn't clear application caches");
3001                    }
3002                }
3003                if(pi != null) {
3004                    try {
3005                        // Callback via pending intent
3006                        int code = (retCode >= 0) ? 1 : 0;
3007                        pi.sendIntent(null, code, null,
3008                                null, null);
3009                    } catch (SendIntentException e1) {
3010                        Slog.i(TAG, "Failed to send pending intent");
3011                    }
3012                }
3013            }
3014        });
3015    }
3016
3017    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3018        synchronized (mInstallLock) {
3019            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3020                throw new IOException("Failed to free enough space");
3021            }
3022        }
3023    }
3024
3025    @Override
3026    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3027        if (!sUserManager.exists(userId)) return null;
3028        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3029        synchronized (mPackages) {
3030            PackageParser.Activity a = mActivities.mActivities.get(component);
3031
3032            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3033            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3034                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3035                if (ps == null) return null;
3036                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3037                        userId);
3038            }
3039            if (mResolveComponentName.equals(component)) {
3040                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3041                        new PackageUserState(), userId);
3042            }
3043        }
3044        return null;
3045    }
3046
3047    @Override
3048    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3049            String resolvedType) {
3050        synchronized (mPackages) {
3051            if (component.equals(mResolveComponentName)) {
3052                // The resolver supports EVERYTHING!
3053                return true;
3054            }
3055            PackageParser.Activity a = mActivities.mActivities.get(component);
3056            if (a == null) {
3057                return false;
3058            }
3059            for (int i=0; i<a.intents.size(); i++) {
3060                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3061                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3062                    return true;
3063                }
3064            }
3065            return false;
3066        }
3067    }
3068
3069    @Override
3070    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3071        if (!sUserManager.exists(userId)) return null;
3072        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3073        synchronized (mPackages) {
3074            PackageParser.Activity a = mReceivers.mActivities.get(component);
3075            if (DEBUG_PACKAGE_INFO) Log.v(
3076                TAG, "getReceiverInfo " + component + ": " + a);
3077            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3078                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3079                if (ps == null) return null;
3080                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3081                        userId);
3082            }
3083        }
3084        return null;
3085    }
3086
3087    @Override
3088    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3089        if (!sUserManager.exists(userId)) return null;
3090        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3091        synchronized (mPackages) {
3092            PackageParser.Service s = mServices.mServices.get(component);
3093            if (DEBUG_PACKAGE_INFO) Log.v(
3094                TAG, "getServiceInfo " + component + ": " + s);
3095            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3096                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3097                if (ps == null) return null;
3098                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3099                        userId);
3100            }
3101        }
3102        return null;
3103    }
3104
3105    @Override
3106    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3107        if (!sUserManager.exists(userId)) return null;
3108        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3109        synchronized (mPackages) {
3110            PackageParser.Provider p = mProviders.mProviders.get(component);
3111            if (DEBUG_PACKAGE_INFO) Log.v(
3112                TAG, "getProviderInfo " + component + ": " + p);
3113            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3114                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3115                if (ps == null) return null;
3116                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3117                        userId);
3118            }
3119        }
3120        return null;
3121    }
3122
3123    @Override
3124    public String[] getSystemSharedLibraryNames() {
3125        Set<String> libSet;
3126        synchronized (mPackages) {
3127            libSet = mSharedLibraries.keySet();
3128            int size = libSet.size();
3129            if (size > 0) {
3130                String[] libs = new String[size];
3131                libSet.toArray(libs);
3132                return libs;
3133            }
3134        }
3135        return null;
3136    }
3137
3138    /**
3139     * @hide
3140     */
3141    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3142        synchronized (mPackages) {
3143            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3144            if (lib != null && lib.apk != null) {
3145                return mPackages.get(lib.apk);
3146            }
3147        }
3148        return null;
3149    }
3150
3151    @Override
3152    public FeatureInfo[] getSystemAvailableFeatures() {
3153        Collection<FeatureInfo> featSet;
3154        synchronized (mPackages) {
3155            featSet = mAvailableFeatures.values();
3156            int size = featSet.size();
3157            if (size > 0) {
3158                FeatureInfo[] features = new FeatureInfo[size+1];
3159                featSet.toArray(features);
3160                FeatureInfo fi = new FeatureInfo();
3161                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3162                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3163                features[size] = fi;
3164                return features;
3165            }
3166        }
3167        return null;
3168    }
3169
3170    @Override
3171    public boolean hasSystemFeature(String name) {
3172        synchronized (mPackages) {
3173            return mAvailableFeatures.containsKey(name);
3174        }
3175    }
3176
3177    private void checkValidCaller(int uid, int userId) {
3178        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3179            return;
3180
3181        throw new SecurityException("Caller uid=" + uid
3182                + " is not privileged to communicate with user=" + userId);
3183    }
3184
3185    @Override
3186    public int checkPermission(String permName, String pkgName, int userId) {
3187        if (!sUserManager.exists(userId)) {
3188            return PackageManager.PERMISSION_DENIED;
3189        }
3190
3191        synchronized (mPackages) {
3192            final PackageParser.Package p = mPackages.get(pkgName);
3193            if (p != null && p.mExtras != null) {
3194                final PackageSetting ps = (PackageSetting) p.mExtras;
3195                final PermissionsState permissionsState = ps.getPermissionsState();
3196                if (permissionsState.hasPermission(permName, userId)) {
3197                    return PackageManager.PERMISSION_GRANTED;
3198                }
3199                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3200                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3201                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3202                    return PackageManager.PERMISSION_GRANTED;
3203                }
3204            }
3205        }
3206
3207        return PackageManager.PERMISSION_DENIED;
3208    }
3209
3210    @Override
3211    public int checkUidPermission(String permName, int uid) {
3212        final int userId = UserHandle.getUserId(uid);
3213
3214        if (!sUserManager.exists(userId)) {
3215            return PackageManager.PERMISSION_DENIED;
3216        }
3217
3218        synchronized (mPackages) {
3219            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3220            if (obj != null) {
3221                final SettingBase ps = (SettingBase) obj;
3222                final PermissionsState permissionsState = ps.getPermissionsState();
3223                if (permissionsState.hasPermission(permName, userId)) {
3224                    return PackageManager.PERMISSION_GRANTED;
3225                }
3226                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3227                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3228                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3229                    return PackageManager.PERMISSION_GRANTED;
3230                }
3231            } else {
3232                ArraySet<String> perms = mSystemPermissions.get(uid);
3233                if (perms != null) {
3234                    if (perms.contains(permName)) {
3235                        return PackageManager.PERMISSION_GRANTED;
3236                    }
3237                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3238                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3239                        return PackageManager.PERMISSION_GRANTED;
3240                    }
3241                }
3242            }
3243        }
3244
3245        return PackageManager.PERMISSION_DENIED;
3246    }
3247
3248    @Override
3249    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3250        if (UserHandle.getCallingUserId() != userId) {
3251            mContext.enforceCallingPermission(
3252                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3253                    "isPermissionRevokedByPolicy for user " + userId);
3254        }
3255
3256        if (checkPermission(permission, packageName, userId)
3257                == PackageManager.PERMISSION_GRANTED) {
3258            return false;
3259        }
3260
3261        final long identity = Binder.clearCallingIdentity();
3262        try {
3263            final int flags = getPermissionFlags(permission, packageName, userId);
3264            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3265        } finally {
3266            Binder.restoreCallingIdentity(identity);
3267        }
3268    }
3269
3270    @Override
3271    public String getPermissionControllerPackageName() {
3272        synchronized (mPackages) {
3273            return mRequiredInstallerPackage;
3274        }
3275    }
3276
3277    /**
3278     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3279     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3280     * @param checkShell TODO(yamasani):
3281     * @param message the message to log on security exception
3282     */
3283    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3284            boolean checkShell, String message) {
3285        if (userId < 0) {
3286            throw new IllegalArgumentException("Invalid userId " + userId);
3287        }
3288        if (checkShell) {
3289            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3290        }
3291        if (userId == UserHandle.getUserId(callingUid)) return;
3292        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3293            if (requireFullPermission) {
3294                mContext.enforceCallingOrSelfPermission(
3295                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3296            } else {
3297                try {
3298                    mContext.enforceCallingOrSelfPermission(
3299                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3300                } catch (SecurityException se) {
3301                    mContext.enforceCallingOrSelfPermission(
3302                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3303                }
3304            }
3305        }
3306    }
3307
3308    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3309        if (callingUid == Process.SHELL_UID) {
3310            if (userHandle >= 0
3311                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3312                throw new SecurityException("Shell does not have permission to access user "
3313                        + userHandle);
3314            } else if (userHandle < 0) {
3315                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3316                        + Debug.getCallers(3));
3317            }
3318        }
3319    }
3320
3321    private BasePermission findPermissionTreeLP(String permName) {
3322        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3323            if (permName.startsWith(bp.name) &&
3324                    permName.length() > bp.name.length() &&
3325                    permName.charAt(bp.name.length()) == '.') {
3326                return bp;
3327            }
3328        }
3329        return null;
3330    }
3331
3332    private BasePermission checkPermissionTreeLP(String permName) {
3333        if (permName != null) {
3334            BasePermission bp = findPermissionTreeLP(permName);
3335            if (bp != null) {
3336                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3337                    return bp;
3338                }
3339                throw new SecurityException("Calling uid "
3340                        + Binder.getCallingUid()
3341                        + " is not allowed to add to permission tree "
3342                        + bp.name + " owned by uid " + bp.uid);
3343            }
3344        }
3345        throw new SecurityException("No permission tree found for " + permName);
3346    }
3347
3348    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3349        if (s1 == null) {
3350            return s2 == null;
3351        }
3352        if (s2 == null) {
3353            return false;
3354        }
3355        if (s1.getClass() != s2.getClass()) {
3356            return false;
3357        }
3358        return s1.equals(s2);
3359    }
3360
3361    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3362        if (pi1.icon != pi2.icon) return false;
3363        if (pi1.logo != pi2.logo) return false;
3364        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3365        if (!compareStrings(pi1.name, pi2.name)) return false;
3366        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3367        // We'll take care of setting this one.
3368        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3369        // These are not currently stored in settings.
3370        //if (!compareStrings(pi1.group, pi2.group)) return false;
3371        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3372        //if (pi1.labelRes != pi2.labelRes) return false;
3373        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3374        return true;
3375    }
3376
3377    int permissionInfoFootprint(PermissionInfo info) {
3378        int size = info.name.length();
3379        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3380        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3381        return size;
3382    }
3383
3384    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3385        int size = 0;
3386        for (BasePermission perm : mSettings.mPermissions.values()) {
3387            if (perm.uid == tree.uid) {
3388                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3389            }
3390        }
3391        return size;
3392    }
3393
3394    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3395        // We calculate the max size of permissions defined by this uid and throw
3396        // if that plus the size of 'info' would exceed our stated maximum.
3397        if (tree.uid != Process.SYSTEM_UID) {
3398            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3399            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3400                throw new SecurityException("Permission tree size cap exceeded");
3401            }
3402        }
3403    }
3404
3405    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3406        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3407            throw new SecurityException("Label must be specified in permission");
3408        }
3409        BasePermission tree = checkPermissionTreeLP(info.name);
3410        BasePermission bp = mSettings.mPermissions.get(info.name);
3411        boolean added = bp == null;
3412        boolean changed = true;
3413        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3414        if (added) {
3415            enforcePermissionCapLocked(info, tree);
3416            bp = new BasePermission(info.name, tree.sourcePackage,
3417                    BasePermission.TYPE_DYNAMIC);
3418        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3419            throw new SecurityException(
3420                    "Not allowed to modify non-dynamic permission "
3421                    + info.name);
3422        } else {
3423            if (bp.protectionLevel == fixedLevel
3424                    && bp.perm.owner.equals(tree.perm.owner)
3425                    && bp.uid == tree.uid
3426                    && comparePermissionInfos(bp.perm.info, info)) {
3427                changed = false;
3428            }
3429        }
3430        bp.protectionLevel = fixedLevel;
3431        info = new PermissionInfo(info);
3432        info.protectionLevel = fixedLevel;
3433        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3434        bp.perm.info.packageName = tree.perm.info.packageName;
3435        bp.uid = tree.uid;
3436        if (added) {
3437            mSettings.mPermissions.put(info.name, bp);
3438        }
3439        if (changed) {
3440            if (!async) {
3441                mSettings.writeLPr();
3442            } else {
3443                scheduleWriteSettingsLocked();
3444            }
3445        }
3446        return added;
3447    }
3448
3449    @Override
3450    public boolean addPermission(PermissionInfo info) {
3451        synchronized (mPackages) {
3452            return addPermissionLocked(info, false);
3453        }
3454    }
3455
3456    @Override
3457    public boolean addPermissionAsync(PermissionInfo info) {
3458        synchronized (mPackages) {
3459            return addPermissionLocked(info, true);
3460        }
3461    }
3462
3463    @Override
3464    public void removePermission(String name) {
3465        synchronized (mPackages) {
3466            checkPermissionTreeLP(name);
3467            BasePermission bp = mSettings.mPermissions.get(name);
3468            if (bp != null) {
3469                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3470                    throw new SecurityException(
3471                            "Not allowed to modify non-dynamic permission "
3472                            + name);
3473                }
3474                mSettings.mPermissions.remove(name);
3475                mSettings.writeLPr();
3476            }
3477        }
3478    }
3479
3480    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3481            BasePermission bp) {
3482        int index = pkg.requestedPermissions.indexOf(bp.name);
3483        if (index == -1) {
3484            throw new SecurityException("Package " + pkg.packageName
3485                    + " has not requested permission " + bp.name);
3486        }
3487        if (!bp.isRuntime() && !bp.isDevelopment()) {
3488            throw new SecurityException("Permission " + bp.name
3489                    + " is not a changeable permission type");
3490        }
3491    }
3492
3493    @Override
3494    public void grantRuntimePermission(String packageName, String name, final int userId) {
3495        if (!sUserManager.exists(userId)) {
3496            Log.e(TAG, "No such user:" + userId);
3497            return;
3498        }
3499
3500        mContext.enforceCallingOrSelfPermission(
3501                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3502                "grantRuntimePermission");
3503
3504        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3505                "grantRuntimePermission");
3506
3507        final int uid;
3508        final SettingBase sb;
3509
3510        synchronized (mPackages) {
3511            final PackageParser.Package pkg = mPackages.get(packageName);
3512            if (pkg == null) {
3513                throw new IllegalArgumentException("Unknown package: " + packageName);
3514            }
3515
3516            final BasePermission bp = mSettings.mPermissions.get(name);
3517            if (bp == null) {
3518                throw new IllegalArgumentException("Unknown permission: " + name);
3519            }
3520
3521            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3522
3523            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3524            sb = (SettingBase) pkg.mExtras;
3525            if (sb == null) {
3526                throw new IllegalArgumentException("Unknown package: " + packageName);
3527            }
3528
3529            final PermissionsState permissionsState = sb.getPermissionsState();
3530
3531            final int flags = permissionsState.getPermissionFlags(name, userId);
3532            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3533                throw new SecurityException("Cannot grant system fixed permission: "
3534                        + name + " for package: " + packageName);
3535            }
3536
3537            if (bp.isDevelopment()) {
3538                // Development permissions must be handled specially, since they are not
3539                // normal runtime permissions.  For now they apply to all users.
3540                if (permissionsState.grantInstallPermission(bp) !=
3541                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3542                    scheduleWriteSettingsLocked();
3543                }
3544                return;
3545            }
3546
3547            final int result = permissionsState.grantRuntimePermission(bp, userId);
3548            switch (result) {
3549                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3550                    return;
3551                }
3552
3553                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3554                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3555                    mHandler.post(new Runnable() {
3556                        @Override
3557                        public void run() {
3558                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3559                        }
3560                    });
3561                } break;
3562            }
3563
3564            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3565
3566            // Not critical if that is lost - app has to request again.
3567            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3568        }
3569
3570        // Only need to do this if user is initialized. Otherwise it's a new user
3571        // and there are no processes running as the user yet and there's no need
3572        // to make an expensive call to remount processes for the changed permissions.
3573        if (READ_EXTERNAL_STORAGE.equals(name)
3574                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3575            final long token = Binder.clearCallingIdentity();
3576            try {
3577                if (sUserManager.isInitialized(userId)) {
3578                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3579                            MountServiceInternal.class);
3580                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3581                }
3582            } finally {
3583                Binder.restoreCallingIdentity(token);
3584            }
3585        }
3586    }
3587
3588    @Override
3589    public void revokeRuntimePermission(String packageName, String name, int userId) {
3590        if (!sUserManager.exists(userId)) {
3591            Log.e(TAG, "No such user:" + userId);
3592            return;
3593        }
3594
3595        mContext.enforceCallingOrSelfPermission(
3596                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3597                "revokeRuntimePermission");
3598
3599        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3600                "revokeRuntimePermission");
3601
3602        final int appId;
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            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3616
3617            SettingBase sb = (SettingBase) pkg.mExtras;
3618            if (sb == null) {
3619                throw new IllegalArgumentException("Unknown package: " + packageName);
3620            }
3621
3622            final PermissionsState permissionsState = sb.getPermissionsState();
3623
3624            final int flags = permissionsState.getPermissionFlags(name, userId);
3625            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3626                throw new SecurityException("Cannot revoke system fixed permission: "
3627                        + name + " for package: " + packageName);
3628            }
3629
3630            if (bp.isDevelopment()) {
3631                // Development permissions must be handled specially, since they are not
3632                // normal runtime permissions.  For now they apply to all users.
3633                if (permissionsState.revokeInstallPermission(bp) !=
3634                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3635                    scheduleWriteSettingsLocked();
3636                }
3637                return;
3638            }
3639
3640            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3641                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3642                return;
3643            }
3644
3645            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3646
3647            // Critical, after this call app should never have the permission.
3648            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3649
3650            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3651        }
3652
3653        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3654    }
3655
3656    @Override
3657    public void resetRuntimePermissions() {
3658        mContext.enforceCallingOrSelfPermission(
3659                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3660                "revokeRuntimePermission");
3661
3662        int callingUid = Binder.getCallingUid();
3663        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3664            mContext.enforceCallingOrSelfPermission(
3665                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3666                    "resetRuntimePermissions");
3667        }
3668
3669        synchronized (mPackages) {
3670            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3671            for (int userId : UserManagerService.getInstance().getUserIds()) {
3672                final int packageCount = mPackages.size();
3673                for (int i = 0; i < packageCount; i++) {
3674                    PackageParser.Package pkg = mPackages.valueAt(i);
3675                    if (!(pkg.mExtras instanceof PackageSetting)) {
3676                        continue;
3677                    }
3678                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3679                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3680                }
3681            }
3682        }
3683    }
3684
3685    @Override
3686    public int getPermissionFlags(String name, String packageName, int userId) {
3687        if (!sUserManager.exists(userId)) {
3688            return 0;
3689        }
3690
3691        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3692
3693        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3694                "getPermissionFlags");
3695
3696        synchronized (mPackages) {
3697            final PackageParser.Package pkg = mPackages.get(packageName);
3698            if (pkg == null) {
3699                throw new IllegalArgumentException("Unknown package: " + packageName);
3700            }
3701
3702            final BasePermission bp = mSettings.mPermissions.get(name);
3703            if (bp == null) {
3704                throw new IllegalArgumentException("Unknown permission: " + name);
3705            }
3706
3707            SettingBase sb = (SettingBase) pkg.mExtras;
3708            if (sb == null) {
3709                throw new IllegalArgumentException("Unknown package: " + packageName);
3710            }
3711
3712            PermissionsState permissionsState = sb.getPermissionsState();
3713            return permissionsState.getPermissionFlags(name, userId);
3714        }
3715    }
3716
3717    @Override
3718    public void updatePermissionFlags(String name, String packageName, int flagMask,
3719            int flagValues, int userId) {
3720        if (!sUserManager.exists(userId)) {
3721            return;
3722        }
3723
3724        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3725
3726        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3727                "updatePermissionFlags");
3728
3729        // Only the system can change these flags and nothing else.
3730        if (getCallingUid() != Process.SYSTEM_UID) {
3731            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3732            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3733            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3734            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3735        }
3736
3737        synchronized (mPackages) {
3738            final PackageParser.Package pkg = mPackages.get(packageName);
3739            if (pkg == null) {
3740                throw new IllegalArgumentException("Unknown package: " + packageName);
3741            }
3742
3743            final BasePermission bp = mSettings.mPermissions.get(name);
3744            if (bp == null) {
3745                throw new IllegalArgumentException("Unknown permission: " + name);
3746            }
3747
3748            SettingBase sb = (SettingBase) pkg.mExtras;
3749            if (sb == null) {
3750                throw new IllegalArgumentException("Unknown package: " + packageName);
3751            }
3752
3753            PermissionsState permissionsState = sb.getPermissionsState();
3754
3755            // Only the package manager can change flags for system component permissions.
3756            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3757            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3758                return;
3759            }
3760
3761            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3762
3763            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3764                // Install and runtime permissions are stored in different places,
3765                // so figure out what permission changed and persist the change.
3766                if (permissionsState.getInstallPermissionState(name) != null) {
3767                    scheduleWriteSettingsLocked();
3768                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3769                        || hadState) {
3770                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3771                }
3772            }
3773        }
3774    }
3775
3776    /**
3777     * Update the permission flags for all packages and runtime permissions of a user in order
3778     * to allow device or profile owner to remove POLICY_FIXED.
3779     */
3780    @Override
3781    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3782        if (!sUserManager.exists(userId)) {
3783            return;
3784        }
3785
3786        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3787
3788        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3789                "updatePermissionFlagsForAllApps");
3790
3791        // Only the system can change system fixed flags.
3792        if (getCallingUid() != Process.SYSTEM_UID) {
3793            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3794            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3795        }
3796
3797        synchronized (mPackages) {
3798            boolean changed = false;
3799            final int packageCount = mPackages.size();
3800            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3801                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3802                SettingBase sb = (SettingBase) pkg.mExtras;
3803                if (sb == null) {
3804                    continue;
3805                }
3806                PermissionsState permissionsState = sb.getPermissionsState();
3807                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3808                        userId, flagMask, flagValues);
3809            }
3810            if (changed) {
3811                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3812            }
3813        }
3814    }
3815
3816    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3817        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3818                != PackageManager.PERMISSION_GRANTED
3819            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3820                != PackageManager.PERMISSION_GRANTED) {
3821            throw new SecurityException(message + " requires "
3822                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3823                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3824        }
3825    }
3826
3827    @Override
3828    public boolean shouldShowRequestPermissionRationale(String permissionName,
3829            String packageName, int userId) {
3830        if (UserHandle.getCallingUserId() != userId) {
3831            mContext.enforceCallingPermission(
3832                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3833                    "canShowRequestPermissionRationale for user " + userId);
3834        }
3835
3836        final int uid = getPackageUid(packageName, userId);
3837        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3838            return false;
3839        }
3840
3841        if (checkPermission(permissionName, packageName, userId)
3842                == PackageManager.PERMISSION_GRANTED) {
3843            return false;
3844        }
3845
3846        final int flags;
3847
3848        final long identity = Binder.clearCallingIdentity();
3849        try {
3850            flags = getPermissionFlags(permissionName,
3851                    packageName, userId);
3852        } finally {
3853            Binder.restoreCallingIdentity(identity);
3854        }
3855
3856        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3857                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3858                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3859
3860        if ((flags & fixedFlags) != 0) {
3861            return false;
3862        }
3863
3864        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3865    }
3866
3867    @Override
3868    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3869        mContext.enforceCallingOrSelfPermission(
3870                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3871                "addOnPermissionsChangeListener");
3872
3873        synchronized (mPackages) {
3874            mOnPermissionChangeListeners.addListenerLocked(listener);
3875        }
3876    }
3877
3878    @Override
3879    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3880        synchronized (mPackages) {
3881            mOnPermissionChangeListeners.removeListenerLocked(listener);
3882        }
3883    }
3884
3885    @Override
3886    public boolean isProtectedBroadcast(String actionName) {
3887        synchronized (mPackages) {
3888            return mProtectedBroadcasts.contains(actionName);
3889        }
3890    }
3891
3892    @Override
3893    public int checkSignatures(String pkg1, String pkg2) {
3894        synchronized (mPackages) {
3895            final PackageParser.Package p1 = mPackages.get(pkg1);
3896            final PackageParser.Package p2 = mPackages.get(pkg2);
3897            if (p1 == null || p1.mExtras == null
3898                    || p2 == null || p2.mExtras == null) {
3899                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3900            }
3901            return compareSignatures(p1.mSignatures, p2.mSignatures);
3902        }
3903    }
3904
3905    @Override
3906    public int checkUidSignatures(int uid1, int uid2) {
3907        // Map to base uids.
3908        uid1 = UserHandle.getAppId(uid1);
3909        uid2 = UserHandle.getAppId(uid2);
3910        // reader
3911        synchronized (mPackages) {
3912            Signature[] s1;
3913            Signature[] s2;
3914            Object obj = mSettings.getUserIdLPr(uid1);
3915            if (obj != null) {
3916                if (obj instanceof SharedUserSetting) {
3917                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3918                } else if (obj instanceof PackageSetting) {
3919                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3920                } else {
3921                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3922                }
3923            } else {
3924                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3925            }
3926            obj = mSettings.getUserIdLPr(uid2);
3927            if (obj != null) {
3928                if (obj instanceof SharedUserSetting) {
3929                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3930                } else if (obj instanceof PackageSetting) {
3931                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3932                } else {
3933                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3934                }
3935            } else {
3936                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3937            }
3938            return compareSignatures(s1, s2);
3939        }
3940    }
3941
3942    private void killUid(int appId, int userId, String reason) {
3943        final long identity = Binder.clearCallingIdentity();
3944        try {
3945            IActivityManager am = ActivityManagerNative.getDefault();
3946            if (am != null) {
3947                try {
3948                    am.killUid(appId, userId, reason);
3949                } catch (RemoteException e) {
3950                    /* ignore - same process */
3951                }
3952            }
3953        } finally {
3954            Binder.restoreCallingIdentity(identity);
3955        }
3956    }
3957
3958    /**
3959     * Compares two sets of signatures. Returns:
3960     * <br />
3961     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3962     * <br />
3963     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3964     * <br />
3965     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3966     * <br />
3967     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3968     * <br />
3969     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3970     */
3971    static int compareSignatures(Signature[] s1, Signature[] s2) {
3972        if (s1 == null) {
3973            return s2 == null
3974                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3975                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3976        }
3977
3978        if (s2 == null) {
3979            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3980        }
3981
3982        if (s1.length != s2.length) {
3983            return PackageManager.SIGNATURE_NO_MATCH;
3984        }
3985
3986        // Since both signature sets are of size 1, we can compare without HashSets.
3987        if (s1.length == 1) {
3988            return s1[0].equals(s2[0]) ?
3989                    PackageManager.SIGNATURE_MATCH :
3990                    PackageManager.SIGNATURE_NO_MATCH;
3991        }
3992
3993        ArraySet<Signature> set1 = new ArraySet<Signature>();
3994        for (Signature sig : s1) {
3995            set1.add(sig);
3996        }
3997        ArraySet<Signature> set2 = new ArraySet<Signature>();
3998        for (Signature sig : s2) {
3999            set2.add(sig);
4000        }
4001        // Make sure s2 contains all signatures in s1.
4002        if (set1.equals(set2)) {
4003            return PackageManager.SIGNATURE_MATCH;
4004        }
4005        return PackageManager.SIGNATURE_NO_MATCH;
4006    }
4007
4008    /**
4009     * If the database version for this type of package (internal storage or
4010     * external storage) is less than the version where package signatures
4011     * were updated, return true.
4012     */
4013    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4014        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4015        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4016    }
4017
4018    /**
4019     * Used for backward compatibility to make sure any packages with
4020     * certificate chains get upgraded to the new style. {@code existingSigs}
4021     * will be in the old format (since they were stored on disk from before the
4022     * system upgrade) and {@code scannedSigs} will be in the newer format.
4023     */
4024    private int compareSignaturesCompat(PackageSignatures existingSigs,
4025            PackageParser.Package scannedPkg) {
4026        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4027            return PackageManager.SIGNATURE_NO_MATCH;
4028        }
4029
4030        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4031        for (Signature sig : existingSigs.mSignatures) {
4032            existingSet.add(sig);
4033        }
4034        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4035        for (Signature sig : scannedPkg.mSignatures) {
4036            try {
4037                Signature[] chainSignatures = sig.getChainSignatures();
4038                for (Signature chainSig : chainSignatures) {
4039                    scannedCompatSet.add(chainSig);
4040                }
4041            } catch (CertificateEncodingException e) {
4042                scannedCompatSet.add(sig);
4043            }
4044        }
4045        /*
4046         * Make sure the expanded scanned set contains all signatures in the
4047         * existing one.
4048         */
4049        if (scannedCompatSet.equals(existingSet)) {
4050            // Migrate the old signatures to the new scheme.
4051            existingSigs.assignSignatures(scannedPkg.mSignatures);
4052            // The new KeySets will be re-added later in the scanning process.
4053            synchronized (mPackages) {
4054                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4055            }
4056            return PackageManager.SIGNATURE_MATCH;
4057        }
4058        return PackageManager.SIGNATURE_NO_MATCH;
4059    }
4060
4061    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4062        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4063        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4064    }
4065
4066    private int compareSignaturesRecover(PackageSignatures existingSigs,
4067            PackageParser.Package scannedPkg) {
4068        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4069            return PackageManager.SIGNATURE_NO_MATCH;
4070        }
4071
4072        String msg = null;
4073        try {
4074            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4075                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4076                        + scannedPkg.packageName);
4077                return PackageManager.SIGNATURE_MATCH;
4078            }
4079        } catch (CertificateException e) {
4080            msg = e.getMessage();
4081        }
4082
4083        logCriticalInfo(Log.INFO,
4084                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4085        return PackageManager.SIGNATURE_NO_MATCH;
4086    }
4087
4088    @Override
4089    public String[] getPackagesForUid(int uid) {
4090        uid = UserHandle.getAppId(uid);
4091        // reader
4092        synchronized (mPackages) {
4093            Object obj = mSettings.getUserIdLPr(uid);
4094            if (obj instanceof SharedUserSetting) {
4095                final SharedUserSetting sus = (SharedUserSetting) obj;
4096                final int N = sus.packages.size();
4097                final String[] res = new String[N];
4098                final Iterator<PackageSetting> it = sus.packages.iterator();
4099                int i = 0;
4100                while (it.hasNext()) {
4101                    res[i++] = it.next().name;
4102                }
4103                return res;
4104            } else if (obj instanceof PackageSetting) {
4105                final PackageSetting ps = (PackageSetting) obj;
4106                return new String[] { ps.name };
4107            }
4108        }
4109        return null;
4110    }
4111
4112    @Override
4113    public String getNameForUid(int uid) {
4114        // reader
4115        synchronized (mPackages) {
4116            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4117            if (obj instanceof SharedUserSetting) {
4118                final SharedUserSetting sus = (SharedUserSetting) obj;
4119                return sus.name + ":" + sus.userId;
4120            } else if (obj instanceof PackageSetting) {
4121                final PackageSetting ps = (PackageSetting) obj;
4122                return ps.name;
4123            }
4124        }
4125        return null;
4126    }
4127
4128    @Override
4129    public int getUidForSharedUser(String sharedUserName) {
4130        if(sharedUserName == null) {
4131            return -1;
4132        }
4133        // reader
4134        synchronized (mPackages) {
4135            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4136            if (suid == null) {
4137                return -1;
4138            }
4139            return suid.userId;
4140        }
4141    }
4142
4143    @Override
4144    public int getFlagsForUid(int uid) {
4145        synchronized (mPackages) {
4146            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4147            if (obj instanceof SharedUserSetting) {
4148                final SharedUserSetting sus = (SharedUserSetting) obj;
4149                return sus.pkgFlags;
4150            } else if (obj instanceof PackageSetting) {
4151                final PackageSetting ps = (PackageSetting) obj;
4152                return ps.pkgFlags;
4153            }
4154        }
4155        return 0;
4156    }
4157
4158    @Override
4159    public int getPrivateFlagsForUid(int uid) {
4160        synchronized (mPackages) {
4161            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4162            if (obj instanceof SharedUserSetting) {
4163                final SharedUserSetting sus = (SharedUserSetting) obj;
4164                return sus.pkgPrivateFlags;
4165            } else if (obj instanceof PackageSetting) {
4166                final PackageSetting ps = (PackageSetting) obj;
4167                return ps.pkgPrivateFlags;
4168            }
4169        }
4170        return 0;
4171    }
4172
4173    @Override
4174    public boolean isUidPrivileged(int uid) {
4175        uid = UserHandle.getAppId(uid);
4176        // reader
4177        synchronized (mPackages) {
4178            Object obj = mSettings.getUserIdLPr(uid);
4179            if (obj instanceof SharedUserSetting) {
4180                final SharedUserSetting sus = (SharedUserSetting) obj;
4181                final Iterator<PackageSetting> it = sus.packages.iterator();
4182                while (it.hasNext()) {
4183                    if (it.next().isPrivileged()) {
4184                        return true;
4185                    }
4186                }
4187            } else if (obj instanceof PackageSetting) {
4188                final PackageSetting ps = (PackageSetting) obj;
4189                return ps.isPrivileged();
4190            }
4191        }
4192        return false;
4193    }
4194
4195    @Override
4196    public String[] getAppOpPermissionPackages(String permissionName) {
4197        synchronized (mPackages) {
4198            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4199            if (pkgs == null) {
4200                return null;
4201            }
4202            return pkgs.toArray(new String[pkgs.size()]);
4203        }
4204    }
4205
4206    @Override
4207    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4208            int flags, int userId) {
4209        if (!sUserManager.exists(userId)) return null;
4210        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4211        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4212        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4213    }
4214
4215    @Override
4216    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4217            IntentFilter filter, int match, ComponentName activity) {
4218        final int userId = UserHandle.getCallingUserId();
4219        if (DEBUG_PREFERRED) {
4220            Log.v(TAG, "setLastChosenActivity intent=" + intent
4221                + " resolvedType=" + resolvedType
4222                + " flags=" + flags
4223                + " filter=" + filter
4224                + " match=" + match
4225                + " activity=" + activity);
4226            filter.dump(new PrintStreamPrinter(System.out), "    ");
4227        }
4228        intent.setComponent(null);
4229        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4230        // Find any earlier preferred or last chosen entries and nuke them
4231        findPreferredActivity(intent, resolvedType,
4232                flags, query, 0, false, true, false, userId);
4233        // Add the new activity as the last chosen for this filter
4234        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4235                "Setting last chosen");
4236    }
4237
4238    @Override
4239    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4240        final int userId = UserHandle.getCallingUserId();
4241        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4242        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4243        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4244                false, false, false, userId);
4245    }
4246
4247    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4248            int flags, List<ResolveInfo> query, int userId) {
4249        if (query != null) {
4250            final int N = query.size();
4251            if (N == 1) {
4252                return query.get(0);
4253            } else if (N > 1) {
4254                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4255                // If there is more than one activity with the same priority,
4256                // then let the user decide between them.
4257                ResolveInfo r0 = query.get(0);
4258                ResolveInfo r1 = query.get(1);
4259                if (DEBUG_INTENT_MATCHING || debug) {
4260                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4261                            + r1.activityInfo.name + "=" + r1.priority);
4262                }
4263                // If the first activity has a higher priority, or a different
4264                // default, then it is always desireable to pick it.
4265                if (r0.priority != r1.priority
4266                        || r0.preferredOrder != r1.preferredOrder
4267                        || r0.isDefault != r1.isDefault) {
4268                    return query.get(0);
4269                }
4270                // If we have saved a preference for a preferred activity for
4271                // this Intent, use that.
4272                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4273                        flags, query, r0.priority, true, false, debug, userId);
4274                if (ri != null) {
4275                    return ri;
4276                }
4277                ri = new ResolveInfo(mResolveInfo);
4278                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4279                ri.activityInfo.applicationInfo = new ApplicationInfo(
4280                        ri.activityInfo.applicationInfo);
4281                if (userId != 0) {
4282                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4283                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4284                }
4285                // Make sure that the resolver is displayable in car mode
4286                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4287                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4288                return ri;
4289            }
4290        }
4291        return null;
4292    }
4293
4294    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4295            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4296        final int N = query.size();
4297        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4298                .get(userId);
4299        // Get the list of persistent preferred activities that handle the intent
4300        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4301        List<PersistentPreferredActivity> pprefs = ppir != null
4302                ? ppir.queryIntent(intent, resolvedType,
4303                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4304                : null;
4305        if (pprefs != null && pprefs.size() > 0) {
4306            final int M = pprefs.size();
4307            for (int i=0; i<M; i++) {
4308                final PersistentPreferredActivity ppa = pprefs.get(i);
4309                if (DEBUG_PREFERRED || debug) {
4310                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4311                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4312                            + "\n  component=" + ppa.mComponent);
4313                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4314                }
4315                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4316                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4317                if (DEBUG_PREFERRED || debug) {
4318                    Slog.v(TAG, "Found persistent preferred activity:");
4319                    if (ai != null) {
4320                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4321                    } else {
4322                        Slog.v(TAG, "  null");
4323                    }
4324                }
4325                if (ai == null) {
4326                    // This previously registered persistent preferred activity
4327                    // component is no longer known. Ignore it and do NOT remove it.
4328                    continue;
4329                }
4330                for (int j=0; j<N; j++) {
4331                    final ResolveInfo ri = query.get(j);
4332                    if (!ri.activityInfo.applicationInfo.packageName
4333                            .equals(ai.applicationInfo.packageName)) {
4334                        continue;
4335                    }
4336                    if (!ri.activityInfo.name.equals(ai.name)) {
4337                        continue;
4338                    }
4339                    //  Found a persistent preference that can handle the intent.
4340                    if (DEBUG_PREFERRED || debug) {
4341                        Slog.v(TAG, "Returning persistent preferred activity: " +
4342                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4343                    }
4344                    return ri;
4345                }
4346            }
4347        }
4348        return null;
4349    }
4350
4351    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4352            List<ResolveInfo> query, int priority, boolean always,
4353            boolean removeMatches, boolean debug, int userId) {
4354        if (!sUserManager.exists(userId)) return null;
4355        // writer
4356        synchronized (mPackages) {
4357            if (intent.getSelector() != null) {
4358                intent = intent.getSelector();
4359            }
4360            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4361
4362            // Try to find a matching persistent preferred activity.
4363            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4364                    debug, userId);
4365
4366            // If a persistent preferred activity matched, use it.
4367            if (pri != null) {
4368                return pri;
4369            }
4370
4371            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4372            // Get the list of preferred activities that handle the intent
4373            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4374            List<PreferredActivity> prefs = pir != null
4375                    ? pir.queryIntent(intent, resolvedType,
4376                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4377                    : null;
4378            if (prefs != null && prefs.size() > 0) {
4379                boolean changed = false;
4380                try {
4381                    // First figure out how good the original match set is.
4382                    // We will only allow preferred activities that came
4383                    // from the same match quality.
4384                    int match = 0;
4385
4386                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4387
4388                    final int N = query.size();
4389                    for (int j=0; j<N; j++) {
4390                        final ResolveInfo ri = query.get(j);
4391                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4392                                + ": 0x" + Integer.toHexString(match));
4393                        if (ri.match > match) {
4394                            match = ri.match;
4395                        }
4396                    }
4397
4398                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4399                            + Integer.toHexString(match));
4400
4401                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4402                    final int M = prefs.size();
4403                    for (int i=0; i<M; i++) {
4404                        final PreferredActivity pa = prefs.get(i);
4405                        if (DEBUG_PREFERRED || debug) {
4406                            Slog.v(TAG, "Checking PreferredActivity ds="
4407                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4408                                    + "\n  component=" + pa.mPref.mComponent);
4409                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4410                        }
4411                        if (pa.mPref.mMatch != match) {
4412                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4413                                    + Integer.toHexString(pa.mPref.mMatch));
4414                            continue;
4415                        }
4416                        // If it's not an "always" type preferred activity and that's what we're
4417                        // looking for, skip it.
4418                        if (always && !pa.mPref.mAlways) {
4419                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4420                            continue;
4421                        }
4422                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4423                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4424                        if (DEBUG_PREFERRED || debug) {
4425                            Slog.v(TAG, "Found preferred activity:");
4426                            if (ai != null) {
4427                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4428                            } else {
4429                                Slog.v(TAG, "  null");
4430                            }
4431                        }
4432                        if (ai == null) {
4433                            // This previously registered preferred activity
4434                            // component is no longer known.  Most likely an update
4435                            // to the app was installed and in the new version this
4436                            // component no longer exists.  Clean it up by removing
4437                            // it from the preferred activities list, and skip it.
4438                            Slog.w(TAG, "Removing dangling preferred activity: "
4439                                    + pa.mPref.mComponent);
4440                            pir.removeFilter(pa);
4441                            changed = true;
4442                            continue;
4443                        }
4444                        for (int j=0; j<N; j++) {
4445                            final ResolveInfo ri = query.get(j);
4446                            if (!ri.activityInfo.applicationInfo.packageName
4447                                    .equals(ai.applicationInfo.packageName)) {
4448                                continue;
4449                            }
4450                            if (!ri.activityInfo.name.equals(ai.name)) {
4451                                continue;
4452                            }
4453
4454                            if (removeMatches) {
4455                                pir.removeFilter(pa);
4456                                changed = true;
4457                                if (DEBUG_PREFERRED) {
4458                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4459                                }
4460                                break;
4461                            }
4462
4463                            // Okay we found a previously set preferred or last chosen app.
4464                            // If the result set is different from when this
4465                            // was created, we need to clear it and re-ask the
4466                            // user their preference, if we're looking for an "always" type entry.
4467                            if (always && !pa.mPref.sameSet(query)) {
4468                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4469                                        + intent + " type " + resolvedType);
4470                                if (DEBUG_PREFERRED) {
4471                                    Slog.v(TAG, "Removing preferred activity since set changed "
4472                                            + pa.mPref.mComponent);
4473                                }
4474                                pir.removeFilter(pa);
4475                                // Re-add the filter as a "last chosen" entry (!always)
4476                                PreferredActivity lastChosen = new PreferredActivity(
4477                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4478                                pir.addFilter(lastChosen);
4479                                changed = true;
4480                                return null;
4481                            }
4482
4483                            // Yay! Either the set matched or we're looking for the last chosen
4484                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4485                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4486                            return ri;
4487                        }
4488                    }
4489                } finally {
4490                    if (changed) {
4491                        if (DEBUG_PREFERRED) {
4492                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4493                        }
4494                        scheduleWritePackageRestrictionsLocked(userId);
4495                    }
4496                }
4497            }
4498        }
4499        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4500        return null;
4501    }
4502
4503    /*
4504     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4505     */
4506    @Override
4507    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4508            int targetUserId) {
4509        mContext.enforceCallingOrSelfPermission(
4510                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4511        List<CrossProfileIntentFilter> matches =
4512                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4513        if (matches != null) {
4514            int size = matches.size();
4515            for (int i = 0; i < size; i++) {
4516                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4517            }
4518        }
4519        if (hasWebURI(intent)) {
4520            // cross-profile app linking works only towards the parent.
4521            final UserInfo parent = getProfileParent(sourceUserId);
4522            synchronized(mPackages) {
4523                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4524                        intent, resolvedType, 0, sourceUserId, parent.id);
4525                return xpDomainInfo != null;
4526            }
4527        }
4528        return false;
4529    }
4530
4531    private UserInfo getProfileParent(int userId) {
4532        final long identity = Binder.clearCallingIdentity();
4533        try {
4534            return sUserManager.getProfileParent(userId);
4535        } finally {
4536            Binder.restoreCallingIdentity(identity);
4537        }
4538    }
4539
4540    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4541            String resolvedType, int userId) {
4542        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4543        if (resolver != null) {
4544            return resolver.queryIntent(intent, resolvedType, false, userId);
4545        }
4546        return null;
4547    }
4548
4549    @Override
4550    public List<ResolveInfo> queryIntentActivities(Intent intent,
4551            String resolvedType, int flags, int userId) {
4552        if (!sUserManager.exists(userId)) return Collections.emptyList();
4553        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4554        ComponentName comp = intent.getComponent();
4555        if (comp == null) {
4556            if (intent.getSelector() != null) {
4557                intent = intent.getSelector();
4558                comp = intent.getComponent();
4559            }
4560        }
4561
4562        if (comp != null) {
4563            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4564            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4565            if (ai != null) {
4566                final ResolveInfo ri = new ResolveInfo();
4567                ri.activityInfo = ai;
4568                list.add(ri);
4569            }
4570            return list;
4571        }
4572
4573        // reader
4574        synchronized (mPackages) {
4575            final String pkgName = intent.getPackage();
4576            if (pkgName == null) {
4577                List<CrossProfileIntentFilter> matchingFilters =
4578                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4579                // Check for results that need to skip the current profile.
4580                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4581                        resolvedType, flags, userId);
4582                if (xpResolveInfo != null) {
4583                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4584                    result.add(xpResolveInfo);
4585                    return filterIfNotSystemUser(result, userId);
4586                }
4587
4588                // Check for results in the current profile.
4589                List<ResolveInfo> result = mActivities.queryIntent(
4590                        intent, resolvedType, flags, userId);
4591
4592                // Check for cross profile results.
4593                xpResolveInfo = queryCrossProfileIntents(
4594                        matchingFilters, intent, resolvedType, flags, userId);
4595                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4596                    result.add(xpResolveInfo);
4597                    Collections.sort(result, mResolvePrioritySorter);
4598                }
4599                result = filterIfNotSystemUser(result, userId);
4600                if (hasWebURI(intent)) {
4601                    CrossProfileDomainInfo xpDomainInfo = null;
4602                    final UserInfo parent = getProfileParent(userId);
4603                    if (parent != null) {
4604                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4605                                flags, userId, parent.id);
4606                    }
4607                    if (xpDomainInfo != null) {
4608                        if (xpResolveInfo != null) {
4609                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4610                            // in the result.
4611                            result.remove(xpResolveInfo);
4612                        }
4613                        if (result.size() == 0) {
4614                            result.add(xpDomainInfo.resolveInfo);
4615                            return result;
4616                        }
4617                    } else if (result.size() <= 1) {
4618                        return result;
4619                    }
4620                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4621                            xpDomainInfo, userId);
4622                    Collections.sort(result, mResolvePrioritySorter);
4623                }
4624                return result;
4625            }
4626            final PackageParser.Package pkg = mPackages.get(pkgName);
4627            if (pkg != null) {
4628                return filterIfNotSystemUser(
4629                        mActivities.queryIntentForPackage(
4630                                intent, resolvedType, flags, pkg.activities, userId),
4631                        userId);
4632            }
4633            return new ArrayList<ResolveInfo>();
4634        }
4635    }
4636
4637    private static class CrossProfileDomainInfo {
4638        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4639        ResolveInfo resolveInfo;
4640        /* Best domain verification status of the activities found in the other profile */
4641        int bestDomainVerificationStatus;
4642    }
4643
4644    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4645            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4646        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4647                sourceUserId)) {
4648            return null;
4649        }
4650        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4651                resolvedType, flags, parentUserId);
4652
4653        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4654            return null;
4655        }
4656        CrossProfileDomainInfo result = null;
4657        int size = resultTargetUser.size();
4658        for (int i = 0; i < size; i++) {
4659            ResolveInfo riTargetUser = resultTargetUser.get(i);
4660            // Intent filter verification is only for filters that specify a host. So don't return
4661            // those that handle all web uris.
4662            if (riTargetUser.handleAllWebDataURI) {
4663                continue;
4664            }
4665            String packageName = riTargetUser.activityInfo.packageName;
4666            PackageSetting ps = mSettings.mPackages.get(packageName);
4667            if (ps == null) {
4668                continue;
4669            }
4670            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4671            int status = (int)(verificationState >> 32);
4672            if (result == null) {
4673                result = new CrossProfileDomainInfo();
4674                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
4675                        sourceUserId, parentUserId);
4676                result.bestDomainVerificationStatus = status;
4677            } else {
4678                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4679                        result.bestDomainVerificationStatus);
4680            }
4681        }
4682        // Don't consider matches with status NEVER across profiles.
4683        if (result != null && result.bestDomainVerificationStatus
4684                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4685            return null;
4686        }
4687        return result;
4688    }
4689
4690    /**
4691     * Verification statuses are ordered from the worse to the best, except for
4692     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4693     */
4694    private int bestDomainVerificationStatus(int status1, int status2) {
4695        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4696            return status2;
4697        }
4698        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4699            return status1;
4700        }
4701        return (int) MathUtils.max(status1, status2);
4702    }
4703
4704    private boolean isUserEnabled(int userId) {
4705        long callingId = Binder.clearCallingIdentity();
4706        try {
4707            UserInfo userInfo = sUserManager.getUserInfo(userId);
4708            return userInfo != null && userInfo.isEnabled();
4709        } finally {
4710            Binder.restoreCallingIdentity(callingId);
4711        }
4712    }
4713
4714    /**
4715     * Filter out activities with systemUserOnly flag set, when current user is not System.
4716     *
4717     * @return filtered list
4718     */
4719    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
4720        if (userId == UserHandle.USER_SYSTEM) {
4721            return resolveInfos;
4722        }
4723        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4724            ResolveInfo info = resolveInfos.get(i);
4725            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
4726                resolveInfos.remove(i);
4727            }
4728        }
4729        return resolveInfos;
4730    }
4731
4732    private static boolean hasWebURI(Intent intent) {
4733        if (intent.getData() == null) {
4734            return false;
4735        }
4736        final String scheme = intent.getScheme();
4737        if (TextUtils.isEmpty(scheme)) {
4738            return false;
4739        }
4740        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4741    }
4742
4743    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4744            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4745            int userId) {
4746        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4747
4748        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4749            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4750                    candidates.size());
4751        }
4752
4753        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4754        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4755        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4756        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
4757        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4758        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4759
4760        synchronized (mPackages) {
4761            final int count = candidates.size();
4762            // First, try to use linked apps. Partition the candidates into four lists:
4763            // one for the final results, one for the "do not use ever", one for "undefined status"
4764            // and finally one for "browser app type".
4765            for (int n=0; n<count; n++) {
4766                ResolveInfo info = candidates.get(n);
4767                String packageName = info.activityInfo.packageName;
4768                PackageSetting ps = mSettings.mPackages.get(packageName);
4769                if (ps != null) {
4770                    // Add to the special match all list (Browser use case)
4771                    if (info.handleAllWebDataURI) {
4772                        matchAllList.add(info);
4773                        continue;
4774                    }
4775                    // Try to get the status from User settings first
4776                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4777                    int status = (int)(packedStatus >> 32);
4778                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4779                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4780                        if (DEBUG_DOMAIN_VERIFICATION) {
4781                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4782                                    + " : linkgen=" + linkGeneration);
4783                        }
4784                        // Use link-enabled generation as preferredOrder, i.e.
4785                        // prefer newly-enabled over earlier-enabled.
4786                        info.preferredOrder = linkGeneration;
4787                        alwaysList.add(info);
4788                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4789                        if (DEBUG_DOMAIN_VERIFICATION) {
4790                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4791                        }
4792                        neverList.add(info);
4793                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4794                        if (DEBUG_DOMAIN_VERIFICATION) {
4795                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
4796                        }
4797                        alwaysAskList.add(info);
4798                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4799                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4800                        if (DEBUG_DOMAIN_VERIFICATION) {
4801                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4802                        }
4803                        undefinedList.add(info);
4804                    }
4805                }
4806            }
4807
4808            // We'll want to include browser possibilities in a few cases
4809            boolean includeBrowser = false;
4810
4811            // First try to add the "always" resolution(s) for the current user, if any
4812            if (alwaysList.size() > 0) {
4813                result.addAll(alwaysList);
4814            // if there is an "always" for the parent user, add it.
4815            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4816                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4817                result.add(xpDomainInfo.resolveInfo);
4818            } else {
4819                // Add all undefined apps as we want them to appear in the disambiguation dialog.
4820                result.addAll(undefinedList);
4821                if (xpDomainInfo != null && (
4822                        xpDomainInfo.bestDomainVerificationStatus
4823                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4824                        || xpDomainInfo.bestDomainVerificationStatus
4825                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4826                    result.add(xpDomainInfo.resolveInfo);
4827                }
4828                includeBrowser = true;
4829            }
4830
4831            // The presence of any 'always ask' alternatives means we'll also offer browsers.
4832            // If there were 'always' entries their preferred order has been set, so we also
4833            // back that off to make the alternatives equivalent
4834            if (alwaysAskList.size() > 0) {
4835                for (ResolveInfo i : result) {
4836                    i.preferredOrder = 0;
4837                }
4838                result.addAll(alwaysAskList);
4839                includeBrowser = true;
4840            }
4841
4842            if (includeBrowser) {
4843                // Also add browsers (all of them or only the default one)
4844                if (DEBUG_DOMAIN_VERIFICATION) {
4845                    Slog.v(TAG, "   ...including browsers in candidate set");
4846                }
4847                if ((matchFlags & MATCH_ALL) != 0) {
4848                    result.addAll(matchAllList);
4849                } else {
4850                    // Browser/generic handling case.  If there's a default browser, go straight
4851                    // to that (but only if there is no other higher-priority match).
4852                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4853                    int maxMatchPrio = 0;
4854                    ResolveInfo defaultBrowserMatch = null;
4855                    final int numCandidates = matchAllList.size();
4856                    for (int n = 0; n < numCandidates; n++) {
4857                        ResolveInfo info = matchAllList.get(n);
4858                        // track the highest overall match priority...
4859                        if (info.priority > maxMatchPrio) {
4860                            maxMatchPrio = info.priority;
4861                        }
4862                        // ...and the highest-priority default browser match
4863                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4864                            if (defaultBrowserMatch == null
4865                                    || (defaultBrowserMatch.priority < info.priority)) {
4866                                if (debug) {
4867                                    Slog.v(TAG, "Considering default browser match " + info);
4868                                }
4869                                defaultBrowserMatch = info;
4870                            }
4871                        }
4872                    }
4873                    if (defaultBrowserMatch != null
4874                            && defaultBrowserMatch.priority >= maxMatchPrio
4875                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4876                    {
4877                        if (debug) {
4878                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4879                        }
4880                        result.add(defaultBrowserMatch);
4881                    } else {
4882                        result.addAll(matchAllList);
4883                    }
4884                }
4885
4886                // If there is nothing selected, add all candidates and remove the ones that the user
4887                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4888                if (result.size() == 0) {
4889                    result.addAll(candidates);
4890                    result.removeAll(neverList);
4891                }
4892            }
4893        }
4894        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4895            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4896                    result.size());
4897            for (ResolveInfo info : result) {
4898                Slog.v(TAG, "  + " + info.activityInfo);
4899            }
4900        }
4901        return result;
4902    }
4903
4904    // Returns a packed value as a long:
4905    //
4906    // high 'int'-sized word: link status: undefined/ask/never/always.
4907    // low 'int'-sized word: relative priority among 'always' results.
4908    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4909        long result = ps.getDomainVerificationStatusForUser(userId);
4910        // if none available, get the master status
4911        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4912            if (ps.getIntentFilterVerificationInfo() != null) {
4913                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4914            }
4915        }
4916        return result;
4917    }
4918
4919    private ResolveInfo querySkipCurrentProfileIntents(
4920            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4921            int flags, int sourceUserId) {
4922        if (matchingFilters != null) {
4923            int size = matchingFilters.size();
4924            for (int i = 0; i < size; i ++) {
4925                CrossProfileIntentFilter filter = matchingFilters.get(i);
4926                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4927                    // Checking if there are activities in the target user that can handle the
4928                    // intent.
4929                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
4930                            resolvedType, flags, sourceUserId);
4931                    if (resolveInfo != null) {
4932                        return resolveInfo;
4933                    }
4934                }
4935            }
4936        }
4937        return null;
4938    }
4939
4940    // Return matching ResolveInfo if any for skip current profile intent filters.
4941    private ResolveInfo queryCrossProfileIntents(
4942            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4943            int flags, int sourceUserId) {
4944        if (matchingFilters != null) {
4945            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4946            // match the same intent. For performance reasons, it is better not to
4947            // run queryIntent twice for the same userId
4948            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4949            int size = matchingFilters.size();
4950            for (int i = 0; i < size; i++) {
4951                CrossProfileIntentFilter filter = matchingFilters.get(i);
4952                int targetUserId = filter.getTargetUserId();
4953                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4954                        && !alreadyTriedUserIds.get(targetUserId)) {
4955                    // Checking if there are activities in the target user that can handle the
4956                    // intent.
4957                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
4958                            resolvedType, flags, sourceUserId);
4959                    if (resolveInfo != null) return resolveInfo;
4960                    alreadyTriedUserIds.put(targetUserId, true);
4961                }
4962            }
4963        }
4964        return null;
4965    }
4966
4967    /**
4968     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
4969     * will forward the intent to the filter's target user.
4970     * Otherwise, returns null.
4971     */
4972    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
4973            String resolvedType, int flags, int sourceUserId) {
4974        int targetUserId = filter.getTargetUserId();
4975        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4976                resolvedType, flags, targetUserId);
4977        if (resultTargetUser != null && !resultTargetUser.isEmpty()
4978                && isUserEnabled(targetUserId)) {
4979            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
4980        }
4981        return null;
4982    }
4983
4984    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
4985            int sourceUserId, int targetUserId) {
4986        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4987        long ident = Binder.clearCallingIdentity();
4988        boolean targetIsProfile;
4989        try {
4990            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
4991        } finally {
4992            Binder.restoreCallingIdentity(ident);
4993        }
4994        String className;
4995        if (targetIsProfile) {
4996            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4997        } else {
4998            className = FORWARD_INTENT_TO_PARENT;
4999        }
5000        ComponentName forwardingActivityComponentName = new ComponentName(
5001                mAndroidApplication.packageName, className);
5002        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5003                sourceUserId);
5004        if (!targetIsProfile) {
5005            forwardingActivityInfo.showUserIcon = targetUserId;
5006            forwardingResolveInfo.noResourceId = true;
5007        }
5008        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5009        forwardingResolveInfo.priority = 0;
5010        forwardingResolveInfo.preferredOrder = 0;
5011        forwardingResolveInfo.match = 0;
5012        forwardingResolveInfo.isDefault = true;
5013        forwardingResolveInfo.filter = filter;
5014        forwardingResolveInfo.targetUserId = targetUserId;
5015        return forwardingResolveInfo;
5016    }
5017
5018    @Override
5019    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5020            Intent[] specifics, String[] specificTypes, Intent intent,
5021            String resolvedType, int flags, int userId) {
5022        if (!sUserManager.exists(userId)) return Collections.emptyList();
5023        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5024                false, "query intent activity options");
5025        final String resultsAction = intent.getAction();
5026
5027        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5028                | PackageManager.GET_RESOLVED_FILTER, userId);
5029
5030        if (DEBUG_INTENT_MATCHING) {
5031            Log.v(TAG, "Query " + intent + ": " + results);
5032        }
5033
5034        int specificsPos = 0;
5035        int N;
5036
5037        // todo: note that the algorithm used here is O(N^2).  This
5038        // isn't a problem in our current environment, but if we start running
5039        // into situations where we have more than 5 or 10 matches then this
5040        // should probably be changed to something smarter...
5041
5042        // First we go through and resolve each of the specific items
5043        // that were supplied, taking care of removing any corresponding
5044        // duplicate items in the generic resolve list.
5045        if (specifics != null) {
5046            for (int i=0; i<specifics.length; i++) {
5047                final Intent sintent = specifics[i];
5048                if (sintent == null) {
5049                    continue;
5050                }
5051
5052                if (DEBUG_INTENT_MATCHING) {
5053                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5054                }
5055
5056                String action = sintent.getAction();
5057                if (resultsAction != null && resultsAction.equals(action)) {
5058                    // If this action was explicitly requested, then don't
5059                    // remove things that have it.
5060                    action = null;
5061                }
5062
5063                ResolveInfo ri = null;
5064                ActivityInfo ai = null;
5065
5066                ComponentName comp = sintent.getComponent();
5067                if (comp == null) {
5068                    ri = resolveIntent(
5069                        sintent,
5070                        specificTypes != null ? specificTypes[i] : null,
5071                            flags, userId);
5072                    if (ri == null) {
5073                        continue;
5074                    }
5075                    if (ri == mResolveInfo) {
5076                        // ACK!  Must do something better with this.
5077                    }
5078                    ai = ri.activityInfo;
5079                    comp = new ComponentName(ai.applicationInfo.packageName,
5080                            ai.name);
5081                } else {
5082                    ai = getActivityInfo(comp, flags, userId);
5083                    if (ai == null) {
5084                        continue;
5085                    }
5086                }
5087
5088                // Look for any generic query activities that are duplicates
5089                // of this specific one, and remove them from the results.
5090                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5091                N = results.size();
5092                int j;
5093                for (j=specificsPos; j<N; j++) {
5094                    ResolveInfo sri = results.get(j);
5095                    if ((sri.activityInfo.name.equals(comp.getClassName())
5096                            && sri.activityInfo.applicationInfo.packageName.equals(
5097                                    comp.getPackageName()))
5098                        || (action != null && sri.filter.matchAction(action))) {
5099                        results.remove(j);
5100                        if (DEBUG_INTENT_MATCHING) Log.v(
5101                            TAG, "Removing duplicate item from " + j
5102                            + " due to specific " + specificsPos);
5103                        if (ri == null) {
5104                            ri = sri;
5105                        }
5106                        j--;
5107                        N--;
5108                    }
5109                }
5110
5111                // Add this specific item to its proper place.
5112                if (ri == null) {
5113                    ri = new ResolveInfo();
5114                    ri.activityInfo = ai;
5115                }
5116                results.add(specificsPos, ri);
5117                ri.specificIndex = i;
5118                specificsPos++;
5119            }
5120        }
5121
5122        // Now we go through the remaining generic results and remove any
5123        // duplicate actions that are found here.
5124        N = results.size();
5125        for (int i=specificsPos; i<N-1; i++) {
5126            final ResolveInfo rii = results.get(i);
5127            if (rii.filter == null) {
5128                continue;
5129            }
5130
5131            // Iterate over all of the actions of this result's intent
5132            // filter...  typically this should be just one.
5133            final Iterator<String> it = rii.filter.actionsIterator();
5134            if (it == null) {
5135                continue;
5136            }
5137            while (it.hasNext()) {
5138                final String action = it.next();
5139                if (resultsAction != null && resultsAction.equals(action)) {
5140                    // If this action was explicitly requested, then don't
5141                    // remove things that have it.
5142                    continue;
5143                }
5144                for (int j=i+1; j<N; j++) {
5145                    final ResolveInfo rij = results.get(j);
5146                    if (rij.filter != null && rij.filter.hasAction(action)) {
5147                        results.remove(j);
5148                        if (DEBUG_INTENT_MATCHING) Log.v(
5149                            TAG, "Removing duplicate item from " + j
5150                            + " due to action " + action + " at " + i);
5151                        j--;
5152                        N--;
5153                    }
5154                }
5155            }
5156
5157            // If the caller didn't request filter information, drop it now
5158            // so we don't have to marshall/unmarshall it.
5159            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5160                rii.filter = null;
5161            }
5162        }
5163
5164        // Filter out the caller activity if so requested.
5165        if (caller != null) {
5166            N = results.size();
5167            for (int i=0; i<N; i++) {
5168                ActivityInfo ainfo = results.get(i).activityInfo;
5169                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5170                        && caller.getClassName().equals(ainfo.name)) {
5171                    results.remove(i);
5172                    break;
5173                }
5174            }
5175        }
5176
5177        // If the caller didn't request filter information,
5178        // drop them now so we don't have to
5179        // marshall/unmarshall it.
5180        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5181            N = results.size();
5182            for (int i=0; i<N; i++) {
5183                results.get(i).filter = null;
5184            }
5185        }
5186
5187        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5188        return results;
5189    }
5190
5191    @Override
5192    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5193            int userId) {
5194        if (!sUserManager.exists(userId)) return Collections.emptyList();
5195        ComponentName comp = intent.getComponent();
5196        if (comp == null) {
5197            if (intent.getSelector() != null) {
5198                intent = intent.getSelector();
5199                comp = intent.getComponent();
5200            }
5201        }
5202        if (comp != null) {
5203            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5204            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5205            if (ai != null) {
5206                ResolveInfo ri = new ResolveInfo();
5207                ri.activityInfo = ai;
5208                list.add(ri);
5209            }
5210            return list;
5211        }
5212
5213        // reader
5214        synchronized (mPackages) {
5215            String pkgName = intent.getPackage();
5216            if (pkgName == null) {
5217                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5218            }
5219            final PackageParser.Package pkg = mPackages.get(pkgName);
5220            if (pkg != null) {
5221                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5222                        userId);
5223            }
5224            return null;
5225        }
5226    }
5227
5228    @Override
5229    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5230        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5231        if (!sUserManager.exists(userId)) return null;
5232        if (query != null) {
5233            if (query.size() >= 1) {
5234                // If there is more than one service with the same priority,
5235                // just arbitrarily pick the first one.
5236                return query.get(0);
5237            }
5238        }
5239        return null;
5240    }
5241
5242    @Override
5243    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5244            int userId) {
5245        if (!sUserManager.exists(userId)) return Collections.emptyList();
5246        ComponentName comp = intent.getComponent();
5247        if (comp == null) {
5248            if (intent.getSelector() != null) {
5249                intent = intent.getSelector();
5250                comp = intent.getComponent();
5251            }
5252        }
5253        if (comp != null) {
5254            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5255            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5256            if (si != null) {
5257                final ResolveInfo ri = new ResolveInfo();
5258                ri.serviceInfo = si;
5259                list.add(ri);
5260            }
5261            return list;
5262        }
5263
5264        // reader
5265        synchronized (mPackages) {
5266            String pkgName = intent.getPackage();
5267            if (pkgName == null) {
5268                return mServices.queryIntent(intent, resolvedType, flags, userId);
5269            }
5270            final PackageParser.Package pkg = mPackages.get(pkgName);
5271            if (pkg != null) {
5272                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5273                        userId);
5274            }
5275            return null;
5276        }
5277    }
5278
5279    @Override
5280    public List<ResolveInfo> queryIntentContentProviders(
5281            Intent intent, String resolvedType, int flags, int userId) {
5282        if (!sUserManager.exists(userId)) return Collections.emptyList();
5283        ComponentName comp = intent.getComponent();
5284        if (comp == null) {
5285            if (intent.getSelector() != null) {
5286                intent = intent.getSelector();
5287                comp = intent.getComponent();
5288            }
5289        }
5290        if (comp != null) {
5291            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5292            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5293            if (pi != null) {
5294                final ResolveInfo ri = new ResolveInfo();
5295                ri.providerInfo = pi;
5296                list.add(ri);
5297            }
5298            return list;
5299        }
5300
5301        // reader
5302        synchronized (mPackages) {
5303            String pkgName = intent.getPackage();
5304            if (pkgName == null) {
5305                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5306            }
5307            final PackageParser.Package pkg = mPackages.get(pkgName);
5308            if (pkg != null) {
5309                return mProviders.queryIntentForPackage(
5310                        intent, resolvedType, flags, pkg.providers, userId);
5311            }
5312            return null;
5313        }
5314    }
5315
5316    @Override
5317    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5318        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5319
5320        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5321
5322        // writer
5323        synchronized (mPackages) {
5324            ArrayList<PackageInfo> list;
5325            if (listUninstalled) {
5326                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5327                for (PackageSetting ps : mSettings.mPackages.values()) {
5328                    PackageInfo pi;
5329                    if (ps.pkg != null) {
5330                        pi = generatePackageInfo(ps.pkg, flags, userId);
5331                    } else {
5332                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5333                    }
5334                    if (pi != null) {
5335                        list.add(pi);
5336                    }
5337                }
5338            } else {
5339                list = new ArrayList<PackageInfo>(mPackages.size());
5340                for (PackageParser.Package p : mPackages.values()) {
5341                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5342                    if (pi != null) {
5343                        list.add(pi);
5344                    }
5345                }
5346            }
5347
5348            return new ParceledListSlice<PackageInfo>(list);
5349        }
5350    }
5351
5352    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5353            String[] permissions, boolean[] tmp, int flags, int userId) {
5354        int numMatch = 0;
5355        final PermissionsState permissionsState = ps.getPermissionsState();
5356        for (int i=0; i<permissions.length; i++) {
5357            final String permission = permissions[i];
5358            if (permissionsState.hasPermission(permission, userId)) {
5359                tmp[i] = true;
5360                numMatch++;
5361            } else {
5362                tmp[i] = false;
5363            }
5364        }
5365        if (numMatch == 0) {
5366            return;
5367        }
5368        PackageInfo pi;
5369        if (ps.pkg != null) {
5370            pi = generatePackageInfo(ps.pkg, flags, userId);
5371        } else {
5372            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5373        }
5374        // The above might return null in cases of uninstalled apps or install-state
5375        // skew across users/profiles.
5376        if (pi != null) {
5377            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5378                if (numMatch == permissions.length) {
5379                    pi.requestedPermissions = permissions;
5380                } else {
5381                    pi.requestedPermissions = new String[numMatch];
5382                    numMatch = 0;
5383                    for (int i=0; i<permissions.length; i++) {
5384                        if (tmp[i]) {
5385                            pi.requestedPermissions[numMatch] = permissions[i];
5386                            numMatch++;
5387                        }
5388                    }
5389                }
5390            }
5391            list.add(pi);
5392        }
5393    }
5394
5395    @Override
5396    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5397            String[] permissions, int flags, int userId) {
5398        if (!sUserManager.exists(userId)) return null;
5399        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5400
5401        // writer
5402        synchronized (mPackages) {
5403            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5404            boolean[] tmpBools = new boolean[permissions.length];
5405            if (listUninstalled) {
5406                for (PackageSetting ps : mSettings.mPackages.values()) {
5407                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5408                }
5409            } else {
5410                for (PackageParser.Package pkg : mPackages.values()) {
5411                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5412                    if (ps != null) {
5413                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5414                                userId);
5415                    }
5416                }
5417            }
5418
5419            return new ParceledListSlice<PackageInfo>(list);
5420        }
5421    }
5422
5423    @Override
5424    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5425        if (!sUserManager.exists(userId)) return null;
5426        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5427
5428        // writer
5429        synchronized (mPackages) {
5430            ArrayList<ApplicationInfo> list;
5431            if (listUninstalled) {
5432                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5433                for (PackageSetting ps : mSettings.mPackages.values()) {
5434                    ApplicationInfo ai;
5435                    if (ps.pkg != null) {
5436                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5437                                ps.readUserState(userId), userId);
5438                    } else {
5439                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5440                    }
5441                    if (ai != null) {
5442                        list.add(ai);
5443                    }
5444                }
5445            } else {
5446                list = new ArrayList<ApplicationInfo>(mPackages.size());
5447                for (PackageParser.Package p : mPackages.values()) {
5448                    if (p.mExtras != null) {
5449                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5450                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5451                        if (ai != null) {
5452                            list.add(ai);
5453                        }
5454                    }
5455                }
5456            }
5457
5458            return new ParceledListSlice<ApplicationInfo>(list);
5459        }
5460    }
5461
5462    public List<ApplicationInfo> getPersistentApplications(int flags) {
5463        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5464
5465        // reader
5466        synchronized (mPackages) {
5467            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5468            final int userId = UserHandle.getCallingUserId();
5469            while (i.hasNext()) {
5470                final PackageParser.Package p = i.next();
5471                if (p.applicationInfo != null
5472                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5473                        && (!mSafeMode || isSystemApp(p))) {
5474                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5475                    if (ps != null) {
5476                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5477                                ps.readUserState(userId), userId);
5478                        if (ai != null) {
5479                            finalList.add(ai);
5480                        }
5481                    }
5482                }
5483            }
5484        }
5485
5486        return finalList;
5487    }
5488
5489    @Override
5490    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5491        if (!sUserManager.exists(userId)) return null;
5492        // reader
5493        synchronized (mPackages) {
5494            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5495            PackageSetting ps = provider != null
5496                    ? mSettings.mPackages.get(provider.owner.packageName)
5497                    : null;
5498            return ps != null
5499                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5500                    && (!mSafeMode || (provider.info.applicationInfo.flags
5501                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5502                    ? PackageParser.generateProviderInfo(provider, flags,
5503                            ps.readUserState(userId), userId)
5504                    : null;
5505        }
5506    }
5507
5508    /**
5509     * @deprecated
5510     */
5511    @Deprecated
5512    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5513        // reader
5514        synchronized (mPackages) {
5515            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5516                    .entrySet().iterator();
5517            final int userId = UserHandle.getCallingUserId();
5518            while (i.hasNext()) {
5519                Map.Entry<String, PackageParser.Provider> entry = i.next();
5520                PackageParser.Provider p = entry.getValue();
5521                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5522
5523                if (ps != null && p.syncable
5524                        && (!mSafeMode || (p.info.applicationInfo.flags
5525                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5526                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5527                            ps.readUserState(userId), userId);
5528                    if (info != null) {
5529                        outNames.add(entry.getKey());
5530                        outInfo.add(info);
5531                    }
5532                }
5533            }
5534        }
5535    }
5536
5537    @Override
5538    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5539            int uid, int flags) {
5540        ArrayList<ProviderInfo> finalList = null;
5541        // reader
5542        synchronized (mPackages) {
5543            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5544            final int userId = processName != null ?
5545                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5546            while (i.hasNext()) {
5547                final PackageParser.Provider p = i.next();
5548                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5549                if (ps != null && p.info.authority != null
5550                        && (processName == null
5551                                || (p.info.processName.equals(processName)
5552                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5553                        && mSettings.isEnabledLPr(p.info, flags, userId)
5554                        && (!mSafeMode
5555                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5556                    if (finalList == null) {
5557                        finalList = new ArrayList<ProviderInfo>(3);
5558                    }
5559                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5560                            ps.readUserState(userId), userId);
5561                    if (info != null) {
5562                        finalList.add(info);
5563                    }
5564                }
5565            }
5566        }
5567
5568        if (finalList != null) {
5569            Collections.sort(finalList, mProviderInitOrderSorter);
5570            return new ParceledListSlice<ProviderInfo>(finalList);
5571        }
5572
5573        return null;
5574    }
5575
5576    @Override
5577    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5578            int flags) {
5579        // reader
5580        synchronized (mPackages) {
5581            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5582            return PackageParser.generateInstrumentationInfo(i, flags);
5583        }
5584    }
5585
5586    @Override
5587    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5588            int flags) {
5589        ArrayList<InstrumentationInfo> finalList =
5590            new ArrayList<InstrumentationInfo>();
5591
5592        // reader
5593        synchronized (mPackages) {
5594            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5595            while (i.hasNext()) {
5596                final PackageParser.Instrumentation p = i.next();
5597                if (targetPackage == null
5598                        || targetPackage.equals(p.info.targetPackage)) {
5599                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5600                            flags);
5601                    if (ii != null) {
5602                        finalList.add(ii);
5603                    }
5604                }
5605            }
5606        }
5607
5608        return finalList;
5609    }
5610
5611    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5612        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5613        if (overlays == null) {
5614            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5615            return;
5616        }
5617        for (PackageParser.Package opkg : overlays.values()) {
5618            // Not much to do if idmap fails: we already logged the error
5619            // and we certainly don't want to abort installation of pkg simply
5620            // because an overlay didn't fit properly. For these reasons,
5621            // ignore the return value of createIdmapForPackagePairLI.
5622            createIdmapForPackagePairLI(pkg, opkg);
5623        }
5624    }
5625
5626    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5627            PackageParser.Package opkg) {
5628        if (!opkg.mTrustedOverlay) {
5629            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5630                    opkg.baseCodePath + ": overlay not trusted");
5631            return false;
5632        }
5633        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5634        if (overlaySet == null) {
5635            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5636                    opkg.baseCodePath + " but target package has no known overlays");
5637            return false;
5638        }
5639        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5640        // TODO: generate idmap for split APKs
5641        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5642            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5643                    + opkg.baseCodePath);
5644            return false;
5645        }
5646        PackageParser.Package[] overlayArray =
5647            overlaySet.values().toArray(new PackageParser.Package[0]);
5648        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5649            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5650                return p1.mOverlayPriority - p2.mOverlayPriority;
5651            }
5652        };
5653        Arrays.sort(overlayArray, cmp);
5654
5655        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5656        int i = 0;
5657        for (PackageParser.Package p : overlayArray) {
5658            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5659        }
5660        return true;
5661    }
5662
5663    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5664        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
5665        try {
5666            scanDirLI(dir, parseFlags, scanFlags, currentTime);
5667        } finally {
5668            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5669        }
5670    }
5671
5672    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5673        final File[] files = dir.listFiles();
5674        if (ArrayUtils.isEmpty(files)) {
5675            Log.d(TAG, "No files in app dir " + dir);
5676            return;
5677        }
5678
5679        if (DEBUG_PACKAGE_SCANNING) {
5680            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5681                    + " flags=0x" + Integer.toHexString(parseFlags));
5682        }
5683
5684        for (File file : files) {
5685            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5686                    && !PackageInstallerService.isStageName(file.getName());
5687            if (!isPackage) {
5688                // Ignore entries which are not packages
5689                continue;
5690            }
5691            try {
5692                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5693                        scanFlags, currentTime, null);
5694            } catch (PackageManagerException e) {
5695                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5696
5697                // Delete invalid userdata apps
5698                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5699                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5700                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5701                    if (file.isDirectory()) {
5702                        mInstaller.rmPackageDir(file.getAbsolutePath());
5703                    } else {
5704                        file.delete();
5705                    }
5706                }
5707            }
5708        }
5709    }
5710
5711    private static File getSettingsProblemFile() {
5712        File dataDir = Environment.getDataDirectory();
5713        File systemDir = new File(dataDir, "system");
5714        File fname = new File(systemDir, "uiderrors.txt");
5715        return fname;
5716    }
5717
5718    static void reportSettingsProblem(int priority, String msg) {
5719        logCriticalInfo(priority, msg);
5720    }
5721
5722    static void logCriticalInfo(int priority, String msg) {
5723        Slog.println(priority, TAG, msg);
5724        EventLogTags.writePmCriticalInfo(msg);
5725        try {
5726            File fname = getSettingsProblemFile();
5727            FileOutputStream out = new FileOutputStream(fname, true);
5728            PrintWriter pw = new FastPrintWriter(out);
5729            SimpleDateFormat formatter = new SimpleDateFormat();
5730            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5731            pw.println(dateString + ": " + msg);
5732            pw.close();
5733            FileUtils.setPermissions(
5734                    fname.toString(),
5735                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5736                    -1, -1);
5737        } catch (java.io.IOException e) {
5738        }
5739    }
5740
5741    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5742            PackageParser.Package pkg, File srcFile, int parseFlags)
5743            throws PackageManagerException {
5744        if (ps != null
5745                && ps.codePath.equals(srcFile)
5746                && ps.timeStamp == srcFile.lastModified()
5747                && !isCompatSignatureUpdateNeeded(pkg)
5748                && !isRecoverSignatureUpdateNeeded(pkg)) {
5749            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5750            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5751            ArraySet<PublicKey> signingKs;
5752            synchronized (mPackages) {
5753                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5754            }
5755            if (ps.signatures.mSignatures != null
5756                    && ps.signatures.mSignatures.length != 0
5757                    && signingKs != null) {
5758                // Optimization: reuse the existing cached certificates
5759                // if the package appears to be unchanged.
5760                pkg.mSignatures = ps.signatures.mSignatures;
5761                pkg.mSigningKeys = signingKs;
5762                return;
5763            }
5764
5765            Slog.w(TAG, "PackageSetting for " + ps.name
5766                    + " is missing signatures.  Collecting certs again to recover them.");
5767        } else {
5768            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5769        }
5770
5771        try {
5772            pp.collectCertificates(pkg, parseFlags);
5773            pp.collectManifestDigest(pkg);
5774        } catch (PackageParserException e) {
5775            throw PackageManagerException.from(e);
5776        }
5777    }
5778
5779    /**
5780     *  Traces a package scan.
5781     *  @see #scanPackageLI(File, int, int, long, UserHandle)
5782     */
5783    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
5784            long currentTime, UserHandle user) throws PackageManagerException {
5785        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
5786        try {
5787            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
5788        } finally {
5789            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5790        }
5791    }
5792
5793    /**
5794     *  Scans a package and returns the newly parsed package.
5795     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
5796     */
5797    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5798            long currentTime, UserHandle user) throws PackageManagerException {
5799        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5800        parseFlags |= mDefParseFlags;
5801        PackageParser pp = new PackageParser();
5802        pp.setSeparateProcesses(mSeparateProcesses);
5803        pp.setOnlyCoreApps(mOnlyCore);
5804        pp.setDisplayMetrics(mMetrics);
5805
5806        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5807            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5808        }
5809
5810        final PackageParser.Package pkg;
5811        try {
5812            pkg = pp.parsePackage(scanFile, parseFlags);
5813        } catch (PackageParserException e) {
5814            throw PackageManagerException.from(e);
5815        }
5816
5817        PackageSetting ps = null;
5818        PackageSetting updatedPkg;
5819        // reader
5820        synchronized (mPackages) {
5821            // Look to see if we already know about this package.
5822            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5823            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5824                // This package has been renamed to its original name.  Let's
5825                // use that.
5826                ps = mSettings.peekPackageLPr(oldName);
5827            }
5828            // If there was no original package, see one for the real package name.
5829            if (ps == null) {
5830                ps = mSettings.peekPackageLPr(pkg.packageName);
5831            }
5832            // Check to see if this package could be hiding/updating a system
5833            // package.  Must look for it either under the original or real
5834            // package name depending on our state.
5835            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5836            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5837        }
5838        boolean updatedPkgBetter = false;
5839        // First check if this is a system package that may involve an update
5840        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5841            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5842            // it needs to drop FLAG_PRIVILEGED.
5843            if (locationIsPrivileged(scanFile)) {
5844                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5845            } else {
5846                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5847            }
5848
5849            if (ps != null && !ps.codePath.equals(scanFile)) {
5850                // The path has changed from what was last scanned...  check the
5851                // version of the new path against what we have stored to determine
5852                // what to do.
5853                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5854                if (pkg.mVersionCode <= ps.versionCode) {
5855                    // The system package has been updated and the code path does not match
5856                    // Ignore entry. Skip it.
5857                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5858                            + " ignored: updated version " + ps.versionCode
5859                            + " better than this " + pkg.mVersionCode);
5860                    if (!updatedPkg.codePath.equals(scanFile)) {
5861                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5862                                + ps.name + " changing from " + updatedPkg.codePathString
5863                                + " to " + scanFile);
5864                        updatedPkg.codePath = scanFile;
5865                        updatedPkg.codePathString = scanFile.toString();
5866                        updatedPkg.resourcePath = scanFile;
5867                        updatedPkg.resourcePathString = scanFile.toString();
5868                    }
5869                    updatedPkg.pkg = pkg;
5870                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5871                            "Package " + ps.name + " at " + scanFile
5872                                    + " ignored: updated version " + ps.versionCode
5873                                    + " better than this " + pkg.mVersionCode);
5874                } else {
5875                    // The current app on the system partition is better than
5876                    // what we have updated to on the data partition; switch
5877                    // back to the system partition version.
5878                    // At this point, its safely assumed that package installation for
5879                    // apps in system partition will go through. If not there won't be a working
5880                    // version of the app
5881                    // writer
5882                    synchronized (mPackages) {
5883                        // Just remove the loaded entries from package lists.
5884                        mPackages.remove(ps.name);
5885                    }
5886
5887                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5888                            + " reverting from " + ps.codePathString
5889                            + ": new version " + pkg.mVersionCode
5890                            + " better than installed " + ps.versionCode);
5891
5892                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5893                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5894                    synchronized (mInstallLock) {
5895                        args.cleanUpResourcesLI();
5896                    }
5897                    synchronized (mPackages) {
5898                        mSettings.enableSystemPackageLPw(ps.name);
5899                    }
5900                    updatedPkgBetter = true;
5901                }
5902            }
5903        }
5904
5905        if (updatedPkg != null) {
5906            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5907            // initially
5908            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5909
5910            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5911            // flag set initially
5912            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5913                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5914            }
5915        }
5916
5917        // Verify certificates against what was last scanned
5918        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5919
5920        /*
5921         * A new system app appeared, but we already had a non-system one of the
5922         * same name installed earlier.
5923         */
5924        boolean shouldHideSystemApp = false;
5925        if (updatedPkg == null && ps != null
5926                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5927            /*
5928             * Check to make sure the signatures match first. If they don't,
5929             * wipe the installed application and its data.
5930             */
5931            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5932                    != PackageManager.SIGNATURE_MATCH) {
5933                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5934                        + " signatures don't match existing userdata copy; removing");
5935                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5936                ps = null;
5937            } else {
5938                /*
5939                 * If the newly-added system app is an older version than the
5940                 * already installed version, hide it. It will be scanned later
5941                 * and re-added like an update.
5942                 */
5943                if (pkg.mVersionCode <= ps.versionCode) {
5944                    shouldHideSystemApp = true;
5945                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5946                            + " but new version " + pkg.mVersionCode + " better than installed "
5947                            + ps.versionCode + "; hiding system");
5948                } else {
5949                    /*
5950                     * The newly found system app is a newer version that the
5951                     * one previously installed. Simply remove the
5952                     * already-installed application and replace it with our own
5953                     * while keeping the application data.
5954                     */
5955                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5956                            + " reverting from " + ps.codePathString + ": new version "
5957                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5958                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5959                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5960                    synchronized (mInstallLock) {
5961                        args.cleanUpResourcesLI();
5962                    }
5963                }
5964            }
5965        }
5966
5967        // The apk is forward locked (not public) if its code and resources
5968        // are kept in different files. (except for app in either system or
5969        // vendor path).
5970        // TODO grab this value from PackageSettings
5971        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5972            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5973                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5974            }
5975        }
5976
5977        // TODO: extend to support forward-locked splits
5978        String resourcePath = null;
5979        String baseResourcePath = null;
5980        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5981            if (ps != null && ps.resourcePathString != null) {
5982                resourcePath = ps.resourcePathString;
5983                baseResourcePath = ps.resourcePathString;
5984            } else {
5985                // Should not happen at all. Just log an error.
5986                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5987            }
5988        } else {
5989            resourcePath = pkg.codePath;
5990            baseResourcePath = pkg.baseCodePath;
5991        }
5992
5993        // Set application objects path explicitly.
5994        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5995        pkg.applicationInfo.setCodePath(pkg.codePath);
5996        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5997        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5998        pkg.applicationInfo.setResourcePath(resourcePath);
5999        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6000        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6001
6002        // Note that we invoke the following method only if we are about to unpack an application
6003        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6004                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6005
6006        /*
6007         * If the system app should be overridden by a previously installed
6008         * data, hide the system app now and let the /data/app scan pick it up
6009         * again.
6010         */
6011        if (shouldHideSystemApp) {
6012            synchronized (mPackages) {
6013                mSettings.disableSystemPackageLPw(pkg.packageName);
6014            }
6015        }
6016
6017        return scannedPkg;
6018    }
6019
6020    private static String fixProcessName(String defProcessName,
6021            String processName, int uid) {
6022        if (processName == null) {
6023            return defProcessName;
6024        }
6025        return processName;
6026    }
6027
6028    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6029            throws PackageManagerException {
6030        if (pkgSetting.signatures.mSignatures != null) {
6031            // Already existing package. Make sure signatures match
6032            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6033                    == PackageManager.SIGNATURE_MATCH;
6034            if (!match) {
6035                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6036                        == PackageManager.SIGNATURE_MATCH;
6037            }
6038            if (!match) {
6039                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6040                        == PackageManager.SIGNATURE_MATCH;
6041            }
6042            if (!match) {
6043                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6044                        + pkg.packageName + " signatures do not match the "
6045                        + "previously installed version; ignoring!");
6046            }
6047        }
6048
6049        // Check for shared user signatures
6050        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6051            // Already existing package. Make sure signatures match
6052            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6053                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6054            if (!match) {
6055                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6056                        == PackageManager.SIGNATURE_MATCH;
6057            }
6058            if (!match) {
6059                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6060                        == PackageManager.SIGNATURE_MATCH;
6061            }
6062            if (!match) {
6063                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6064                        "Package " + pkg.packageName
6065                        + " has no signatures that match those in shared user "
6066                        + pkgSetting.sharedUser.name + "; ignoring!");
6067            }
6068        }
6069    }
6070
6071    /**
6072     * Enforces that only the system UID or root's UID can call a method exposed
6073     * via Binder.
6074     *
6075     * @param message used as message if SecurityException is thrown
6076     * @throws SecurityException if the caller is not system or root
6077     */
6078    private static final void enforceSystemOrRoot(String message) {
6079        final int uid = Binder.getCallingUid();
6080        if (uid != Process.SYSTEM_UID && uid != 0) {
6081            throw new SecurityException(message);
6082        }
6083    }
6084
6085    @Override
6086    public void performBootDexOpt() {
6087        enforceSystemOrRoot("Only the system can request dexopt be performed");
6088
6089        // Before everything else, see whether we need to fstrim.
6090        try {
6091            IMountService ms = PackageHelper.getMountService();
6092            if (ms != null) {
6093                final boolean isUpgrade = isUpgrade();
6094                boolean doTrim = isUpgrade;
6095                if (doTrim) {
6096                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6097                } else {
6098                    final long interval = android.provider.Settings.Global.getLong(
6099                            mContext.getContentResolver(),
6100                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6101                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6102                    if (interval > 0) {
6103                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6104                        if (timeSinceLast > interval) {
6105                            doTrim = true;
6106                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6107                                    + "; running immediately");
6108                        }
6109                    }
6110                }
6111                if (doTrim) {
6112                    if (!isFirstBoot()) {
6113                        try {
6114                            ActivityManagerNative.getDefault().showBootMessage(
6115                                    mContext.getResources().getString(
6116                                            R.string.android_upgrading_fstrim), true);
6117                        } catch (RemoteException e) {
6118                        }
6119                    }
6120                    ms.runMaintenance();
6121                }
6122            } else {
6123                Slog.e(TAG, "Mount service unavailable!");
6124            }
6125        } catch (RemoteException e) {
6126            // Can't happen; MountService is local
6127        }
6128
6129        final ArraySet<PackageParser.Package> pkgs;
6130        synchronized (mPackages) {
6131            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6132        }
6133
6134        if (pkgs != null) {
6135            // Sort apps by importance for dexopt ordering. Important apps are given more priority
6136            // in case the device runs out of space.
6137            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6138            // Give priority to core apps.
6139            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6140                PackageParser.Package pkg = it.next();
6141                if (pkg.coreApp) {
6142                    if (DEBUG_DEXOPT) {
6143                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6144                    }
6145                    sortedPkgs.add(pkg);
6146                    it.remove();
6147                }
6148            }
6149            // Give priority to system apps that listen for pre boot complete.
6150            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6151            ArraySet<String> pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM);
6152            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6153                PackageParser.Package pkg = it.next();
6154                if (pkgNames.contains(pkg.packageName)) {
6155                    if (DEBUG_DEXOPT) {
6156                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6157                    }
6158                    sortedPkgs.add(pkg);
6159                    it.remove();
6160                }
6161            }
6162            // Filter out packages that aren't recently used.
6163            filterRecentlyUsedApps(pkgs);
6164            // Add all remaining apps.
6165            for (PackageParser.Package pkg : pkgs) {
6166                if (DEBUG_DEXOPT) {
6167                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6168                }
6169                sortedPkgs.add(pkg);
6170            }
6171
6172            // If we want to be lazy, filter everything that wasn't recently used.
6173            if (mLazyDexOpt) {
6174                filterRecentlyUsedApps(sortedPkgs);
6175            }
6176
6177            int i = 0;
6178            int total = sortedPkgs.size();
6179            File dataDir = Environment.getDataDirectory();
6180            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6181            if (lowThreshold == 0) {
6182                throw new IllegalStateException("Invalid low memory threshold");
6183            }
6184            for (PackageParser.Package pkg : sortedPkgs) {
6185                long usableSpace = dataDir.getUsableSpace();
6186                if (usableSpace < lowThreshold) {
6187                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6188                    break;
6189                }
6190                performBootDexOpt(pkg, ++i, total);
6191            }
6192        }
6193    }
6194
6195    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6196        // Filter out packages that aren't recently used.
6197        //
6198        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6199        // should do a full dexopt.
6200        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6201            int total = pkgs.size();
6202            int skipped = 0;
6203            long now = System.currentTimeMillis();
6204            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6205                PackageParser.Package pkg = i.next();
6206                long then = pkg.mLastPackageUsageTimeInMills;
6207                if (then + mDexOptLRUThresholdInMills < now) {
6208                    if (DEBUG_DEXOPT) {
6209                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6210                              ((then == 0) ? "never" : new Date(then)));
6211                    }
6212                    i.remove();
6213                    skipped++;
6214                }
6215            }
6216            if (DEBUG_DEXOPT) {
6217                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6218            }
6219        }
6220    }
6221
6222    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6223        List<ResolveInfo> ris = null;
6224        try {
6225            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6226                    intent, null, 0, userId);
6227        } catch (RemoteException e) {
6228        }
6229        ArraySet<String> pkgNames = new ArraySet<String>();
6230        if (ris != null) {
6231            for (ResolveInfo ri : ris) {
6232                pkgNames.add(ri.activityInfo.packageName);
6233            }
6234        }
6235        return pkgNames;
6236    }
6237
6238    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6239        if (DEBUG_DEXOPT) {
6240            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6241        }
6242        if (!isFirstBoot()) {
6243            try {
6244                ActivityManagerNative.getDefault().showBootMessage(
6245                        mContext.getResources().getString(R.string.android_upgrading_apk,
6246                                curr, total), true);
6247            } catch (RemoteException e) {
6248            }
6249        }
6250        PackageParser.Package p = pkg;
6251        synchronized (mInstallLock) {
6252            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6253                    false /* force dex */, false /* defer */, true /* include dependencies */,
6254                    false /* boot complete */);
6255        }
6256    }
6257
6258    @Override
6259    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6260        return performDexOptTraced(packageName, instructionSet, false);
6261    }
6262
6263    public boolean performDexOpt(
6264            String packageName, String instructionSet, boolean backgroundDexopt) {
6265        return performDexOptTraced(packageName, instructionSet, backgroundDexopt);
6266    }
6267
6268    private boolean performDexOptTraced(
6269            String packageName, String instructionSet, boolean backgroundDexopt) {
6270        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6271        try {
6272            return performDexOptInternal(packageName, instructionSet, backgroundDexopt);
6273        } finally {
6274            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6275        }
6276    }
6277
6278    private boolean performDexOptInternal(
6279            String packageName, String instructionSet, boolean backgroundDexopt) {
6280        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6281        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6282        if (!dexopt && !updateUsage) {
6283            // We aren't going to dexopt or update usage, so bail early.
6284            return false;
6285        }
6286        PackageParser.Package p;
6287        final String targetInstructionSet;
6288        synchronized (mPackages) {
6289            p = mPackages.get(packageName);
6290            if (p == null) {
6291                return false;
6292            }
6293            if (updateUsage) {
6294                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6295            }
6296            mPackageUsage.write(false);
6297            if (!dexopt) {
6298                // We aren't going to dexopt, so bail early.
6299                return false;
6300            }
6301
6302            targetInstructionSet = instructionSet != null ? instructionSet :
6303                    getPrimaryInstructionSet(p.applicationInfo);
6304            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6305                return false;
6306            }
6307        }
6308        long callingId = Binder.clearCallingIdentity();
6309        try {
6310            synchronized (mInstallLock) {
6311                final String[] instructionSets = new String[] { targetInstructionSet };
6312                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6313                        false /* forceDex */, false /* defer */, true /* inclDependencies */,
6314                        true /* boot complete */);
6315                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6316            }
6317        } finally {
6318            Binder.restoreCallingIdentity(callingId);
6319        }
6320    }
6321
6322    public ArraySet<String> getPackagesThatNeedDexOpt() {
6323        ArraySet<String> pkgs = null;
6324        synchronized (mPackages) {
6325            for (PackageParser.Package p : mPackages.values()) {
6326                if (DEBUG_DEXOPT) {
6327                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6328                }
6329                if (!p.mDexOptPerformed.isEmpty()) {
6330                    continue;
6331                }
6332                if (pkgs == null) {
6333                    pkgs = new ArraySet<String>();
6334                }
6335                pkgs.add(p.packageName);
6336            }
6337        }
6338        return pkgs;
6339    }
6340
6341    public void shutdown() {
6342        mPackageUsage.write(true);
6343    }
6344
6345    @Override
6346    public void forceDexOpt(String packageName) {
6347        enforceSystemOrRoot("forceDexOpt");
6348
6349        PackageParser.Package pkg;
6350        synchronized (mPackages) {
6351            pkg = mPackages.get(packageName);
6352            if (pkg == null) {
6353                throw new IllegalArgumentException("Missing package: " + packageName);
6354            }
6355        }
6356
6357        synchronized (mInstallLock) {
6358            final String[] instructionSets = new String[] {
6359                    getPrimaryInstructionSet(pkg.applicationInfo) };
6360
6361            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6362
6363            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6364                    true /*forceDex*/, false /* defer */, true /* inclDependencies */,
6365                    true /* boot complete */);
6366
6367            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6368            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6369                throw new IllegalStateException("Failed to dexopt: " + res);
6370            }
6371        }
6372    }
6373
6374    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6375        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6376            Slog.w(TAG, "Unable to update from " + oldPkg.name
6377                    + " to " + newPkg.packageName
6378                    + ": old package not in system partition");
6379            return false;
6380        } else if (mPackages.get(oldPkg.name) != null) {
6381            Slog.w(TAG, "Unable to update from " + oldPkg.name
6382                    + " to " + newPkg.packageName
6383                    + ": old package still exists");
6384            return false;
6385        }
6386        return true;
6387    }
6388
6389    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6390        int[] users = sUserManager.getUserIds();
6391        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6392        if (res < 0) {
6393            return res;
6394        }
6395        for (int user : users) {
6396            if (user != 0) {
6397                res = mInstaller.createUserData(volumeUuid, packageName,
6398                        UserHandle.getUid(user, uid), user, seinfo);
6399                if (res < 0) {
6400                    return res;
6401                }
6402            }
6403        }
6404        return res;
6405    }
6406
6407    private int removeDataDirsLI(String volumeUuid, String packageName) {
6408        int[] users = sUserManager.getUserIds();
6409        int res = 0;
6410        for (int user : users) {
6411            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6412            if (resInner < 0) {
6413                res = resInner;
6414            }
6415        }
6416
6417        return res;
6418    }
6419
6420    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6421        int[] users = sUserManager.getUserIds();
6422        int res = 0;
6423        for (int user : users) {
6424            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6425            if (resInner < 0) {
6426                res = resInner;
6427            }
6428        }
6429        return res;
6430    }
6431
6432    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6433            PackageParser.Package changingLib) {
6434        if (file.path != null) {
6435            usesLibraryFiles.add(file.path);
6436            return;
6437        }
6438        PackageParser.Package p = mPackages.get(file.apk);
6439        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6440            // If we are doing this while in the middle of updating a library apk,
6441            // then we need to make sure to use that new apk for determining the
6442            // dependencies here.  (We haven't yet finished committing the new apk
6443            // to the package manager state.)
6444            if (p == null || p.packageName.equals(changingLib.packageName)) {
6445                p = changingLib;
6446            }
6447        }
6448        if (p != null) {
6449            usesLibraryFiles.addAll(p.getAllCodePaths());
6450        }
6451    }
6452
6453    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6454            PackageParser.Package changingLib) throws PackageManagerException {
6455        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6456            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6457            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6458            for (int i=0; i<N; i++) {
6459                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6460                if (file == null) {
6461                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6462                            "Package " + pkg.packageName + " requires unavailable shared library "
6463                            + pkg.usesLibraries.get(i) + "; failing!");
6464                }
6465                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6466            }
6467            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6468            for (int i=0; i<N; i++) {
6469                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6470                if (file == null) {
6471                    Slog.w(TAG, "Package " + pkg.packageName
6472                            + " desires unavailable shared library "
6473                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6474                } else {
6475                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6476                }
6477            }
6478            N = usesLibraryFiles.size();
6479            if (N > 0) {
6480                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6481            } else {
6482                pkg.usesLibraryFiles = null;
6483            }
6484        }
6485    }
6486
6487    private static boolean hasString(List<String> list, List<String> which) {
6488        if (list == null) {
6489            return false;
6490        }
6491        for (int i=list.size()-1; i>=0; i--) {
6492            for (int j=which.size()-1; j>=0; j--) {
6493                if (which.get(j).equals(list.get(i))) {
6494                    return true;
6495                }
6496            }
6497        }
6498        return false;
6499    }
6500
6501    private void updateAllSharedLibrariesLPw() {
6502        for (PackageParser.Package pkg : mPackages.values()) {
6503            try {
6504                updateSharedLibrariesLPw(pkg, null);
6505            } catch (PackageManagerException e) {
6506                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6507            }
6508        }
6509    }
6510
6511    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6512            PackageParser.Package changingPkg) {
6513        ArrayList<PackageParser.Package> res = null;
6514        for (PackageParser.Package pkg : mPackages.values()) {
6515            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6516                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6517                if (res == null) {
6518                    res = new ArrayList<PackageParser.Package>();
6519                }
6520                res.add(pkg);
6521                try {
6522                    updateSharedLibrariesLPw(pkg, changingPkg);
6523                } catch (PackageManagerException e) {
6524                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6525                }
6526            }
6527        }
6528        return res;
6529    }
6530
6531    /**
6532     * Derive the value of the {@code cpuAbiOverride} based on the provided
6533     * value and an optional stored value from the package settings.
6534     */
6535    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6536        String cpuAbiOverride = null;
6537
6538        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6539            cpuAbiOverride = null;
6540        } else if (abiOverride != null) {
6541            cpuAbiOverride = abiOverride;
6542        } else if (settings != null) {
6543            cpuAbiOverride = settings.cpuAbiOverrideString;
6544        }
6545
6546        return cpuAbiOverride;
6547    }
6548
6549    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6550            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6551        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6552        try {
6553            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6554        } finally {
6555            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6556        }
6557    }
6558
6559    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6560            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6561        boolean success = false;
6562        try {
6563            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6564                    currentTime, user);
6565            success = true;
6566            return res;
6567        } finally {
6568            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6569                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6570            }
6571        }
6572    }
6573
6574    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6575            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6576        final File scanFile = new File(pkg.codePath);
6577        if (pkg.applicationInfo.getCodePath() == null ||
6578                pkg.applicationInfo.getResourcePath() == null) {
6579            // Bail out. The resource and code paths haven't been set.
6580            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6581                    "Code and resource paths haven't been set correctly");
6582        }
6583
6584        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6585            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6586        } else {
6587            // Only allow system apps to be flagged as core apps.
6588            pkg.coreApp = false;
6589        }
6590
6591        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6592            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6593        }
6594
6595        if (mCustomResolverComponentName != null &&
6596                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6597            setUpCustomResolverActivity(pkg);
6598        }
6599
6600        if (pkg.packageName.equals("android")) {
6601            synchronized (mPackages) {
6602                if (mAndroidApplication != null) {
6603                    Slog.w(TAG, "*************************************************");
6604                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6605                    Slog.w(TAG, " file=" + scanFile);
6606                    Slog.w(TAG, "*************************************************");
6607                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6608                            "Core android package being redefined.  Skipping.");
6609                }
6610
6611                // Set up information for our fall-back user intent resolution activity.
6612                mPlatformPackage = pkg;
6613                pkg.mVersionCode = mSdkVersion;
6614                mAndroidApplication = pkg.applicationInfo;
6615
6616                if (!mResolverReplaced) {
6617                    mResolveActivity.applicationInfo = mAndroidApplication;
6618                    mResolveActivity.name = ResolverActivity.class.getName();
6619                    mResolveActivity.packageName = mAndroidApplication.packageName;
6620                    mResolveActivity.processName = "system:ui";
6621                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6622                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6623                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6624                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6625                    mResolveActivity.exported = true;
6626                    mResolveActivity.enabled = true;
6627                    mResolveInfo.activityInfo = mResolveActivity;
6628                    mResolveInfo.priority = 0;
6629                    mResolveInfo.preferredOrder = 0;
6630                    mResolveInfo.match = 0;
6631                    mResolveComponentName = new ComponentName(
6632                            mAndroidApplication.packageName, mResolveActivity.name);
6633                }
6634            }
6635        }
6636
6637        if (DEBUG_PACKAGE_SCANNING) {
6638            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6639                Log.d(TAG, "Scanning package " + pkg.packageName);
6640        }
6641
6642        if (mPackages.containsKey(pkg.packageName)
6643                || mSharedLibraries.containsKey(pkg.packageName)) {
6644            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6645                    "Application package " + pkg.packageName
6646                    + " already installed.  Skipping duplicate.");
6647        }
6648
6649        // If we're only installing presumed-existing packages, require that the
6650        // scanned APK is both already known and at the path previously established
6651        // for it.  Previously unknown packages we pick up normally, but if we have an
6652        // a priori expectation about this package's install presence, enforce it.
6653        // With a singular exception for new system packages. When an OTA contains
6654        // a new system package, we allow the codepath to change from a system location
6655        // to the user-installed location. If we don't allow this change, any newer,
6656        // user-installed version of the application will be ignored.
6657        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6658            if (mExpectingBetter.containsKey(pkg.packageName)) {
6659                logCriticalInfo(Log.WARN,
6660                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6661            } else {
6662                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6663                if (known != null) {
6664                    if (DEBUG_PACKAGE_SCANNING) {
6665                        Log.d(TAG, "Examining " + pkg.codePath
6666                                + " and requiring known paths " + known.codePathString
6667                                + " & " + known.resourcePathString);
6668                    }
6669                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6670                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6671                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6672                                "Application package " + pkg.packageName
6673                                + " found at " + pkg.applicationInfo.getCodePath()
6674                                + " but expected at " + known.codePathString + "; ignoring.");
6675                    }
6676                }
6677            }
6678        }
6679
6680        // Initialize package source and resource directories
6681        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6682        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6683
6684        SharedUserSetting suid = null;
6685        PackageSetting pkgSetting = null;
6686
6687        if (!isSystemApp(pkg)) {
6688            // Only system apps can use these features.
6689            pkg.mOriginalPackages = null;
6690            pkg.mRealPackage = null;
6691            pkg.mAdoptPermissions = null;
6692        }
6693
6694        // writer
6695        synchronized (mPackages) {
6696            if (pkg.mSharedUserId != null) {
6697                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6698                if (suid == null) {
6699                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6700                            "Creating application package " + pkg.packageName
6701                            + " for shared user failed");
6702                }
6703                if (DEBUG_PACKAGE_SCANNING) {
6704                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6705                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6706                                + "): packages=" + suid.packages);
6707                }
6708            }
6709
6710            // Check if we are renaming from an original package name.
6711            PackageSetting origPackage = null;
6712            String realName = null;
6713            if (pkg.mOriginalPackages != null) {
6714                // This package may need to be renamed to a previously
6715                // installed name.  Let's check on that...
6716                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6717                if (pkg.mOriginalPackages.contains(renamed)) {
6718                    // This package had originally been installed as the
6719                    // original name, and we have already taken care of
6720                    // transitioning to the new one.  Just update the new
6721                    // one to continue using the old name.
6722                    realName = pkg.mRealPackage;
6723                    if (!pkg.packageName.equals(renamed)) {
6724                        // Callers into this function may have already taken
6725                        // care of renaming the package; only do it here if
6726                        // it is not already done.
6727                        pkg.setPackageName(renamed);
6728                    }
6729
6730                } else {
6731                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6732                        if ((origPackage = mSettings.peekPackageLPr(
6733                                pkg.mOriginalPackages.get(i))) != null) {
6734                            // We do have the package already installed under its
6735                            // original name...  should we use it?
6736                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6737                                // New package is not compatible with original.
6738                                origPackage = null;
6739                                continue;
6740                            } else if (origPackage.sharedUser != null) {
6741                                // Make sure uid is compatible between packages.
6742                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6743                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6744                                            + " to " + pkg.packageName + ": old uid "
6745                                            + origPackage.sharedUser.name
6746                                            + " differs from " + pkg.mSharedUserId);
6747                                    origPackage = null;
6748                                    continue;
6749                                }
6750                            } else {
6751                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6752                                        + pkg.packageName + " to old name " + origPackage.name);
6753                            }
6754                            break;
6755                        }
6756                    }
6757                }
6758            }
6759
6760            if (mTransferedPackages.contains(pkg.packageName)) {
6761                Slog.w(TAG, "Package " + pkg.packageName
6762                        + " was transferred to another, but its .apk remains");
6763            }
6764
6765            // Just create the setting, don't add it yet. For already existing packages
6766            // the PkgSetting exists already and doesn't have to be created.
6767            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6768                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6769                    pkg.applicationInfo.primaryCpuAbi,
6770                    pkg.applicationInfo.secondaryCpuAbi,
6771                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6772                    user, false);
6773            if (pkgSetting == null) {
6774                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6775                        "Creating application package " + pkg.packageName + " failed");
6776            }
6777
6778            if (pkgSetting.origPackage != null) {
6779                // If we are first transitioning from an original package,
6780                // fix up the new package's name now.  We need to do this after
6781                // looking up the package under its new name, so getPackageLP
6782                // can take care of fiddling things correctly.
6783                pkg.setPackageName(origPackage.name);
6784
6785                // File a report about this.
6786                String msg = "New package " + pkgSetting.realName
6787                        + " renamed to replace old package " + pkgSetting.name;
6788                reportSettingsProblem(Log.WARN, msg);
6789
6790                // Make a note of it.
6791                mTransferedPackages.add(origPackage.name);
6792
6793                // No longer need to retain this.
6794                pkgSetting.origPackage = null;
6795            }
6796
6797            if (realName != null) {
6798                // Make a note of it.
6799                mTransferedPackages.add(pkg.packageName);
6800            }
6801
6802            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6803                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6804            }
6805
6806            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6807                // Check all shared libraries and map to their actual file path.
6808                // We only do this here for apps not on a system dir, because those
6809                // are the only ones that can fail an install due to this.  We
6810                // will take care of the system apps by updating all of their
6811                // library paths after the scan is done.
6812                updateSharedLibrariesLPw(pkg, null);
6813            }
6814
6815            if (mFoundPolicyFile) {
6816                SELinuxMMAC.assignSeinfoValue(pkg);
6817            }
6818
6819            pkg.applicationInfo.uid = pkgSetting.appId;
6820            pkg.mExtras = pkgSetting;
6821            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6822                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6823                    // We just determined the app is signed correctly, so bring
6824                    // over the latest parsed certs.
6825                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6826                } else {
6827                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6828                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6829                                "Package " + pkg.packageName + " upgrade keys do not match the "
6830                                + "previously installed version");
6831                    } else {
6832                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6833                        String msg = "System package " + pkg.packageName
6834                            + " signature changed; retaining data.";
6835                        reportSettingsProblem(Log.WARN, msg);
6836                    }
6837                }
6838            } else {
6839                try {
6840                    verifySignaturesLP(pkgSetting, pkg);
6841                    // We just determined the app is signed correctly, so bring
6842                    // over the latest parsed certs.
6843                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6844                } catch (PackageManagerException e) {
6845                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6846                        throw e;
6847                    }
6848                    // The signature has changed, but this package is in the system
6849                    // image...  let's recover!
6850                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6851                    // However...  if this package is part of a shared user, but it
6852                    // doesn't match the signature of the shared user, let's fail.
6853                    // What this means is that you can't change the signatures
6854                    // associated with an overall shared user, which doesn't seem all
6855                    // that unreasonable.
6856                    if (pkgSetting.sharedUser != null) {
6857                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6858                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6859                            throw new PackageManagerException(
6860                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6861                                            "Signature mismatch for shared user : "
6862                                            + pkgSetting.sharedUser);
6863                        }
6864                    }
6865                    // File a report about this.
6866                    String msg = "System package " + pkg.packageName
6867                        + " signature changed; retaining data.";
6868                    reportSettingsProblem(Log.WARN, msg);
6869                }
6870            }
6871            // Verify that this new package doesn't have any content providers
6872            // that conflict with existing packages.  Only do this if the
6873            // package isn't already installed, since we don't want to break
6874            // things that are installed.
6875            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6876                final int N = pkg.providers.size();
6877                int i;
6878                for (i=0; i<N; i++) {
6879                    PackageParser.Provider p = pkg.providers.get(i);
6880                    if (p.info.authority != null) {
6881                        String names[] = p.info.authority.split(";");
6882                        for (int j = 0; j < names.length; j++) {
6883                            if (mProvidersByAuthority.containsKey(names[j])) {
6884                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6885                                final String otherPackageName =
6886                                        ((other != null && other.getComponentName() != null) ?
6887                                                other.getComponentName().getPackageName() : "?");
6888                                throw new PackageManagerException(
6889                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6890                                                "Can't install because provider name " + names[j]
6891                                                + " (in package " + pkg.applicationInfo.packageName
6892                                                + ") is already used by " + otherPackageName);
6893                            }
6894                        }
6895                    }
6896                }
6897            }
6898
6899            if (pkg.mAdoptPermissions != null) {
6900                // This package wants to adopt ownership of permissions from
6901                // another package.
6902                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6903                    final String origName = pkg.mAdoptPermissions.get(i);
6904                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6905                    if (orig != null) {
6906                        if (verifyPackageUpdateLPr(orig, pkg)) {
6907                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6908                                    + pkg.packageName);
6909                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6910                        }
6911                    }
6912                }
6913            }
6914        }
6915
6916        final String pkgName = pkg.packageName;
6917
6918        final long scanFileTime = scanFile.lastModified();
6919        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6920        pkg.applicationInfo.processName = fixProcessName(
6921                pkg.applicationInfo.packageName,
6922                pkg.applicationInfo.processName,
6923                pkg.applicationInfo.uid);
6924
6925        File dataPath;
6926        if (mPlatformPackage == pkg) {
6927            // The system package is special.
6928            dataPath = new File(Environment.getDataDirectory(), "system");
6929
6930            pkg.applicationInfo.dataDir = dataPath.getPath();
6931
6932        } else {
6933            // This is a normal package, need to make its data directory.
6934            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6935                    UserHandle.USER_OWNER, pkg.packageName);
6936
6937            boolean uidError = false;
6938            if (dataPath.exists()) {
6939                int currentUid = 0;
6940                try {
6941                    StructStat stat = Os.stat(dataPath.getPath());
6942                    currentUid = stat.st_uid;
6943                } catch (ErrnoException e) {
6944                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6945                }
6946
6947                // If we have mismatched owners for the data path, we have a problem.
6948                if (currentUid != pkg.applicationInfo.uid) {
6949                    boolean recovered = false;
6950                    if (currentUid == 0) {
6951                        // The directory somehow became owned by root.  Wow.
6952                        // This is probably because the system was stopped while
6953                        // installd was in the middle of messing with its libs
6954                        // directory.  Ask installd to fix that.
6955                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6956                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6957                        if (ret >= 0) {
6958                            recovered = true;
6959                            String msg = "Package " + pkg.packageName
6960                                    + " unexpectedly changed to uid 0; recovered to " +
6961                                    + pkg.applicationInfo.uid;
6962                            reportSettingsProblem(Log.WARN, msg);
6963                        }
6964                    }
6965                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6966                            || (scanFlags&SCAN_BOOTING) != 0)) {
6967                        // If this is a system app, we can at least delete its
6968                        // current data so the application will still work.
6969                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6970                        if (ret >= 0) {
6971                            // TODO: Kill the processes first
6972                            // Old data gone!
6973                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6974                                    ? "System package " : "Third party package ";
6975                            String msg = prefix + pkg.packageName
6976                                    + " has changed from uid: "
6977                                    + currentUid + " to "
6978                                    + pkg.applicationInfo.uid + "; old data erased";
6979                            reportSettingsProblem(Log.WARN, msg);
6980                            recovered = true;
6981
6982                            // And now re-install the app.
6983                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6984                                    pkg.applicationInfo.seinfo);
6985                            if (ret == -1) {
6986                                // Ack should not happen!
6987                                msg = prefix + pkg.packageName
6988                                        + " could not have data directory re-created after delete.";
6989                                reportSettingsProblem(Log.WARN, msg);
6990                                throw new PackageManagerException(
6991                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6992                            }
6993                        }
6994                        if (!recovered) {
6995                            mHasSystemUidErrors = true;
6996                        }
6997                    } else if (!recovered) {
6998                        // If we allow this install to proceed, we will be broken.
6999                        // Abort, abort!
7000                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7001                                "scanPackageLI");
7002                    }
7003                    if (!recovered) {
7004                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7005                            + pkg.applicationInfo.uid + "/fs_"
7006                            + currentUid;
7007                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7008                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7009                        String msg = "Package " + pkg.packageName
7010                                + " has mismatched uid: "
7011                                + currentUid + " on disk, "
7012                                + pkg.applicationInfo.uid + " in settings";
7013                        // writer
7014                        synchronized (mPackages) {
7015                            mSettings.mReadMessages.append(msg);
7016                            mSettings.mReadMessages.append('\n');
7017                            uidError = true;
7018                            if (!pkgSetting.uidError) {
7019                                reportSettingsProblem(Log.ERROR, msg);
7020                            }
7021                        }
7022                    }
7023                }
7024                pkg.applicationInfo.dataDir = dataPath.getPath();
7025                if (mShouldRestoreconData) {
7026                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7027                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7028                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7029                }
7030            } else {
7031                if (DEBUG_PACKAGE_SCANNING) {
7032                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7033                        Log.v(TAG, "Want this data dir: " + dataPath);
7034                }
7035                //invoke installer to do the actual installation
7036                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7037                        pkg.applicationInfo.seinfo);
7038                if (ret < 0) {
7039                    // Error from installer
7040                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7041                            "Unable to create data dirs [errorCode=" + ret + "]");
7042                }
7043
7044                if (dataPath.exists()) {
7045                    pkg.applicationInfo.dataDir = dataPath.getPath();
7046                } else {
7047                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
7048                    pkg.applicationInfo.dataDir = null;
7049                }
7050            }
7051
7052            pkgSetting.uidError = uidError;
7053        }
7054
7055        final String path = scanFile.getPath();
7056        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7057
7058        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7059            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7060
7061            // Some system apps still use directory structure for native libraries
7062            // in which case we might end up not detecting abi solely based on apk
7063            // structure. Try to detect abi based on directory structure.
7064            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7065                    pkg.applicationInfo.primaryCpuAbi == null) {
7066                setBundledAppAbisAndRoots(pkg, pkgSetting);
7067                setNativeLibraryPaths(pkg);
7068            }
7069
7070        } else {
7071            if ((scanFlags & SCAN_MOVE) != 0) {
7072                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7073                // but we already have this packages package info in the PackageSetting. We just
7074                // use that and derive the native library path based on the new codepath.
7075                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7076                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7077            }
7078
7079            // Set native library paths again. For moves, the path will be updated based on the
7080            // ABIs we've determined above. For non-moves, the path will be updated based on the
7081            // ABIs we determined during compilation, but the path will depend on the final
7082            // package path (after the rename away from the stage path).
7083            setNativeLibraryPaths(pkg);
7084        }
7085
7086        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7087        final int[] userIds = sUserManager.getUserIds();
7088        synchronized (mInstallLock) {
7089            // Make sure all user data directories are ready to roll; we're okay
7090            // if they already exist
7091            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7092                for (int userId : userIds) {
7093                    if (userId != 0) {
7094                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7095                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7096                                pkg.applicationInfo.seinfo);
7097                    }
7098                }
7099            }
7100
7101            // Create a native library symlink only if we have native libraries
7102            // and if the native libraries are 32 bit libraries. We do not provide
7103            // this symlink for 64 bit libraries.
7104            if (pkg.applicationInfo.primaryCpuAbi != null &&
7105                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7106                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7107                try {
7108                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7109                    for (int userId : userIds) {
7110                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7111                                nativeLibPath, userId) < 0) {
7112                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7113                                    "Failed linking native library dir (user=" + userId + ")");
7114                        }
7115                    }
7116                } finally {
7117                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7118                }
7119            }
7120        }
7121
7122        // This is a special case for the "system" package, where the ABI is
7123        // dictated by the zygote configuration (and init.rc). We should keep track
7124        // of this ABI so that we can deal with "normal" applications that run under
7125        // the same UID correctly.
7126        if (mPlatformPackage == pkg) {
7127            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7128                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7129        }
7130
7131        // If there's a mismatch between the abi-override in the package setting
7132        // and the abiOverride specified for the install. Warn about this because we
7133        // would've already compiled the app without taking the package setting into
7134        // account.
7135        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7136            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7137                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7138                        " for package: " + pkg.packageName);
7139            }
7140        }
7141
7142        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7143        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7144        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7145
7146        // Copy the derived override back to the parsed package, so that we can
7147        // update the package settings accordingly.
7148        pkg.cpuAbiOverride = cpuAbiOverride;
7149
7150        if (DEBUG_ABI_SELECTION) {
7151            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7152                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7153                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7154        }
7155
7156        // Push the derived path down into PackageSettings so we know what to
7157        // clean up at uninstall time.
7158        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7159
7160        if (DEBUG_ABI_SELECTION) {
7161            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7162                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7163                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7164        }
7165
7166        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7167            // We don't do this here during boot because we can do it all
7168            // at once after scanning all existing packages.
7169            //
7170            // We also do this *before* we perform dexopt on this package, so that
7171            // we can avoid redundant dexopts, and also to make sure we've got the
7172            // code and package path correct.
7173            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7174                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */);
7175        }
7176
7177        if ((scanFlags & SCAN_NO_DEX) == 0) {
7178            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7179
7180            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7181                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */,
7182                    (scanFlags & SCAN_BOOTING) == 0);
7183
7184            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7185            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7186                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7187            }
7188        }
7189        if (mFactoryTest && pkg.requestedPermissions.contains(
7190                android.Manifest.permission.FACTORY_TEST)) {
7191            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7192        }
7193
7194        ArrayList<PackageParser.Package> clientLibPkgs = null;
7195
7196        // writer
7197        synchronized (mPackages) {
7198            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7199                // Only system apps can add new shared libraries.
7200                if (pkg.libraryNames != null) {
7201                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7202                        String name = pkg.libraryNames.get(i);
7203                        boolean allowed = false;
7204                        if (pkg.isUpdatedSystemApp()) {
7205                            // New library entries can only be added through the
7206                            // system image.  This is important to get rid of a lot
7207                            // of nasty edge cases: for example if we allowed a non-
7208                            // system update of the app to add a library, then uninstalling
7209                            // the update would make the library go away, and assumptions
7210                            // we made such as through app install filtering would now
7211                            // have allowed apps on the device which aren't compatible
7212                            // with it.  Better to just have the restriction here, be
7213                            // conservative, and create many fewer cases that can negatively
7214                            // impact the user experience.
7215                            final PackageSetting sysPs = mSettings
7216                                    .getDisabledSystemPkgLPr(pkg.packageName);
7217                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7218                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7219                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7220                                        allowed = true;
7221                                        allowed = true;
7222                                        break;
7223                                    }
7224                                }
7225                            }
7226                        } else {
7227                            allowed = true;
7228                        }
7229                        if (allowed) {
7230                            if (!mSharedLibraries.containsKey(name)) {
7231                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7232                            } else if (!name.equals(pkg.packageName)) {
7233                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7234                                        + name + " already exists; skipping");
7235                            }
7236                        } else {
7237                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7238                                    + name + " that is not declared on system image; skipping");
7239                        }
7240                    }
7241                    if ((scanFlags&SCAN_BOOTING) == 0) {
7242                        // If we are not booting, we need to update any applications
7243                        // that are clients of our shared library.  If we are booting,
7244                        // this will all be done once the scan is complete.
7245                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7246                    }
7247                }
7248            }
7249        }
7250
7251        // We also need to dexopt any apps that are dependent on this library.  Note that
7252        // if these fail, we should abort the install since installing the library will
7253        // result in some apps being broken.
7254        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7255        try {
7256            if (clientLibPkgs != null) {
7257                if ((scanFlags & SCAN_NO_DEX) == 0) {
7258                    for (int i = 0; i < clientLibPkgs.size(); i++) {
7259                        PackageParser.Package clientPkg = clientLibPkgs.get(i);
7260                        int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7261                                null /* instruction sets */, forceDex,
7262                                (scanFlags & SCAN_DEFER_DEX) != 0, false,
7263                                (scanFlags & SCAN_BOOTING) == 0);
7264                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7265                            throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7266                                    "scanPackageLI failed to dexopt clientLibPkgs");
7267                        }
7268                    }
7269                }
7270            }
7271        } finally {
7272            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7273        }
7274
7275        // Request the ActivityManager to kill the process(only for existing packages)
7276        // so that we do not end up in a confused state while the user is still using the older
7277        // version of the application while the new one gets installed.
7278        if ((scanFlags & SCAN_REPLACING) != 0) {
7279            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7280
7281            killApplication(pkg.applicationInfo.packageName,
7282                        pkg.applicationInfo.uid, "replace pkg");
7283
7284            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7285        }
7286
7287        // Also need to kill any apps that are dependent on the library.
7288        if (clientLibPkgs != null) {
7289            for (int i=0; i<clientLibPkgs.size(); i++) {
7290                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7291                killApplication(clientPkg.applicationInfo.packageName,
7292                        clientPkg.applicationInfo.uid, "update lib");
7293            }
7294        }
7295
7296        // Make sure we're not adding any bogus keyset info
7297        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7298        ksms.assertScannedPackageValid(pkg);
7299
7300        // writer
7301        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7302
7303        boolean createIdmapFailed = false;
7304        synchronized (mPackages) {
7305            // We don't expect installation to fail beyond this point
7306
7307            // Add the new setting to mSettings
7308            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7309            // Add the new setting to mPackages
7310            mPackages.put(pkg.applicationInfo.packageName, pkg);
7311            // Make sure we don't accidentally delete its data.
7312            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7313            while (iter.hasNext()) {
7314                PackageCleanItem item = iter.next();
7315                if (pkgName.equals(item.packageName)) {
7316                    iter.remove();
7317                }
7318            }
7319
7320            // Take care of first install / last update times.
7321            if (currentTime != 0) {
7322                if (pkgSetting.firstInstallTime == 0) {
7323                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7324                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7325                    pkgSetting.lastUpdateTime = currentTime;
7326                }
7327            } else if (pkgSetting.firstInstallTime == 0) {
7328                // We need *something*.  Take time time stamp of the file.
7329                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7330            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7331                if (scanFileTime != pkgSetting.timeStamp) {
7332                    // A package on the system image has changed; consider this
7333                    // to be an update.
7334                    pkgSetting.lastUpdateTime = scanFileTime;
7335                }
7336            }
7337
7338            // Add the package's KeySets to the global KeySetManagerService
7339            ksms.addScannedPackageLPw(pkg);
7340
7341            int N = pkg.providers.size();
7342            StringBuilder r = null;
7343            int i;
7344            for (i=0; i<N; i++) {
7345                PackageParser.Provider p = pkg.providers.get(i);
7346                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7347                        p.info.processName, pkg.applicationInfo.uid);
7348                mProviders.addProvider(p);
7349                p.syncable = p.info.isSyncable;
7350                if (p.info.authority != null) {
7351                    String names[] = p.info.authority.split(";");
7352                    p.info.authority = null;
7353                    for (int j = 0; j < names.length; j++) {
7354                        if (j == 1 && p.syncable) {
7355                            // We only want the first authority for a provider to possibly be
7356                            // syncable, so if we already added this provider using a different
7357                            // authority clear the syncable flag. We copy the provider before
7358                            // changing it because the mProviders object contains a reference
7359                            // to a provider that we don't want to change.
7360                            // Only do this for the second authority since the resulting provider
7361                            // object can be the same for all future authorities for this provider.
7362                            p = new PackageParser.Provider(p);
7363                            p.syncable = false;
7364                        }
7365                        if (!mProvidersByAuthority.containsKey(names[j])) {
7366                            mProvidersByAuthority.put(names[j], p);
7367                            if (p.info.authority == null) {
7368                                p.info.authority = names[j];
7369                            } else {
7370                                p.info.authority = p.info.authority + ";" + names[j];
7371                            }
7372                            if (DEBUG_PACKAGE_SCANNING) {
7373                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7374                                    Log.d(TAG, "Registered content provider: " + names[j]
7375                                            + ", className = " + p.info.name + ", isSyncable = "
7376                                            + p.info.isSyncable);
7377                            }
7378                        } else {
7379                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7380                            Slog.w(TAG, "Skipping provider name " + names[j] +
7381                                    " (in package " + pkg.applicationInfo.packageName +
7382                                    "): name already used by "
7383                                    + ((other != null && other.getComponentName() != null)
7384                                            ? other.getComponentName().getPackageName() : "?"));
7385                        }
7386                    }
7387                }
7388                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7389                    if (r == null) {
7390                        r = new StringBuilder(256);
7391                    } else {
7392                        r.append(' ');
7393                    }
7394                    r.append(p.info.name);
7395                }
7396            }
7397            if (r != null) {
7398                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7399            }
7400
7401            N = pkg.services.size();
7402            r = null;
7403            for (i=0; i<N; i++) {
7404                PackageParser.Service s = pkg.services.get(i);
7405                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7406                        s.info.processName, pkg.applicationInfo.uid);
7407                mServices.addService(s);
7408                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7409                    if (r == null) {
7410                        r = new StringBuilder(256);
7411                    } else {
7412                        r.append(' ');
7413                    }
7414                    r.append(s.info.name);
7415                }
7416            }
7417            if (r != null) {
7418                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7419            }
7420
7421            N = pkg.receivers.size();
7422            r = null;
7423            for (i=0; i<N; i++) {
7424                PackageParser.Activity a = pkg.receivers.get(i);
7425                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7426                        a.info.processName, pkg.applicationInfo.uid);
7427                mReceivers.addActivity(a, "receiver");
7428                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7429                    if (r == null) {
7430                        r = new StringBuilder(256);
7431                    } else {
7432                        r.append(' ');
7433                    }
7434                    r.append(a.info.name);
7435                }
7436            }
7437            if (r != null) {
7438                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7439            }
7440
7441            N = pkg.activities.size();
7442            r = null;
7443            for (i=0; i<N; i++) {
7444                PackageParser.Activity a = pkg.activities.get(i);
7445                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7446                        a.info.processName, pkg.applicationInfo.uid);
7447                mActivities.addActivity(a, "activity");
7448                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7449                    if (r == null) {
7450                        r = new StringBuilder(256);
7451                    } else {
7452                        r.append(' ');
7453                    }
7454                    r.append(a.info.name);
7455                }
7456            }
7457            if (r != null) {
7458                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7459            }
7460
7461            N = pkg.permissionGroups.size();
7462            r = null;
7463            for (i=0; i<N; i++) {
7464                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7465                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7466                if (cur == null) {
7467                    mPermissionGroups.put(pg.info.name, pg);
7468                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7469                        if (r == null) {
7470                            r = new StringBuilder(256);
7471                        } else {
7472                            r.append(' ');
7473                        }
7474                        r.append(pg.info.name);
7475                    }
7476                } else {
7477                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7478                            + pg.info.packageName + " ignored: original from "
7479                            + cur.info.packageName);
7480                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7481                        if (r == null) {
7482                            r = new StringBuilder(256);
7483                        } else {
7484                            r.append(' ');
7485                        }
7486                        r.append("DUP:");
7487                        r.append(pg.info.name);
7488                    }
7489                }
7490            }
7491            if (r != null) {
7492                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7493            }
7494
7495            N = pkg.permissions.size();
7496            r = null;
7497            for (i=0; i<N; i++) {
7498                PackageParser.Permission p = pkg.permissions.get(i);
7499
7500                // Assume by default that we did not install this permission into the system.
7501                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7502
7503                // Now that permission groups have a special meaning, we ignore permission
7504                // groups for legacy apps to prevent unexpected behavior. In particular,
7505                // permissions for one app being granted to someone just becuase they happen
7506                // to be in a group defined by another app (before this had no implications).
7507                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7508                    p.group = mPermissionGroups.get(p.info.group);
7509                    // Warn for a permission in an unknown group.
7510                    if (p.info.group != null && p.group == null) {
7511                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7512                                + p.info.packageName + " in an unknown group " + p.info.group);
7513                    }
7514                }
7515
7516                ArrayMap<String, BasePermission> permissionMap =
7517                        p.tree ? mSettings.mPermissionTrees
7518                                : mSettings.mPermissions;
7519                BasePermission bp = permissionMap.get(p.info.name);
7520
7521                // Allow system apps to redefine non-system permissions
7522                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7523                    final boolean currentOwnerIsSystem = (bp.perm != null
7524                            && isSystemApp(bp.perm.owner));
7525                    if (isSystemApp(p.owner)) {
7526                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7527                            // It's a built-in permission and no owner, take ownership now
7528                            bp.packageSetting = pkgSetting;
7529                            bp.perm = p;
7530                            bp.uid = pkg.applicationInfo.uid;
7531                            bp.sourcePackage = p.info.packageName;
7532                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7533                        } else if (!currentOwnerIsSystem) {
7534                            String msg = "New decl " + p.owner + " of permission  "
7535                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7536                            reportSettingsProblem(Log.WARN, msg);
7537                            bp = null;
7538                        }
7539                    }
7540                }
7541
7542                if (bp == null) {
7543                    bp = new BasePermission(p.info.name, p.info.packageName,
7544                            BasePermission.TYPE_NORMAL);
7545                    permissionMap.put(p.info.name, bp);
7546                }
7547
7548                if (bp.perm == null) {
7549                    if (bp.sourcePackage == null
7550                            || bp.sourcePackage.equals(p.info.packageName)) {
7551                        BasePermission tree = findPermissionTreeLP(p.info.name);
7552                        if (tree == null
7553                                || tree.sourcePackage.equals(p.info.packageName)) {
7554                            bp.packageSetting = pkgSetting;
7555                            bp.perm = p;
7556                            bp.uid = pkg.applicationInfo.uid;
7557                            bp.sourcePackage = p.info.packageName;
7558                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7559                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7560                                if (r == null) {
7561                                    r = new StringBuilder(256);
7562                                } else {
7563                                    r.append(' ');
7564                                }
7565                                r.append(p.info.name);
7566                            }
7567                        } else {
7568                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7569                                    + p.info.packageName + " ignored: base tree "
7570                                    + tree.name + " is from package "
7571                                    + tree.sourcePackage);
7572                        }
7573                    } else {
7574                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7575                                + p.info.packageName + " ignored: original from "
7576                                + bp.sourcePackage);
7577                    }
7578                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7579                    if (r == null) {
7580                        r = new StringBuilder(256);
7581                    } else {
7582                        r.append(' ');
7583                    }
7584                    r.append("DUP:");
7585                    r.append(p.info.name);
7586                }
7587                if (bp.perm == p) {
7588                    bp.protectionLevel = p.info.protectionLevel;
7589                }
7590            }
7591
7592            if (r != null) {
7593                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7594            }
7595
7596            N = pkg.instrumentation.size();
7597            r = null;
7598            for (i=0; i<N; i++) {
7599                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7600                a.info.packageName = pkg.applicationInfo.packageName;
7601                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7602                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7603                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7604                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7605                a.info.dataDir = pkg.applicationInfo.dataDir;
7606
7607                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7608                // need other information about the application, like the ABI and what not ?
7609                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7610                mInstrumentation.put(a.getComponentName(), a);
7611                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7612                    if (r == null) {
7613                        r = new StringBuilder(256);
7614                    } else {
7615                        r.append(' ');
7616                    }
7617                    r.append(a.info.name);
7618                }
7619            }
7620            if (r != null) {
7621                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7622            }
7623
7624            if (pkg.protectedBroadcasts != null) {
7625                N = pkg.protectedBroadcasts.size();
7626                for (i=0; i<N; i++) {
7627                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7628                }
7629            }
7630
7631            pkgSetting.setTimeStamp(scanFileTime);
7632
7633            // Create idmap files for pairs of (packages, overlay packages).
7634            // Note: "android", ie framework-res.apk, is handled by native layers.
7635            if (pkg.mOverlayTarget != null) {
7636                // This is an overlay package.
7637                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7638                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7639                        mOverlays.put(pkg.mOverlayTarget,
7640                                new ArrayMap<String, PackageParser.Package>());
7641                    }
7642                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7643                    map.put(pkg.packageName, pkg);
7644                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7645                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7646                        createIdmapFailed = true;
7647                    }
7648                }
7649            } else if (mOverlays.containsKey(pkg.packageName) &&
7650                    !pkg.packageName.equals("android")) {
7651                // This is a regular package, with one or more known overlay packages.
7652                createIdmapsForPackageLI(pkg);
7653            }
7654        }
7655
7656        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7657
7658        if (createIdmapFailed) {
7659            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7660                    "scanPackageLI failed to createIdmap");
7661        }
7662        return pkg;
7663    }
7664
7665    /**
7666     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7667     * is derived purely on the basis of the contents of {@code scanFile} and
7668     * {@code cpuAbiOverride}.
7669     *
7670     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7671     */
7672    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7673                                 String cpuAbiOverride, boolean extractLibs)
7674            throws PackageManagerException {
7675        // TODO: We can probably be smarter about this stuff. For installed apps,
7676        // we can calculate this information at install time once and for all. For
7677        // system apps, we can probably assume that this information doesn't change
7678        // after the first boot scan. As things stand, we do lots of unnecessary work.
7679
7680        // Give ourselves some initial paths; we'll come back for another
7681        // pass once we've determined ABI below.
7682        setNativeLibraryPaths(pkg);
7683
7684        // We would never need to extract libs for forward-locked and external packages,
7685        // since the container service will do it for us. We shouldn't attempt to
7686        // extract libs from system app when it was not updated.
7687        if (pkg.isForwardLocked() || isExternal(pkg) ||
7688            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7689            extractLibs = false;
7690        }
7691
7692        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7693        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7694
7695        NativeLibraryHelper.Handle handle = null;
7696        try {
7697            handle = NativeLibraryHelper.Handle.create(pkg);
7698            // TODO(multiArch): This can be null for apps that didn't go through the
7699            // usual installation process. We can calculate it again, like we
7700            // do during install time.
7701            //
7702            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7703            // unnecessary.
7704            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7705
7706            // Null out the abis so that they can be recalculated.
7707            pkg.applicationInfo.primaryCpuAbi = null;
7708            pkg.applicationInfo.secondaryCpuAbi = null;
7709            if (isMultiArch(pkg.applicationInfo)) {
7710                // Warn if we've set an abiOverride for multi-lib packages..
7711                // By definition, we need to copy both 32 and 64 bit libraries for
7712                // such packages.
7713                if (pkg.cpuAbiOverride != null
7714                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7715                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7716                }
7717
7718                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7719                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7720                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7721                    if (extractLibs) {
7722                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7723                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7724                                useIsaSpecificSubdirs);
7725                    } else {
7726                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7727                    }
7728                }
7729
7730                maybeThrowExceptionForMultiArchCopy(
7731                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7732
7733                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7734                    if (extractLibs) {
7735                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7736                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7737                                useIsaSpecificSubdirs);
7738                    } else {
7739                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7740                    }
7741                }
7742
7743                maybeThrowExceptionForMultiArchCopy(
7744                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7745
7746                if (abi64 >= 0) {
7747                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7748                }
7749
7750                if (abi32 >= 0) {
7751                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7752                    if (abi64 >= 0) {
7753                        pkg.applicationInfo.secondaryCpuAbi = abi;
7754                    } else {
7755                        pkg.applicationInfo.primaryCpuAbi = abi;
7756                    }
7757                }
7758            } else {
7759                String[] abiList = (cpuAbiOverride != null) ?
7760                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7761
7762                // Enable gross and lame hacks for apps that are built with old
7763                // SDK tools. We must scan their APKs for renderscript bitcode and
7764                // not launch them if it's present. Don't bother checking on devices
7765                // that don't have 64 bit support.
7766                boolean needsRenderScriptOverride = false;
7767                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7768                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7769                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7770                    needsRenderScriptOverride = true;
7771                }
7772
7773                final int copyRet;
7774                if (extractLibs) {
7775                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7776                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7777                } else {
7778                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7779                }
7780
7781                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7782                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7783                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7784                }
7785
7786                if (copyRet >= 0) {
7787                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7788                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7789                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7790                } else if (needsRenderScriptOverride) {
7791                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7792                }
7793            }
7794        } catch (IOException ioe) {
7795            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7796        } finally {
7797            IoUtils.closeQuietly(handle);
7798        }
7799
7800        // Now that we've calculated the ABIs and determined if it's an internal app,
7801        // we will go ahead and populate the nativeLibraryPath.
7802        setNativeLibraryPaths(pkg);
7803    }
7804
7805    /**
7806     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7807     * i.e, so that all packages can be run inside a single process if required.
7808     *
7809     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7810     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7811     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7812     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7813     * updating a package that belongs to a shared user.
7814     *
7815     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7816     * adds unnecessary complexity.
7817     */
7818    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7819            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt,
7820            boolean bootComplete) {
7821        String requiredInstructionSet = null;
7822        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7823            requiredInstructionSet = VMRuntime.getInstructionSet(
7824                     scannedPackage.applicationInfo.primaryCpuAbi);
7825        }
7826
7827        PackageSetting requirer = null;
7828        for (PackageSetting ps : packagesForUser) {
7829            // If packagesForUser contains scannedPackage, we skip it. This will happen
7830            // when scannedPackage is an update of an existing package. Without this check,
7831            // we will never be able to change the ABI of any package belonging to a shared
7832            // user, even if it's compatible with other packages.
7833            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7834                if (ps.primaryCpuAbiString == null) {
7835                    continue;
7836                }
7837
7838                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7839                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7840                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7841                    // this but there's not much we can do.
7842                    String errorMessage = "Instruction set mismatch, "
7843                            + ((requirer == null) ? "[caller]" : requirer)
7844                            + " requires " + requiredInstructionSet + " whereas " + ps
7845                            + " requires " + instructionSet;
7846                    Slog.w(TAG, errorMessage);
7847                }
7848
7849                if (requiredInstructionSet == null) {
7850                    requiredInstructionSet = instructionSet;
7851                    requirer = ps;
7852                }
7853            }
7854        }
7855
7856        if (requiredInstructionSet != null) {
7857            String adjustedAbi;
7858            if (requirer != null) {
7859                // requirer != null implies that either scannedPackage was null or that scannedPackage
7860                // did not require an ABI, in which case we have to adjust scannedPackage to match
7861                // the ABI of the set (which is the same as requirer's ABI)
7862                adjustedAbi = requirer.primaryCpuAbiString;
7863                if (scannedPackage != null) {
7864                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7865                }
7866            } else {
7867                // requirer == null implies that we're updating all ABIs in the set to
7868                // match scannedPackage.
7869                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7870            }
7871
7872            for (PackageSetting ps : packagesForUser) {
7873                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7874                    if (ps.primaryCpuAbiString != null) {
7875                        continue;
7876                    }
7877
7878                    ps.primaryCpuAbiString = adjustedAbi;
7879                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7880                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7881                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7882
7883                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7884
7885                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7886                                null /* instruction sets */, forceDexOpt, deferDexOpt, true,
7887                                bootComplete);
7888
7889                        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7890                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7891                            ps.primaryCpuAbiString = null;
7892                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7893                            return;
7894                        } else {
7895                            mInstaller.rmdex(ps.codePathString,
7896                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7897                        }
7898                    }
7899                }
7900            }
7901        }
7902    }
7903
7904    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7905        synchronized (mPackages) {
7906            mResolverReplaced = true;
7907            // Set up information for custom user intent resolution activity.
7908            mResolveActivity.applicationInfo = pkg.applicationInfo;
7909            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7910            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7911            mResolveActivity.processName = pkg.applicationInfo.packageName;
7912            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7913            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7914                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7915            mResolveActivity.theme = 0;
7916            mResolveActivity.exported = true;
7917            mResolveActivity.enabled = true;
7918            mResolveInfo.activityInfo = mResolveActivity;
7919            mResolveInfo.priority = 0;
7920            mResolveInfo.preferredOrder = 0;
7921            mResolveInfo.match = 0;
7922            mResolveComponentName = mCustomResolverComponentName;
7923            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7924                    mResolveComponentName);
7925        }
7926    }
7927
7928    private static String calculateBundledApkRoot(final String codePathString) {
7929        final File codePath = new File(codePathString);
7930        final File codeRoot;
7931        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7932            codeRoot = Environment.getRootDirectory();
7933        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7934            codeRoot = Environment.getOemDirectory();
7935        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7936            codeRoot = Environment.getVendorDirectory();
7937        } else {
7938            // Unrecognized code path; take its top real segment as the apk root:
7939            // e.g. /something/app/blah.apk => /something
7940            try {
7941                File f = codePath.getCanonicalFile();
7942                File parent = f.getParentFile();    // non-null because codePath is a file
7943                File tmp;
7944                while ((tmp = parent.getParentFile()) != null) {
7945                    f = parent;
7946                    parent = tmp;
7947                }
7948                codeRoot = f;
7949                Slog.w(TAG, "Unrecognized code path "
7950                        + codePath + " - using " + codeRoot);
7951            } catch (IOException e) {
7952                // Can't canonicalize the code path -- shenanigans?
7953                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7954                return Environment.getRootDirectory().getPath();
7955            }
7956        }
7957        return codeRoot.getPath();
7958    }
7959
7960    /**
7961     * Derive and set the location of native libraries for the given package,
7962     * which varies depending on where and how the package was installed.
7963     */
7964    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7965        final ApplicationInfo info = pkg.applicationInfo;
7966        final String codePath = pkg.codePath;
7967        final File codeFile = new File(codePath);
7968        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7969        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7970
7971        info.nativeLibraryRootDir = null;
7972        info.nativeLibraryRootRequiresIsa = false;
7973        info.nativeLibraryDir = null;
7974        info.secondaryNativeLibraryDir = null;
7975
7976        if (isApkFile(codeFile)) {
7977            // Monolithic install
7978            if (bundledApp) {
7979                // If "/system/lib64/apkname" exists, assume that is the per-package
7980                // native library directory to use; otherwise use "/system/lib/apkname".
7981                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7982                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7983                        getPrimaryInstructionSet(info));
7984
7985                // This is a bundled system app so choose the path based on the ABI.
7986                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7987                // is just the default path.
7988                final String apkName = deriveCodePathName(codePath);
7989                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7990                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7991                        apkName).getAbsolutePath();
7992
7993                if (info.secondaryCpuAbi != null) {
7994                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7995                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7996                            secondaryLibDir, apkName).getAbsolutePath();
7997                }
7998            } else if (asecApp) {
7999                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8000                        .getAbsolutePath();
8001            } else {
8002                final String apkName = deriveCodePathName(codePath);
8003                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8004                        .getAbsolutePath();
8005            }
8006
8007            info.nativeLibraryRootRequiresIsa = false;
8008            info.nativeLibraryDir = info.nativeLibraryRootDir;
8009        } else {
8010            // Cluster install
8011            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8012            info.nativeLibraryRootRequiresIsa = true;
8013
8014            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8015                    getPrimaryInstructionSet(info)).getAbsolutePath();
8016
8017            if (info.secondaryCpuAbi != null) {
8018                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8019                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8020            }
8021        }
8022    }
8023
8024    /**
8025     * Calculate the abis and roots for a bundled app. These can uniquely
8026     * be determined from the contents of the system partition, i.e whether
8027     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8028     * of this information, and instead assume that the system was built
8029     * sensibly.
8030     */
8031    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8032                                           PackageSetting pkgSetting) {
8033        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8034
8035        // If "/system/lib64/apkname" exists, assume that is the per-package
8036        // native library directory to use; otherwise use "/system/lib/apkname".
8037        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8038        setBundledAppAbi(pkg, apkRoot, apkName);
8039        // pkgSetting might be null during rescan following uninstall of updates
8040        // to a bundled app, so accommodate that possibility.  The settings in
8041        // that case will be established later from the parsed package.
8042        //
8043        // If the settings aren't null, sync them up with what we've just derived.
8044        // note that apkRoot isn't stored in the package settings.
8045        if (pkgSetting != null) {
8046            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8047            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8048        }
8049    }
8050
8051    /**
8052     * Deduces the ABI of a bundled app and sets the relevant fields on the
8053     * parsed pkg object.
8054     *
8055     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8056     *        under which system libraries are installed.
8057     * @param apkName the name of the installed package.
8058     */
8059    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8060        final File codeFile = new File(pkg.codePath);
8061
8062        final boolean has64BitLibs;
8063        final boolean has32BitLibs;
8064        if (isApkFile(codeFile)) {
8065            // Monolithic install
8066            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8067            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8068        } else {
8069            // Cluster install
8070            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8071            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8072                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8073                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8074                has64BitLibs = (new File(rootDir, isa)).exists();
8075            } else {
8076                has64BitLibs = false;
8077            }
8078            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8079                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8080                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8081                has32BitLibs = (new File(rootDir, isa)).exists();
8082            } else {
8083                has32BitLibs = false;
8084            }
8085        }
8086
8087        if (has64BitLibs && !has32BitLibs) {
8088            // The package has 64 bit libs, but not 32 bit libs. Its primary
8089            // ABI should be 64 bit. We can safely assume here that the bundled
8090            // native libraries correspond to the most preferred ABI in the list.
8091
8092            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8093            pkg.applicationInfo.secondaryCpuAbi = null;
8094        } else if (has32BitLibs && !has64BitLibs) {
8095            // The package has 32 bit libs but not 64 bit libs. Its primary
8096            // ABI should be 32 bit.
8097
8098            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8099            pkg.applicationInfo.secondaryCpuAbi = null;
8100        } else if (has32BitLibs && has64BitLibs) {
8101            // The application has both 64 and 32 bit bundled libraries. We check
8102            // here that the app declares multiArch support, and warn if it doesn't.
8103            //
8104            // We will be lenient here and record both ABIs. The primary will be the
8105            // ABI that's higher on the list, i.e, a device that's configured to prefer
8106            // 64 bit apps will see a 64 bit primary ABI,
8107
8108            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8109                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8110            }
8111
8112            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8113                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8114                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8115            } else {
8116                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8117                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8118            }
8119        } else {
8120            pkg.applicationInfo.primaryCpuAbi = null;
8121            pkg.applicationInfo.secondaryCpuAbi = null;
8122        }
8123    }
8124
8125    private void killApplication(String pkgName, int appId, String reason) {
8126        // Request the ActivityManager to kill the process(only for existing packages)
8127        // so that we do not end up in a confused state while the user is still using the older
8128        // version of the application while the new one gets installed.
8129        IActivityManager am = ActivityManagerNative.getDefault();
8130        if (am != null) {
8131            try {
8132                am.killApplicationWithAppId(pkgName, appId, reason);
8133            } catch (RemoteException e) {
8134            }
8135        }
8136    }
8137
8138    void removePackageLI(PackageSetting ps, boolean chatty) {
8139        if (DEBUG_INSTALL) {
8140            if (chatty)
8141                Log.d(TAG, "Removing package " + ps.name);
8142        }
8143
8144        // writer
8145        synchronized (mPackages) {
8146            mPackages.remove(ps.name);
8147            final PackageParser.Package pkg = ps.pkg;
8148            if (pkg != null) {
8149                cleanPackageDataStructuresLILPw(pkg, chatty);
8150            }
8151        }
8152    }
8153
8154    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8155        if (DEBUG_INSTALL) {
8156            if (chatty)
8157                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8158        }
8159
8160        // writer
8161        synchronized (mPackages) {
8162            mPackages.remove(pkg.applicationInfo.packageName);
8163            cleanPackageDataStructuresLILPw(pkg, chatty);
8164        }
8165    }
8166
8167    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8168        int N = pkg.providers.size();
8169        StringBuilder r = null;
8170        int i;
8171        for (i=0; i<N; i++) {
8172            PackageParser.Provider p = pkg.providers.get(i);
8173            mProviders.removeProvider(p);
8174            if (p.info.authority == null) {
8175
8176                /* There was another ContentProvider with this authority when
8177                 * this app was installed so this authority is null,
8178                 * Ignore it as we don't have to unregister the provider.
8179                 */
8180                continue;
8181            }
8182            String names[] = p.info.authority.split(";");
8183            for (int j = 0; j < names.length; j++) {
8184                if (mProvidersByAuthority.get(names[j]) == p) {
8185                    mProvidersByAuthority.remove(names[j]);
8186                    if (DEBUG_REMOVE) {
8187                        if (chatty)
8188                            Log.d(TAG, "Unregistered content provider: " + names[j]
8189                                    + ", className = " + p.info.name + ", isSyncable = "
8190                                    + p.info.isSyncable);
8191                    }
8192                }
8193            }
8194            if (DEBUG_REMOVE && chatty) {
8195                if (r == null) {
8196                    r = new StringBuilder(256);
8197                } else {
8198                    r.append(' ');
8199                }
8200                r.append(p.info.name);
8201            }
8202        }
8203        if (r != null) {
8204            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8205        }
8206
8207        N = pkg.services.size();
8208        r = null;
8209        for (i=0; i<N; i++) {
8210            PackageParser.Service s = pkg.services.get(i);
8211            mServices.removeService(s);
8212            if (chatty) {
8213                if (r == null) {
8214                    r = new StringBuilder(256);
8215                } else {
8216                    r.append(' ');
8217                }
8218                r.append(s.info.name);
8219            }
8220        }
8221        if (r != null) {
8222            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8223        }
8224
8225        N = pkg.receivers.size();
8226        r = null;
8227        for (i=0; i<N; i++) {
8228            PackageParser.Activity a = pkg.receivers.get(i);
8229            mReceivers.removeActivity(a, "receiver");
8230            if (DEBUG_REMOVE && chatty) {
8231                if (r == null) {
8232                    r = new StringBuilder(256);
8233                } else {
8234                    r.append(' ');
8235                }
8236                r.append(a.info.name);
8237            }
8238        }
8239        if (r != null) {
8240            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8241        }
8242
8243        N = pkg.activities.size();
8244        r = null;
8245        for (i=0; i<N; i++) {
8246            PackageParser.Activity a = pkg.activities.get(i);
8247            mActivities.removeActivity(a, "activity");
8248            if (DEBUG_REMOVE && chatty) {
8249                if (r == null) {
8250                    r = new StringBuilder(256);
8251                } else {
8252                    r.append(' ');
8253                }
8254                r.append(a.info.name);
8255            }
8256        }
8257        if (r != null) {
8258            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8259        }
8260
8261        N = pkg.permissions.size();
8262        r = null;
8263        for (i=0; i<N; i++) {
8264            PackageParser.Permission p = pkg.permissions.get(i);
8265            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8266            if (bp == null) {
8267                bp = mSettings.mPermissionTrees.get(p.info.name);
8268            }
8269            if (bp != null && bp.perm == p) {
8270                bp.perm = null;
8271                if (DEBUG_REMOVE && chatty) {
8272                    if (r == null) {
8273                        r = new StringBuilder(256);
8274                    } else {
8275                        r.append(' ');
8276                    }
8277                    r.append(p.info.name);
8278                }
8279            }
8280            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8281                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8282                if (appOpPerms != null) {
8283                    appOpPerms.remove(pkg.packageName);
8284                }
8285            }
8286        }
8287        if (r != null) {
8288            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8289        }
8290
8291        N = pkg.requestedPermissions.size();
8292        r = null;
8293        for (i=0; i<N; i++) {
8294            String perm = pkg.requestedPermissions.get(i);
8295            BasePermission bp = mSettings.mPermissions.get(perm);
8296            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8297                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8298                if (appOpPerms != null) {
8299                    appOpPerms.remove(pkg.packageName);
8300                    if (appOpPerms.isEmpty()) {
8301                        mAppOpPermissionPackages.remove(perm);
8302                    }
8303                }
8304            }
8305        }
8306        if (r != null) {
8307            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8308        }
8309
8310        N = pkg.instrumentation.size();
8311        r = null;
8312        for (i=0; i<N; i++) {
8313            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8314            mInstrumentation.remove(a.getComponentName());
8315            if (DEBUG_REMOVE && chatty) {
8316                if (r == null) {
8317                    r = new StringBuilder(256);
8318                } else {
8319                    r.append(' ');
8320                }
8321                r.append(a.info.name);
8322            }
8323        }
8324        if (r != null) {
8325            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8326        }
8327
8328        r = null;
8329        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8330            // Only system apps can hold shared libraries.
8331            if (pkg.libraryNames != null) {
8332                for (i=0; i<pkg.libraryNames.size(); i++) {
8333                    String name = pkg.libraryNames.get(i);
8334                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8335                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8336                        mSharedLibraries.remove(name);
8337                        if (DEBUG_REMOVE && chatty) {
8338                            if (r == null) {
8339                                r = new StringBuilder(256);
8340                            } else {
8341                                r.append(' ');
8342                            }
8343                            r.append(name);
8344                        }
8345                    }
8346                }
8347            }
8348        }
8349        if (r != null) {
8350            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8351        }
8352    }
8353
8354    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8355        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8356            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8357                return true;
8358            }
8359        }
8360        return false;
8361    }
8362
8363    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8364    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8365    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8366
8367    private void updatePermissionsLPw(String changingPkg,
8368            PackageParser.Package pkgInfo, int flags) {
8369        // Make sure there are no dangling permission trees.
8370        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8371        while (it.hasNext()) {
8372            final BasePermission bp = it.next();
8373            if (bp.packageSetting == null) {
8374                // We may not yet have parsed the package, so just see if
8375                // we still know about its settings.
8376                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8377            }
8378            if (bp.packageSetting == null) {
8379                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8380                        + " from package " + bp.sourcePackage);
8381                it.remove();
8382            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8383                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8384                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8385                            + " from package " + bp.sourcePackage);
8386                    flags |= UPDATE_PERMISSIONS_ALL;
8387                    it.remove();
8388                }
8389            }
8390        }
8391
8392        // Make sure all dynamic permissions have been assigned to a package,
8393        // and make sure there are no dangling permissions.
8394        it = mSettings.mPermissions.values().iterator();
8395        while (it.hasNext()) {
8396            final BasePermission bp = it.next();
8397            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8398                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8399                        + bp.name + " pkg=" + bp.sourcePackage
8400                        + " info=" + bp.pendingInfo);
8401                if (bp.packageSetting == null && bp.pendingInfo != null) {
8402                    final BasePermission tree = findPermissionTreeLP(bp.name);
8403                    if (tree != null && tree.perm != null) {
8404                        bp.packageSetting = tree.packageSetting;
8405                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8406                                new PermissionInfo(bp.pendingInfo));
8407                        bp.perm.info.packageName = tree.perm.info.packageName;
8408                        bp.perm.info.name = bp.name;
8409                        bp.uid = tree.uid;
8410                    }
8411                }
8412            }
8413            if (bp.packageSetting == null) {
8414                // We may not yet have parsed the package, so just see if
8415                // we still know about its settings.
8416                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8417            }
8418            if (bp.packageSetting == null) {
8419                Slog.w(TAG, "Removing dangling permission: " + bp.name
8420                        + " from package " + bp.sourcePackage);
8421                it.remove();
8422            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8423                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8424                    Slog.i(TAG, "Removing old permission: " + bp.name
8425                            + " from package " + bp.sourcePackage);
8426                    flags |= UPDATE_PERMISSIONS_ALL;
8427                    it.remove();
8428                }
8429            }
8430        }
8431
8432        // Now update the permissions for all packages, in particular
8433        // replace the granted permissions of the system packages.
8434        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8435            for (PackageParser.Package pkg : mPackages.values()) {
8436                if (pkg != pkgInfo) {
8437                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8438                            changingPkg);
8439                }
8440            }
8441        }
8442
8443        if (pkgInfo != null) {
8444            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8445        }
8446    }
8447
8448    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8449            String packageOfInterest) {
8450        // IMPORTANT: There are two types of permissions: install and runtime.
8451        // Install time permissions are granted when the app is installed to
8452        // all device users and users added in the future. Runtime permissions
8453        // are granted at runtime explicitly to specific users. Normal and signature
8454        // protected permissions are install time permissions. Dangerous permissions
8455        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8456        // otherwise they are runtime permissions. This function does not manage
8457        // runtime permissions except for the case an app targeting Lollipop MR1
8458        // being upgraded to target a newer SDK, in which case dangerous permissions
8459        // are transformed from install time to runtime ones.
8460
8461        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8462        if (ps == null) {
8463            return;
8464        }
8465
8466        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8467
8468        PermissionsState permissionsState = ps.getPermissionsState();
8469        PermissionsState origPermissions = permissionsState;
8470
8471        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8472
8473        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8474
8475        boolean changedInstallPermission = false;
8476
8477        if (replace) {
8478            ps.installPermissionsFixed = false;
8479            if (!ps.isSharedUser()) {
8480                origPermissions = new PermissionsState(permissionsState);
8481                permissionsState.reset();
8482            }
8483        }
8484
8485        permissionsState.setGlobalGids(mGlobalGids);
8486
8487        final int N = pkg.requestedPermissions.size();
8488        for (int i=0; i<N; i++) {
8489            final String name = pkg.requestedPermissions.get(i);
8490            final BasePermission bp = mSettings.mPermissions.get(name);
8491
8492            if (DEBUG_INSTALL) {
8493                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8494            }
8495
8496            if (bp == null || bp.packageSetting == null) {
8497                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8498                    Slog.w(TAG, "Unknown permission " + name
8499                            + " in package " + pkg.packageName);
8500                }
8501                continue;
8502            }
8503
8504            final String perm = bp.name;
8505            boolean allowedSig = false;
8506            int grant = GRANT_DENIED;
8507
8508            // Keep track of app op permissions.
8509            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8510                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8511                if (pkgs == null) {
8512                    pkgs = new ArraySet<>();
8513                    mAppOpPermissionPackages.put(bp.name, pkgs);
8514                }
8515                pkgs.add(pkg.packageName);
8516            }
8517
8518            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8519            switch (level) {
8520                case PermissionInfo.PROTECTION_NORMAL: {
8521                    // For all apps normal permissions are install time ones.
8522                    grant = GRANT_INSTALL;
8523                } break;
8524
8525                case PermissionInfo.PROTECTION_DANGEROUS: {
8526                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8527                        // For legacy apps dangerous permissions are install time ones.
8528                        grant = GRANT_INSTALL_LEGACY;
8529                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8530                        // For legacy apps that became modern, install becomes runtime.
8531                        grant = GRANT_UPGRADE;
8532                    } else if (mPromoteSystemApps
8533                            && isSystemApp(ps)
8534                            && mExistingSystemPackages.contains(ps.name)) {
8535                        // For legacy system apps, install becomes runtime.
8536                        // We cannot check hasInstallPermission() for system apps since those
8537                        // permissions were granted implicitly and not persisted pre-M.
8538                        grant = GRANT_UPGRADE;
8539                    } else {
8540                        // For modern apps keep runtime permissions unchanged.
8541                        grant = GRANT_RUNTIME;
8542                    }
8543                } break;
8544
8545                case PermissionInfo.PROTECTION_SIGNATURE: {
8546                    // For all apps signature permissions are install time ones.
8547                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8548                    if (allowedSig) {
8549                        grant = GRANT_INSTALL;
8550                    }
8551                } break;
8552            }
8553
8554            if (DEBUG_INSTALL) {
8555                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8556            }
8557
8558            if (grant != GRANT_DENIED) {
8559                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8560                    // If this is an existing, non-system package, then
8561                    // we can't add any new permissions to it.
8562                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8563                        // Except...  if this is a permission that was added
8564                        // to the platform (note: need to only do this when
8565                        // updating the platform).
8566                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8567                            grant = GRANT_DENIED;
8568                        }
8569                    }
8570                }
8571
8572                switch (grant) {
8573                    case GRANT_INSTALL: {
8574                        // Revoke this as runtime permission to handle the case of
8575                        // a runtime permission being downgraded to an install one.
8576                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8577                            if (origPermissions.getRuntimePermissionState(
8578                                    bp.name, userId) != null) {
8579                                // Revoke the runtime permission and clear the flags.
8580                                origPermissions.revokeRuntimePermission(bp, userId);
8581                                origPermissions.updatePermissionFlags(bp, userId,
8582                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8583                                // If we revoked a permission permission, we have to write.
8584                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8585                                        changedRuntimePermissionUserIds, userId);
8586                            }
8587                        }
8588                        // Grant an install permission.
8589                        if (permissionsState.grantInstallPermission(bp) !=
8590                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8591                            changedInstallPermission = true;
8592                        }
8593                    } break;
8594
8595                    case GRANT_INSTALL_LEGACY: {
8596                        // Grant an install permission.
8597                        if (permissionsState.grantInstallPermission(bp) !=
8598                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8599                            changedInstallPermission = true;
8600                        }
8601                    } break;
8602
8603                    case GRANT_RUNTIME: {
8604                        // Grant previously granted runtime permissions.
8605                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8606                            PermissionState permissionState = origPermissions
8607                                    .getRuntimePermissionState(bp.name, userId);
8608                            final int flags = permissionState != null
8609                                    ? permissionState.getFlags() : 0;
8610                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8611                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8612                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8613                                    // If we cannot put the permission as it was, we have to write.
8614                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8615                                            changedRuntimePermissionUserIds, userId);
8616                                }
8617                            }
8618                            // Propagate the permission flags.
8619                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8620                        }
8621                    } break;
8622
8623                    case GRANT_UPGRADE: {
8624                        // Grant runtime permissions for a previously held install permission.
8625                        PermissionState permissionState = origPermissions
8626                                .getInstallPermissionState(bp.name);
8627                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8628
8629                        if (origPermissions.revokeInstallPermission(bp)
8630                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8631                            // We will be transferring the permission flags, so clear them.
8632                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8633                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8634                            changedInstallPermission = true;
8635                        }
8636
8637                        // If the permission is not to be promoted to runtime we ignore it and
8638                        // also its other flags as they are not applicable to install permissions.
8639                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8640                            for (int userId : currentUserIds) {
8641                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8642                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8643                                    // Transfer the permission flags.
8644                                    permissionsState.updatePermissionFlags(bp, userId,
8645                                            flags, flags);
8646                                    // If we granted the permission, we have to write.
8647                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8648                                            changedRuntimePermissionUserIds, userId);
8649                                }
8650                            }
8651                        }
8652                    } break;
8653
8654                    default: {
8655                        if (packageOfInterest == null
8656                                || packageOfInterest.equals(pkg.packageName)) {
8657                            Slog.w(TAG, "Not granting permission " + perm
8658                                    + " to package " + pkg.packageName
8659                                    + " because it was previously installed without");
8660                        }
8661                    } break;
8662                }
8663            } else {
8664                if (permissionsState.revokeInstallPermission(bp) !=
8665                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8666                    // Also drop the permission flags.
8667                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8668                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8669                    changedInstallPermission = true;
8670                    Slog.i(TAG, "Un-granting permission " + perm
8671                            + " from package " + pkg.packageName
8672                            + " (protectionLevel=" + bp.protectionLevel
8673                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8674                            + ")");
8675                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8676                    // Don't print warning for app op permissions, since it is fine for them
8677                    // not to be granted, there is a UI for the user to decide.
8678                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8679                        Slog.w(TAG, "Not granting permission " + perm
8680                                + " to package " + pkg.packageName
8681                                + " (protectionLevel=" + bp.protectionLevel
8682                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8683                                + ")");
8684                    }
8685                }
8686            }
8687        }
8688
8689        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8690                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8691            // This is the first that we have heard about this package, so the
8692            // permissions we have now selected are fixed until explicitly
8693            // changed.
8694            ps.installPermissionsFixed = true;
8695        }
8696
8697        // Persist the runtime permissions state for users with changes.
8698        for (int userId : changedRuntimePermissionUserIds) {
8699            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8700        }
8701
8702        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8703    }
8704
8705    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8706        boolean allowed = false;
8707        final int NP = PackageParser.NEW_PERMISSIONS.length;
8708        for (int ip=0; ip<NP; ip++) {
8709            final PackageParser.NewPermissionInfo npi
8710                    = PackageParser.NEW_PERMISSIONS[ip];
8711            if (npi.name.equals(perm)
8712                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8713                allowed = true;
8714                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8715                        + pkg.packageName);
8716                break;
8717            }
8718        }
8719        return allowed;
8720    }
8721
8722    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8723            BasePermission bp, PermissionsState origPermissions) {
8724        boolean allowed;
8725        allowed = (compareSignatures(
8726                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8727                        == PackageManager.SIGNATURE_MATCH)
8728                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8729                        == PackageManager.SIGNATURE_MATCH);
8730        if (!allowed && (bp.protectionLevel
8731                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8732            if (isSystemApp(pkg)) {
8733                // For updated system applications, a system permission
8734                // is granted only if it had been defined by the original application.
8735                if (pkg.isUpdatedSystemApp()) {
8736                    final PackageSetting sysPs = mSettings
8737                            .getDisabledSystemPkgLPr(pkg.packageName);
8738                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8739                        // If the original was granted this permission, we take
8740                        // that grant decision as read and propagate it to the
8741                        // update.
8742                        if (sysPs.isPrivileged()) {
8743                            allowed = true;
8744                        }
8745                    } else {
8746                        // The system apk may have been updated with an older
8747                        // version of the one on the data partition, but which
8748                        // granted a new system permission that it didn't have
8749                        // before.  In this case we do want to allow the app to
8750                        // now get the new permission if the ancestral apk is
8751                        // privileged to get it.
8752                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8753                            for (int j=0;
8754                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8755                                if (perm.equals(
8756                                        sysPs.pkg.requestedPermissions.get(j))) {
8757                                    allowed = true;
8758                                    break;
8759                                }
8760                            }
8761                        }
8762                    }
8763                } else {
8764                    allowed = isPrivilegedApp(pkg);
8765                }
8766            }
8767        }
8768        if (!allowed) {
8769            if (!allowed && (bp.protectionLevel
8770                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8771                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8772                // If this was a previously normal/dangerous permission that got moved
8773                // to a system permission as part of the runtime permission redesign, then
8774                // we still want to blindly grant it to old apps.
8775                allowed = true;
8776            }
8777            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8778                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8779                // If this permission is to be granted to the system installer and
8780                // this app is an installer, then it gets the permission.
8781                allowed = true;
8782            }
8783            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8784                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8785                // If this permission is to be granted to the system verifier and
8786                // this app is a verifier, then it gets the permission.
8787                allowed = true;
8788            }
8789            if (!allowed && (bp.protectionLevel
8790                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8791                    && isSystemApp(pkg)) {
8792                // Any pre-installed system app is allowed to get this permission.
8793                allowed = true;
8794            }
8795            if (!allowed && (bp.protectionLevel
8796                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8797                // For development permissions, a development permission
8798                // is granted only if it was already granted.
8799                allowed = origPermissions.hasInstallPermission(perm);
8800            }
8801        }
8802        return allowed;
8803    }
8804
8805    final class ActivityIntentResolver
8806            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8807        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8808                boolean defaultOnly, int userId) {
8809            if (!sUserManager.exists(userId)) return null;
8810            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8811            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8812        }
8813
8814        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8815                int userId) {
8816            if (!sUserManager.exists(userId)) return null;
8817            mFlags = flags;
8818            return super.queryIntent(intent, resolvedType,
8819                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8820        }
8821
8822        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8823                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8824            if (!sUserManager.exists(userId)) return null;
8825            if (packageActivities == null) {
8826                return null;
8827            }
8828            mFlags = flags;
8829            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8830            final int N = packageActivities.size();
8831            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8832                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8833
8834            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8835            for (int i = 0; i < N; ++i) {
8836                intentFilters = packageActivities.get(i).intents;
8837                if (intentFilters != null && intentFilters.size() > 0) {
8838                    PackageParser.ActivityIntentInfo[] array =
8839                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8840                    intentFilters.toArray(array);
8841                    listCut.add(array);
8842                }
8843            }
8844            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8845        }
8846
8847        public final void addActivity(PackageParser.Activity a, String type) {
8848            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8849            mActivities.put(a.getComponentName(), a);
8850            if (DEBUG_SHOW_INFO)
8851                Log.v(
8852                TAG, "  " + type + " " +
8853                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8854            if (DEBUG_SHOW_INFO)
8855                Log.v(TAG, "    Class=" + a.info.name);
8856            final int NI = a.intents.size();
8857            for (int j=0; j<NI; j++) {
8858                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8859                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8860                    intent.setPriority(0);
8861                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8862                            + a.className + " with priority > 0, forcing to 0");
8863                }
8864                if (DEBUG_SHOW_INFO) {
8865                    Log.v(TAG, "    IntentFilter:");
8866                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8867                }
8868                if (!intent.debugCheck()) {
8869                    Log.w(TAG, "==> For Activity " + a.info.name);
8870                }
8871                addFilter(intent);
8872            }
8873        }
8874
8875        public final void removeActivity(PackageParser.Activity a, String type) {
8876            mActivities.remove(a.getComponentName());
8877            if (DEBUG_SHOW_INFO) {
8878                Log.v(TAG, "  " + type + " "
8879                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8880                                : a.info.name) + ":");
8881                Log.v(TAG, "    Class=" + a.info.name);
8882            }
8883            final int NI = a.intents.size();
8884            for (int j=0; j<NI; j++) {
8885                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8886                if (DEBUG_SHOW_INFO) {
8887                    Log.v(TAG, "    IntentFilter:");
8888                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8889                }
8890                removeFilter(intent);
8891            }
8892        }
8893
8894        @Override
8895        protected boolean allowFilterResult(
8896                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8897            ActivityInfo filterAi = filter.activity.info;
8898            for (int i=dest.size()-1; i>=0; i--) {
8899                ActivityInfo destAi = dest.get(i).activityInfo;
8900                if (destAi.name == filterAi.name
8901                        && destAi.packageName == filterAi.packageName) {
8902                    return false;
8903                }
8904            }
8905            return true;
8906        }
8907
8908        @Override
8909        protected ActivityIntentInfo[] newArray(int size) {
8910            return new ActivityIntentInfo[size];
8911        }
8912
8913        @Override
8914        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8915            if (!sUserManager.exists(userId)) return true;
8916            PackageParser.Package p = filter.activity.owner;
8917            if (p != null) {
8918                PackageSetting ps = (PackageSetting)p.mExtras;
8919                if (ps != null) {
8920                    // System apps are never considered stopped for purposes of
8921                    // filtering, because there may be no way for the user to
8922                    // actually re-launch them.
8923                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8924                            && ps.getStopped(userId);
8925                }
8926            }
8927            return false;
8928        }
8929
8930        @Override
8931        protected boolean isPackageForFilter(String packageName,
8932                PackageParser.ActivityIntentInfo info) {
8933            return packageName.equals(info.activity.owner.packageName);
8934        }
8935
8936        @Override
8937        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8938                int match, int userId) {
8939            if (!sUserManager.exists(userId)) return null;
8940            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8941                return null;
8942            }
8943            final PackageParser.Activity activity = info.activity;
8944            if (mSafeMode && (activity.info.applicationInfo.flags
8945                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8946                return null;
8947            }
8948            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8949            if (ps == null) {
8950                return null;
8951            }
8952            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8953                    ps.readUserState(userId), userId);
8954            if (ai == null) {
8955                return null;
8956            }
8957            final ResolveInfo res = new ResolveInfo();
8958            res.activityInfo = ai;
8959            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8960                res.filter = info;
8961            }
8962            if (info != null) {
8963                res.handleAllWebDataURI = info.handleAllWebDataURI();
8964            }
8965            res.priority = info.getPriority();
8966            res.preferredOrder = activity.owner.mPreferredOrder;
8967            //System.out.println("Result: " + res.activityInfo.className +
8968            //                   " = " + res.priority);
8969            res.match = match;
8970            res.isDefault = info.hasDefault;
8971            res.labelRes = info.labelRes;
8972            res.nonLocalizedLabel = info.nonLocalizedLabel;
8973            if (userNeedsBadging(userId)) {
8974                res.noResourceId = true;
8975            } else {
8976                res.icon = info.icon;
8977            }
8978            res.iconResourceId = info.icon;
8979            res.system = res.activityInfo.applicationInfo.isSystemApp();
8980            return res;
8981        }
8982
8983        @Override
8984        protected void sortResults(List<ResolveInfo> results) {
8985            Collections.sort(results, mResolvePrioritySorter);
8986        }
8987
8988        @Override
8989        protected void dumpFilter(PrintWriter out, String prefix,
8990                PackageParser.ActivityIntentInfo filter) {
8991            out.print(prefix); out.print(
8992                    Integer.toHexString(System.identityHashCode(filter.activity)));
8993                    out.print(' ');
8994                    filter.activity.printComponentShortName(out);
8995                    out.print(" filter ");
8996                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8997        }
8998
8999        @Override
9000        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9001            return filter.activity;
9002        }
9003
9004        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9005            PackageParser.Activity activity = (PackageParser.Activity)label;
9006            out.print(prefix); out.print(
9007                    Integer.toHexString(System.identityHashCode(activity)));
9008                    out.print(' ');
9009                    activity.printComponentShortName(out);
9010            if (count > 1) {
9011                out.print(" ("); out.print(count); out.print(" filters)");
9012            }
9013            out.println();
9014        }
9015
9016//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9017//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9018//            final List<ResolveInfo> retList = Lists.newArrayList();
9019//            while (i.hasNext()) {
9020//                final ResolveInfo resolveInfo = i.next();
9021//                if (isEnabledLP(resolveInfo.activityInfo)) {
9022//                    retList.add(resolveInfo);
9023//                }
9024//            }
9025//            return retList;
9026//        }
9027
9028        // Keys are String (activity class name), values are Activity.
9029        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9030                = new ArrayMap<ComponentName, PackageParser.Activity>();
9031        private int mFlags;
9032    }
9033
9034    private final class ServiceIntentResolver
9035            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9036        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9037                boolean defaultOnly, int userId) {
9038            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9039            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9040        }
9041
9042        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9043                int userId) {
9044            if (!sUserManager.exists(userId)) return null;
9045            mFlags = flags;
9046            return super.queryIntent(intent, resolvedType,
9047                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9048        }
9049
9050        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9051                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9052            if (!sUserManager.exists(userId)) return null;
9053            if (packageServices == null) {
9054                return null;
9055            }
9056            mFlags = flags;
9057            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9058            final int N = packageServices.size();
9059            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9060                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9061
9062            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9063            for (int i = 0; i < N; ++i) {
9064                intentFilters = packageServices.get(i).intents;
9065                if (intentFilters != null && intentFilters.size() > 0) {
9066                    PackageParser.ServiceIntentInfo[] array =
9067                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9068                    intentFilters.toArray(array);
9069                    listCut.add(array);
9070                }
9071            }
9072            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9073        }
9074
9075        public final void addService(PackageParser.Service s) {
9076            mServices.put(s.getComponentName(), s);
9077            if (DEBUG_SHOW_INFO) {
9078                Log.v(TAG, "  "
9079                        + (s.info.nonLocalizedLabel != null
9080                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9081                Log.v(TAG, "    Class=" + s.info.name);
9082            }
9083            final int NI = s.intents.size();
9084            int j;
9085            for (j=0; j<NI; j++) {
9086                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9087                if (DEBUG_SHOW_INFO) {
9088                    Log.v(TAG, "    IntentFilter:");
9089                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9090                }
9091                if (!intent.debugCheck()) {
9092                    Log.w(TAG, "==> For Service " + s.info.name);
9093                }
9094                addFilter(intent);
9095            }
9096        }
9097
9098        public final void removeService(PackageParser.Service s) {
9099            mServices.remove(s.getComponentName());
9100            if (DEBUG_SHOW_INFO) {
9101                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9102                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9103                Log.v(TAG, "    Class=" + s.info.name);
9104            }
9105            final int NI = s.intents.size();
9106            int j;
9107            for (j=0; j<NI; j++) {
9108                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9109                if (DEBUG_SHOW_INFO) {
9110                    Log.v(TAG, "    IntentFilter:");
9111                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9112                }
9113                removeFilter(intent);
9114            }
9115        }
9116
9117        @Override
9118        protected boolean allowFilterResult(
9119                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9120            ServiceInfo filterSi = filter.service.info;
9121            for (int i=dest.size()-1; i>=0; i--) {
9122                ServiceInfo destAi = dest.get(i).serviceInfo;
9123                if (destAi.name == filterSi.name
9124                        && destAi.packageName == filterSi.packageName) {
9125                    return false;
9126                }
9127            }
9128            return true;
9129        }
9130
9131        @Override
9132        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9133            return new PackageParser.ServiceIntentInfo[size];
9134        }
9135
9136        @Override
9137        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9138            if (!sUserManager.exists(userId)) return true;
9139            PackageParser.Package p = filter.service.owner;
9140            if (p != null) {
9141                PackageSetting ps = (PackageSetting)p.mExtras;
9142                if (ps != null) {
9143                    // System apps are never considered stopped for purposes of
9144                    // filtering, because there may be no way for the user to
9145                    // actually re-launch them.
9146                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9147                            && ps.getStopped(userId);
9148                }
9149            }
9150            return false;
9151        }
9152
9153        @Override
9154        protected boolean isPackageForFilter(String packageName,
9155                PackageParser.ServiceIntentInfo info) {
9156            return packageName.equals(info.service.owner.packageName);
9157        }
9158
9159        @Override
9160        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9161                int match, int userId) {
9162            if (!sUserManager.exists(userId)) return null;
9163            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9164            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
9165                return null;
9166            }
9167            final PackageParser.Service service = info.service;
9168            if (mSafeMode && (service.info.applicationInfo.flags
9169                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9170                return null;
9171            }
9172            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9173            if (ps == null) {
9174                return null;
9175            }
9176            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9177                    ps.readUserState(userId), userId);
9178            if (si == null) {
9179                return null;
9180            }
9181            final ResolveInfo res = new ResolveInfo();
9182            res.serviceInfo = si;
9183            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9184                res.filter = filter;
9185            }
9186            res.priority = info.getPriority();
9187            res.preferredOrder = service.owner.mPreferredOrder;
9188            res.match = match;
9189            res.isDefault = info.hasDefault;
9190            res.labelRes = info.labelRes;
9191            res.nonLocalizedLabel = info.nonLocalizedLabel;
9192            res.icon = info.icon;
9193            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9194            return res;
9195        }
9196
9197        @Override
9198        protected void sortResults(List<ResolveInfo> results) {
9199            Collections.sort(results, mResolvePrioritySorter);
9200        }
9201
9202        @Override
9203        protected void dumpFilter(PrintWriter out, String prefix,
9204                PackageParser.ServiceIntentInfo filter) {
9205            out.print(prefix); out.print(
9206                    Integer.toHexString(System.identityHashCode(filter.service)));
9207                    out.print(' ');
9208                    filter.service.printComponentShortName(out);
9209                    out.print(" filter ");
9210                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9211        }
9212
9213        @Override
9214        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9215            return filter.service;
9216        }
9217
9218        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9219            PackageParser.Service service = (PackageParser.Service)label;
9220            out.print(prefix); out.print(
9221                    Integer.toHexString(System.identityHashCode(service)));
9222                    out.print(' ');
9223                    service.printComponentShortName(out);
9224            if (count > 1) {
9225                out.print(" ("); out.print(count); out.print(" filters)");
9226            }
9227            out.println();
9228        }
9229
9230//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9231//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9232//            final List<ResolveInfo> retList = Lists.newArrayList();
9233//            while (i.hasNext()) {
9234//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9235//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9236//                    retList.add(resolveInfo);
9237//                }
9238//            }
9239//            return retList;
9240//        }
9241
9242        // Keys are String (activity class name), values are Activity.
9243        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9244                = new ArrayMap<ComponentName, PackageParser.Service>();
9245        private int mFlags;
9246    };
9247
9248    private final class ProviderIntentResolver
9249            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9250        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9251                boolean defaultOnly, int userId) {
9252            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9253            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9254        }
9255
9256        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9257                int userId) {
9258            if (!sUserManager.exists(userId))
9259                return null;
9260            mFlags = flags;
9261            return super.queryIntent(intent, resolvedType,
9262                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9263        }
9264
9265        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9266                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9267            if (!sUserManager.exists(userId))
9268                return null;
9269            if (packageProviders == null) {
9270                return null;
9271            }
9272            mFlags = flags;
9273            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9274            final int N = packageProviders.size();
9275            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9276                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9277
9278            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9279            for (int i = 0; i < N; ++i) {
9280                intentFilters = packageProviders.get(i).intents;
9281                if (intentFilters != null && intentFilters.size() > 0) {
9282                    PackageParser.ProviderIntentInfo[] array =
9283                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9284                    intentFilters.toArray(array);
9285                    listCut.add(array);
9286                }
9287            }
9288            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9289        }
9290
9291        public final void addProvider(PackageParser.Provider p) {
9292            if (mProviders.containsKey(p.getComponentName())) {
9293                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9294                return;
9295            }
9296
9297            mProviders.put(p.getComponentName(), p);
9298            if (DEBUG_SHOW_INFO) {
9299                Log.v(TAG, "  "
9300                        + (p.info.nonLocalizedLabel != null
9301                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9302                Log.v(TAG, "    Class=" + p.info.name);
9303            }
9304            final int NI = p.intents.size();
9305            int j;
9306            for (j = 0; j < NI; j++) {
9307                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9308                if (DEBUG_SHOW_INFO) {
9309                    Log.v(TAG, "    IntentFilter:");
9310                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9311                }
9312                if (!intent.debugCheck()) {
9313                    Log.w(TAG, "==> For Provider " + p.info.name);
9314                }
9315                addFilter(intent);
9316            }
9317        }
9318
9319        public final void removeProvider(PackageParser.Provider p) {
9320            mProviders.remove(p.getComponentName());
9321            if (DEBUG_SHOW_INFO) {
9322                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9323                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9324                Log.v(TAG, "    Class=" + p.info.name);
9325            }
9326            final int NI = p.intents.size();
9327            int j;
9328            for (j = 0; j < NI; j++) {
9329                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9330                if (DEBUG_SHOW_INFO) {
9331                    Log.v(TAG, "    IntentFilter:");
9332                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9333                }
9334                removeFilter(intent);
9335            }
9336        }
9337
9338        @Override
9339        protected boolean allowFilterResult(
9340                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9341            ProviderInfo filterPi = filter.provider.info;
9342            for (int i = dest.size() - 1; i >= 0; i--) {
9343                ProviderInfo destPi = dest.get(i).providerInfo;
9344                if (destPi.name == filterPi.name
9345                        && destPi.packageName == filterPi.packageName) {
9346                    return false;
9347                }
9348            }
9349            return true;
9350        }
9351
9352        @Override
9353        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9354            return new PackageParser.ProviderIntentInfo[size];
9355        }
9356
9357        @Override
9358        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9359            if (!sUserManager.exists(userId))
9360                return true;
9361            PackageParser.Package p = filter.provider.owner;
9362            if (p != null) {
9363                PackageSetting ps = (PackageSetting) p.mExtras;
9364                if (ps != null) {
9365                    // System apps are never considered stopped for purposes of
9366                    // filtering, because there may be no way for the user to
9367                    // actually re-launch them.
9368                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9369                            && ps.getStopped(userId);
9370                }
9371            }
9372            return false;
9373        }
9374
9375        @Override
9376        protected boolean isPackageForFilter(String packageName,
9377                PackageParser.ProviderIntentInfo info) {
9378            return packageName.equals(info.provider.owner.packageName);
9379        }
9380
9381        @Override
9382        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9383                int match, int userId) {
9384            if (!sUserManager.exists(userId))
9385                return null;
9386            final PackageParser.ProviderIntentInfo info = filter;
9387            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9388                return null;
9389            }
9390            final PackageParser.Provider provider = info.provider;
9391            if (mSafeMode && (provider.info.applicationInfo.flags
9392                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9393                return null;
9394            }
9395            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9396            if (ps == null) {
9397                return null;
9398            }
9399            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9400                    ps.readUserState(userId), userId);
9401            if (pi == null) {
9402                return null;
9403            }
9404            final ResolveInfo res = new ResolveInfo();
9405            res.providerInfo = pi;
9406            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9407                res.filter = filter;
9408            }
9409            res.priority = info.getPriority();
9410            res.preferredOrder = provider.owner.mPreferredOrder;
9411            res.match = match;
9412            res.isDefault = info.hasDefault;
9413            res.labelRes = info.labelRes;
9414            res.nonLocalizedLabel = info.nonLocalizedLabel;
9415            res.icon = info.icon;
9416            res.system = res.providerInfo.applicationInfo.isSystemApp();
9417            return res;
9418        }
9419
9420        @Override
9421        protected void sortResults(List<ResolveInfo> results) {
9422            Collections.sort(results, mResolvePrioritySorter);
9423        }
9424
9425        @Override
9426        protected void dumpFilter(PrintWriter out, String prefix,
9427                PackageParser.ProviderIntentInfo filter) {
9428            out.print(prefix);
9429            out.print(
9430                    Integer.toHexString(System.identityHashCode(filter.provider)));
9431            out.print(' ');
9432            filter.provider.printComponentShortName(out);
9433            out.print(" filter ");
9434            out.println(Integer.toHexString(System.identityHashCode(filter)));
9435        }
9436
9437        @Override
9438        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9439            return filter.provider;
9440        }
9441
9442        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9443            PackageParser.Provider provider = (PackageParser.Provider)label;
9444            out.print(prefix); out.print(
9445                    Integer.toHexString(System.identityHashCode(provider)));
9446                    out.print(' ');
9447                    provider.printComponentShortName(out);
9448            if (count > 1) {
9449                out.print(" ("); out.print(count); out.print(" filters)");
9450            }
9451            out.println();
9452        }
9453
9454        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9455                = new ArrayMap<ComponentName, PackageParser.Provider>();
9456        private int mFlags;
9457    };
9458
9459    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9460            new Comparator<ResolveInfo>() {
9461        public int compare(ResolveInfo r1, ResolveInfo r2) {
9462            int v1 = r1.priority;
9463            int v2 = r2.priority;
9464            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9465            if (v1 != v2) {
9466                return (v1 > v2) ? -1 : 1;
9467            }
9468            v1 = r1.preferredOrder;
9469            v2 = r2.preferredOrder;
9470            if (v1 != v2) {
9471                return (v1 > v2) ? -1 : 1;
9472            }
9473            if (r1.isDefault != r2.isDefault) {
9474                return r1.isDefault ? -1 : 1;
9475            }
9476            v1 = r1.match;
9477            v2 = r2.match;
9478            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9479            if (v1 != v2) {
9480                return (v1 > v2) ? -1 : 1;
9481            }
9482            if (r1.system != r2.system) {
9483                return r1.system ? -1 : 1;
9484            }
9485            return 0;
9486        }
9487    };
9488
9489    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9490            new Comparator<ProviderInfo>() {
9491        public int compare(ProviderInfo p1, ProviderInfo p2) {
9492            final int v1 = p1.initOrder;
9493            final int v2 = p2.initOrder;
9494            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9495        }
9496    };
9497
9498    final void sendPackageBroadcast(final String action, final String pkg,
9499            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9500            final int[] userIds) {
9501        mHandler.post(new Runnable() {
9502            @Override
9503            public void run() {
9504                try {
9505                    final IActivityManager am = ActivityManagerNative.getDefault();
9506                    if (am == null) return;
9507                    final int[] resolvedUserIds;
9508                    if (userIds == null) {
9509                        resolvedUserIds = am.getRunningUserIds();
9510                    } else {
9511                        resolvedUserIds = userIds;
9512                    }
9513                    for (int id : resolvedUserIds) {
9514                        final Intent intent = new Intent(action,
9515                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9516                        if (extras != null) {
9517                            intent.putExtras(extras);
9518                        }
9519                        if (targetPkg != null) {
9520                            intent.setPackage(targetPkg);
9521                        }
9522                        // Modify the UID when posting to other users
9523                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9524                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9525                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9526                            intent.putExtra(Intent.EXTRA_UID, uid);
9527                        }
9528                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9529                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9530                        if (DEBUG_BROADCASTS) {
9531                            RuntimeException here = new RuntimeException("here");
9532                            here.fillInStackTrace();
9533                            Slog.d(TAG, "Sending to user " + id + ": "
9534                                    + intent.toShortString(false, true, false, false)
9535                                    + " " + intent.getExtras(), here);
9536                        }
9537                        am.broadcastIntent(null, intent, null, finishedReceiver,
9538                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9539                                null, finishedReceiver != null, false, id);
9540                    }
9541                } catch (RemoteException ex) {
9542                }
9543            }
9544        });
9545    }
9546
9547    /**
9548     * Check if the external storage media is available. This is true if there
9549     * is a mounted external storage medium or if the external storage is
9550     * emulated.
9551     */
9552    private boolean isExternalMediaAvailable() {
9553        return mMediaMounted || Environment.isExternalStorageEmulated();
9554    }
9555
9556    @Override
9557    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9558        // writer
9559        synchronized (mPackages) {
9560            if (!isExternalMediaAvailable()) {
9561                // If the external storage is no longer mounted at this point,
9562                // the caller may not have been able to delete all of this
9563                // packages files and can not delete any more.  Bail.
9564                return null;
9565            }
9566            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9567            if (lastPackage != null) {
9568                pkgs.remove(lastPackage);
9569            }
9570            if (pkgs.size() > 0) {
9571                return pkgs.get(0);
9572            }
9573        }
9574        return null;
9575    }
9576
9577    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9578        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9579                userId, andCode ? 1 : 0, packageName);
9580        if (mSystemReady) {
9581            msg.sendToTarget();
9582        } else {
9583            if (mPostSystemReadyMessages == null) {
9584                mPostSystemReadyMessages = new ArrayList<>();
9585            }
9586            mPostSystemReadyMessages.add(msg);
9587        }
9588    }
9589
9590    void startCleaningPackages() {
9591        // reader
9592        synchronized (mPackages) {
9593            if (!isExternalMediaAvailable()) {
9594                return;
9595            }
9596            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9597                return;
9598            }
9599        }
9600        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9601        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9602        IActivityManager am = ActivityManagerNative.getDefault();
9603        if (am != null) {
9604            try {
9605                am.startService(null, intent, null, mContext.getOpPackageName(),
9606                        UserHandle.USER_OWNER);
9607            } catch (RemoteException e) {
9608            }
9609        }
9610    }
9611
9612    @Override
9613    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9614            int installFlags, String installerPackageName, VerificationParams verificationParams,
9615            String packageAbiOverride) {
9616        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9617                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9618    }
9619
9620    @Override
9621    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9622            int installFlags, String installerPackageName, VerificationParams verificationParams,
9623            String packageAbiOverride, int userId) {
9624        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9625
9626        final int callingUid = Binder.getCallingUid();
9627        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9628
9629        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9630            try {
9631                if (observer != null) {
9632                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9633                }
9634            } catch (RemoteException re) {
9635            }
9636            return;
9637        }
9638
9639        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9640            installFlags |= PackageManager.INSTALL_FROM_ADB;
9641
9642        } else {
9643            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9644            // about installerPackageName.
9645
9646            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9647            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9648        }
9649
9650        UserHandle user;
9651        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9652            user = UserHandle.ALL;
9653        } else {
9654            user = new UserHandle(userId);
9655        }
9656
9657        // Only system components can circumvent runtime permissions when installing.
9658        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9659                && mContext.checkCallingOrSelfPermission(Manifest.permission
9660                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9661            throw new SecurityException("You need the "
9662                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9663                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9664        }
9665
9666        verificationParams.setInstallerUid(callingUid);
9667
9668        final File originFile = new File(originPath);
9669        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9670
9671        final Message msg = mHandler.obtainMessage(INIT_COPY);
9672        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9673                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9674        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
9675        msg.obj = params;
9676
9677        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
9678                System.identityHashCode(msg.obj));
9679        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9680                System.identityHashCode(msg.obj));
9681
9682        mHandler.sendMessage(msg);
9683    }
9684
9685    void installStage(String packageName, File stagedDir, String stagedCid,
9686            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
9687            String installerPackageName, int installerUid, UserHandle user) {
9688        final VerificationParams verifParams = new VerificationParams(
9689                null, sessionParams.originatingUri, sessionParams.referrerUri, installerUid, null);
9690        verifParams.setInstallerUid(installerUid);
9691
9692        final OriginInfo origin;
9693        if (stagedDir != null) {
9694            origin = OriginInfo.fromStagedFile(stagedDir);
9695        } else {
9696            origin = OriginInfo.fromStagedContainer(stagedCid);
9697        }
9698
9699        final Message msg = mHandler.obtainMessage(INIT_COPY);
9700        final InstallParams params = new InstallParams(origin, null, observer,
9701                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
9702                verifParams, user, sessionParams.abiOverride,
9703                sessionParams.grantedRuntimePermissions);
9704        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
9705        msg.obj = params;
9706
9707        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
9708                System.identityHashCode(msg.obj));
9709        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9710                System.identityHashCode(msg.obj));
9711
9712        mHandler.sendMessage(msg);
9713    }
9714
9715    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9716        Bundle extras = new Bundle(1);
9717        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9718
9719        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9720                packageName, extras, null, null, new int[] {userId});
9721        try {
9722            IActivityManager am = ActivityManagerNative.getDefault();
9723            final boolean isSystem =
9724                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9725            if (isSystem && am.isUserRunning(userId, false)) {
9726                // The just-installed/enabled app is bundled on the system, so presumed
9727                // to be able to run automatically without needing an explicit launch.
9728                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9729                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9730                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9731                        .setPackage(packageName);
9732                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9733                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9734            }
9735        } catch (RemoteException e) {
9736            // shouldn't happen
9737            Slog.w(TAG, "Unable to bootstrap installed package", e);
9738        }
9739    }
9740
9741    @Override
9742    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9743            int userId) {
9744        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9745        PackageSetting pkgSetting;
9746        final int uid = Binder.getCallingUid();
9747        enforceCrossUserPermission(uid, userId, true, true,
9748                "setApplicationHiddenSetting for user " + userId);
9749
9750        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9751            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9752            return false;
9753        }
9754
9755        long callingId = Binder.clearCallingIdentity();
9756        try {
9757            boolean sendAdded = false;
9758            boolean sendRemoved = false;
9759            // writer
9760            synchronized (mPackages) {
9761                pkgSetting = mSettings.mPackages.get(packageName);
9762                if (pkgSetting == null) {
9763                    return false;
9764                }
9765                if (pkgSetting.getHidden(userId) != hidden) {
9766                    pkgSetting.setHidden(hidden, userId);
9767                    mSettings.writePackageRestrictionsLPr(userId);
9768                    if (hidden) {
9769                        sendRemoved = true;
9770                    } else {
9771                        sendAdded = true;
9772                    }
9773                }
9774            }
9775            if (sendAdded) {
9776                sendPackageAddedForUser(packageName, pkgSetting, userId);
9777                return true;
9778            }
9779            if (sendRemoved) {
9780                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9781                        "hiding pkg");
9782                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9783                return true;
9784            }
9785        } finally {
9786            Binder.restoreCallingIdentity(callingId);
9787        }
9788        return false;
9789    }
9790
9791    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9792            int userId) {
9793        final PackageRemovedInfo info = new PackageRemovedInfo();
9794        info.removedPackage = packageName;
9795        info.removedUsers = new int[] {userId};
9796        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9797        info.sendBroadcast(false, false, false);
9798    }
9799
9800    /**
9801     * Returns true if application is not found or there was an error. Otherwise it returns
9802     * the hidden state of the package for the given user.
9803     */
9804    @Override
9805    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9806        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9807        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9808                false, "getApplicationHidden for user " + userId);
9809        PackageSetting pkgSetting;
9810        long callingId = Binder.clearCallingIdentity();
9811        try {
9812            // writer
9813            synchronized (mPackages) {
9814                pkgSetting = mSettings.mPackages.get(packageName);
9815                if (pkgSetting == null) {
9816                    return true;
9817                }
9818                return pkgSetting.getHidden(userId);
9819            }
9820        } finally {
9821            Binder.restoreCallingIdentity(callingId);
9822        }
9823    }
9824
9825    /**
9826     * @hide
9827     */
9828    @Override
9829    public int installExistingPackageAsUser(String packageName, int userId) {
9830        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9831                null);
9832        PackageSetting pkgSetting;
9833        final int uid = Binder.getCallingUid();
9834        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9835                + userId);
9836        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9837            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9838        }
9839
9840        long callingId = Binder.clearCallingIdentity();
9841        try {
9842            boolean sendAdded = false;
9843
9844            // writer
9845            synchronized (mPackages) {
9846                pkgSetting = mSettings.mPackages.get(packageName);
9847                if (pkgSetting == null) {
9848                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9849                }
9850                if (!pkgSetting.getInstalled(userId)) {
9851                    pkgSetting.setInstalled(true, userId);
9852                    pkgSetting.setHidden(false, userId);
9853                    mSettings.writePackageRestrictionsLPr(userId);
9854                    sendAdded = true;
9855                }
9856            }
9857
9858            if (sendAdded) {
9859                sendPackageAddedForUser(packageName, pkgSetting, userId);
9860            }
9861        } finally {
9862            Binder.restoreCallingIdentity(callingId);
9863        }
9864
9865        return PackageManager.INSTALL_SUCCEEDED;
9866    }
9867
9868    boolean isUserRestricted(int userId, String restrictionKey) {
9869        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9870        if (restrictions.getBoolean(restrictionKey, false)) {
9871            Log.w(TAG, "User is restricted: " + restrictionKey);
9872            return true;
9873        }
9874        return false;
9875    }
9876
9877    @Override
9878    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9879        mContext.enforceCallingOrSelfPermission(
9880                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9881                "Only package verification agents can verify applications");
9882
9883        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9884        final PackageVerificationResponse response = new PackageVerificationResponse(
9885                verificationCode, Binder.getCallingUid());
9886        msg.arg1 = id;
9887        msg.obj = response;
9888        mHandler.sendMessage(msg);
9889    }
9890
9891    @Override
9892    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9893            long millisecondsToDelay) {
9894        mContext.enforceCallingOrSelfPermission(
9895                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9896                "Only package verification agents can extend verification timeouts");
9897
9898        final PackageVerificationState state = mPendingVerification.get(id);
9899        final PackageVerificationResponse response = new PackageVerificationResponse(
9900                verificationCodeAtTimeout, Binder.getCallingUid());
9901
9902        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9903            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9904        }
9905        if (millisecondsToDelay < 0) {
9906            millisecondsToDelay = 0;
9907        }
9908        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9909                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9910            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9911        }
9912
9913        if ((state != null) && !state.timeoutExtended()) {
9914            state.extendTimeout();
9915
9916            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9917            msg.arg1 = id;
9918            msg.obj = response;
9919            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9920        }
9921    }
9922
9923    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9924            int verificationCode, UserHandle user) {
9925        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9926        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9927        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9928        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9929        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9930
9931        mContext.sendBroadcastAsUser(intent, user,
9932                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9933    }
9934
9935    private ComponentName matchComponentForVerifier(String packageName,
9936            List<ResolveInfo> receivers) {
9937        ActivityInfo targetReceiver = null;
9938
9939        final int NR = receivers.size();
9940        for (int i = 0; i < NR; i++) {
9941            final ResolveInfo info = receivers.get(i);
9942            if (info.activityInfo == null) {
9943                continue;
9944            }
9945
9946            if (packageName.equals(info.activityInfo.packageName)) {
9947                targetReceiver = info.activityInfo;
9948                break;
9949            }
9950        }
9951
9952        if (targetReceiver == null) {
9953            return null;
9954        }
9955
9956        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9957    }
9958
9959    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9960            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9961        if (pkgInfo.verifiers.length == 0) {
9962            return null;
9963        }
9964
9965        final int N = pkgInfo.verifiers.length;
9966        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9967        for (int i = 0; i < N; i++) {
9968            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9969
9970            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9971                    receivers);
9972            if (comp == null) {
9973                continue;
9974            }
9975
9976            final int verifierUid = getUidForVerifier(verifierInfo);
9977            if (verifierUid == -1) {
9978                continue;
9979            }
9980
9981            if (DEBUG_VERIFY) {
9982                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9983                        + " with the correct signature");
9984            }
9985            sufficientVerifiers.add(comp);
9986            verificationState.addSufficientVerifier(verifierUid);
9987        }
9988
9989        return sufficientVerifiers;
9990    }
9991
9992    private int getUidForVerifier(VerifierInfo verifierInfo) {
9993        synchronized (mPackages) {
9994            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9995            if (pkg == null) {
9996                return -1;
9997            } else if (pkg.mSignatures.length != 1) {
9998                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9999                        + " has more than one signature; ignoring");
10000                return -1;
10001            }
10002
10003            /*
10004             * If the public key of the package's signature does not match
10005             * our expected public key, then this is a different package and
10006             * we should skip.
10007             */
10008
10009            final byte[] expectedPublicKey;
10010            try {
10011                final Signature verifierSig = pkg.mSignatures[0];
10012                final PublicKey publicKey = verifierSig.getPublicKey();
10013                expectedPublicKey = publicKey.getEncoded();
10014            } catch (CertificateException e) {
10015                return -1;
10016            }
10017
10018            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10019
10020            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10021                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10022                        + " does not have the expected public key; ignoring");
10023                return -1;
10024            }
10025
10026            return pkg.applicationInfo.uid;
10027        }
10028    }
10029
10030    @Override
10031    public void finishPackageInstall(int token) {
10032        enforceSystemOrRoot("Only the system is allowed to finish installs");
10033
10034        if (DEBUG_INSTALL) {
10035            Slog.v(TAG, "BM finishing package install for " + token);
10036        }
10037        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10038
10039        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10040        mHandler.sendMessage(msg);
10041    }
10042
10043    /**
10044     * Get the verification agent timeout.
10045     *
10046     * @return verification timeout in milliseconds
10047     */
10048    private long getVerificationTimeout() {
10049        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10050                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10051                DEFAULT_VERIFICATION_TIMEOUT);
10052    }
10053
10054    /**
10055     * Get the default verification agent response code.
10056     *
10057     * @return default verification response code
10058     */
10059    private int getDefaultVerificationResponse() {
10060        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10061                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10062                DEFAULT_VERIFICATION_RESPONSE);
10063    }
10064
10065    /**
10066     * Check whether or not package verification has been enabled.
10067     *
10068     * @return true if verification should be performed
10069     */
10070    private boolean isVerificationEnabled(int userId, int installFlags) {
10071        if (!DEFAULT_VERIFY_ENABLE) {
10072            return false;
10073        }
10074
10075        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10076
10077        // Check if installing from ADB
10078        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10079            // Do not run verification in a test harness environment
10080            if (ActivityManager.isRunningInTestHarness()) {
10081                return false;
10082            }
10083            if (ensureVerifyAppsEnabled) {
10084                return true;
10085            }
10086            // Check if the developer does not want package verification for ADB installs
10087            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10088                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10089                return false;
10090            }
10091        }
10092
10093        if (ensureVerifyAppsEnabled) {
10094            return true;
10095        }
10096
10097        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10098                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10099    }
10100
10101    @Override
10102    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10103            throws RemoteException {
10104        mContext.enforceCallingOrSelfPermission(
10105                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10106                "Only intentfilter verification agents can verify applications");
10107
10108        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10109        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10110                Binder.getCallingUid(), verificationCode, failedDomains);
10111        msg.arg1 = id;
10112        msg.obj = response;
10113        mHandler.sendMessage(msg);
10114    }
10115
10116    @Override
10117    public int getIntentVerificationStatus(String packageName, int userId) {
10118        synchronized (mPackages) {
10119            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10120        }
10121    }
10122
10123    @Override
10124    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10125        mContext.enforceCallingOrSelfPermission(
10126                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10127
10128        boolean result = false;
10129        synchronized (mPackages) {
10130            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10131        }
10132        if (result) {
10133            scheduleWritePackageRestrictionsLocked(userId);
10134        }
10135        return result;
10136    }
10137
10138    @Override
10139    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10140        synchronized (mPackages) {
10141            return mSettings.getIntentFilterVerificationsLPr(packageName);
10142        }
10143    }
10144
10145    @Override
10146    public List<IntentFilter> getAllIntentFilters(String packageName) {
10147        if (TextUtils.isEmpty(packageName)) {
10148            return Collections.<IntentFilter>emptyList();
10149        }
10150        synchronized (mPackages) {
10151            PackageParser.Package pkg = mPackages.get(packageName);
10152            if (pkg == null || pkg.activities == null) {
10153                return Collections.<IntentFilter>emptyList();
10154            }
10155            final int count = pkg.activities.size();
10156            ArrayList<IntentFilter> result = new ArrayList<>();
10157            for (int n=0; n<count; n++) {
10158                PackageParser.Activity activity = pkg.activities.get(n);
10159                if (activity.intents != null || activity.intents.size() > 0) {
10160                    result.addAll(activity.intents);
10161                }
10162            }
10163            return result;
10164        }
10165    }
10166
10167    @Override
10168    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10169        mContext.enforceCallingOrSelfPermission(
10170                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10171
10172        synchronized (mPackages) {
10173            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10174            if (packageName != null) {
10175                result |= updateIntentVerificationStatus(packageName,
10176                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10177                        userId);
10178                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10179                        packageName, userId);
10180            }
10181            return result;
10182        }
10183    }
10184
10185    @Override
10186    public String getDefaultBrowserPackageName(int userId) {
10187        synchronized (mPackages) {
10188            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10189        }
10190    }
10191
10192    /**
10193     * Get the "allow unknown sources" setting.
10194     *
10195     * @return the current "allow unknown sources" setting
10196     */
10197    private int getUnknownSourcesSettings() {
10198        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10199                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10200                -1);
10201    }
10202
10203    @Override
10204    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10205        final int uid = Binder.getCallingUid();
10206        // writer
10207        synchronized (mPackages) {
10208            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10209            if (targetPackageSetting == null) {
10210                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10211            }
10212
10213            PackageSetting installerPackageSetting;
10214            if (installerPackageName != null) {
10215                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10216                if (installerPackageSetting == null) {
10217                    throw new IllegalArgumentException("Unknown installer package: "
10218                            + installerPackageName);
10219                }
10220            } else {
10221                installerPackageSetting = null;
10222            }
10223
10224            Signature[] callerSignature;
10225            Object obj = mSettings.getUserIdLPr(uid);
10226            if (obj != null) {
10227                if (obj instanceof SharedUserSetting) {
10228                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10229                } else if (obj instanceof PackageSetting) {
10230                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10231                } else {
10232                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10233                }
10234            } else {
10235                throw new SecurityException("Unknown calling uid " + uid);
10236            }
10237
10238            // Verify: can't set installerPackageName to a package that is
10239            // not signed with the same cert as the caller.
10240            if (installerPackageSetting != null) {
10241                if (compareSignatures(callerSignature,
10242                        installerPackageSetting.signatures.mSignatures)
10243                        != PackageManager.SIGNATURE_MATCH) {
10244                    throw new SecurityException(
10245                            "Caller does not have same cert as new installer package "
10246                            + installerPackageName);
10247                }
10248            }
10249
10250            // Verify: if target already has an installer package, it must
10251            // be signed with the same cert as the caller.
10252            if (targetPackageSetting.installerPackageName != null) {
10253                PackageSetting setting = mSettings.mPackages.get(
10254                        targetPackageSetting.installerPackageName);
10255                // If the currently set package isn't valid, then it's always
10256                // okay to change it.
10257                if (setting != null) {
10258                    if (compareSignatures(callerSignature,
10259                            setting.signatures.mSignatures)
10260                            != PackageManager.SIGNATURE_MATCH) {
10261                        throw new SecurityException(
10262                                "Caller does not have same cert as old installer package "
10263                                + targetPackageSetting.installerPackageName);
10264                    }
10265                }
10266            }
10267
10268            // Okay!
10269            targetPackageSetting.installerPackageName = installerPackageName;
10270            scheduleWriteSettingsLocked();
10271        }
10272    }
10273
10274    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10275        // Queue up an async operation since the package installation may take a little while.
10276        mHandler.post(new Runnable() {
10277            public void run() {
10278                mHandler.removeCallbacks(this);
10279                 // Result object to be returned
10280                PackageInstalledInfo res = new PackageInstalledInfo();
10281                res.returnCode = currentStatus;
10282                res.uid = -1;
10283                res.pkg = null;
10284                res.removedInfo = new PackageRemovedInfo();
10285                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10286                    args.doPreInstall(res.returnCode);
10287                    synchronized (mInstallLock) {
10288                        installPackageTracedLI(args, res);
10289                    }
10290                    args.doPostInstall(res.returnCode, res.uid);
10291                }
10292
10293                // A restore should be performed at this point if (a) the install
10294                // succeeded, (b) the operation is not an update, and (c) the new
10295                // package has not opted out of backup participation.
10296                final boolean update = res.removedInfo.removedPackage != null;
10297                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10298                boolean doRestore = !update
10299                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10300
10301                // Set up the post-install work request bookkeeping.  This will be used
10302                // and cleaned up by the post-install event handling regardless of whether
10303                // there's a restore pass performed.  Token values are >= 1.
10304                int token;
10305                if (mNextInstallToken < 0) mNextInstallToken = 1;
10306                token = mNextInstallToken++;
10307
10308                PostInstallData data = new PostInstallData(args, res);
10309                mRunningInstalls.put(token, data);
10310                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10311
10312                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10313                    // Pass responsibility to the Backup Manager.  It will perform a
10314                    // restore if appropriate, then pass responsibility back to the
10315                    // Package Manager to run the post-install observer callbacks
10316                    // and broadcasts.
10317                    IBackupManager bm = IBackupManager.Stub.asInterface(
10318                            ServiceManager.getService(Context.BACKUP_SERVICE));
10319                    if (bm != null) {
10320                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10321                                + " to BM for possible restore");
10322                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10323                        try {
10324                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10325                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10326                            } else {
10327                                doRestore = false;
10328                            }
10329                        } catch (RemoteException e) {
10330                            // can't happen; the backup manager is local
10331                        } catch (Exception e) {
10332                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10333                            doRestore = false;
10334                        }
10335                    } else {
10336                        Slog.e(TAG, "Backup Manager not found!");
10337                        doRestore = false;
10338                    }
10339                }
10340
10341                if (!doRestore) {
10342                    // No restore possible, or the Backup Manager was mysteriously not
10343                    // available -- just fire the post-install work request directly.
10344                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10345
10346                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10347
10348                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10349                    mHandler.sendMessage(msg);
10350                }
10351            }
10352        });
10353    }
10354
10355    private abstract class HandlerParams {
10356        private static final int MAX_RETRIES = 4;
10357
10358        /**
10359         * Number of times startCopy() has been attempted and had a non-fatal
10360         * error.
10361         */
10362        private int mRetries = 0;
10363
10364        /** User handle for the user requesting the information or installation. */
10365        private final UserHandle mUser;
10366        String traceMethod;
10367        int traceCookie;
10368
10369        HandlerParams(UserHandle user) {
10370            mUser = user;
10371        }
10372
10373        UserHandle getUser() {
10374            return mUser;
10375        }
10376
10377        HandlerParams setTraceMethod(String traceMethod) {
10378            this.traceMethod = traceMethod;
10379            return this;
10380        }
10381
10382        HandlerParams setTraceCookie(int traceCookie) {
10383            this.traceCookie = traceCookie;
10384            return this;
10385        }
10386
10387        final boolean startCopy() {
10388            boolean res;
10389            try {
10390                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10391
10392                if (++mRetries > MAX_RETRIES) {
10393                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10394                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10395                    handleServiceError();
10396                    return false;
10397                } else {
10398                    handleStartCopy();
10399                    res = true;
10400                }
10401            } catch (RemoteException e) {
10402                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10403                mHandler.sendEmptyMessage(MCS_RECONNECT);
10404                res = false;
10405            }
10406            handleReturnCode();
10407            return res;
10408        }
10409
10410        final void serviceError() {
10411            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10412            handleServiceError();
10413            handleReturnCode();
10414        }
10415
10416        abstract void handleStartCopy() throws RemoteException;
10417        abstract void handleServiceError();
10418        abstract void handleReturnCode();
10419    }
10420
10421    class MeasureParams extends HandlerParams {
10422        private final PackageStats mStats;
10423        private boolean mSuccess;
10424
10425        private final IPackageStatsObserver mObserver;
10426
10427        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10428            super(new UserHandle(stats.userHandle));
10429            mObserver = observer;
10430            mStats = stats;
10431        }
10432
10433        @Override
10434        public String toString() {
10435            return "MeasureParams{"
10436                + Integer.toHexString(System.identityHashCode(this))
10437                + " " + mStats.packageName + "}";
10438        }
10439
10440        @Override
10441        void handleStartCopy() throws RemoteException {
10442            synchronized (mInstallLock) {
10443                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10444            }
10445
10446            if (mSuccess) {
10447                final boolean mounted;
10448                if (Environment.isExternalStorageEmulated()) {
10449                    mounted = true;
10450                } else {
10451                    final String status = Environment.getExternalStorageState();
10452                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10453                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10454                }
10455
10456                if (mounted) {
10457                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10458
10459                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10460                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10461
10462                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10463                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10464
10465                    // Always subtract cache size, since it's a subdirectory
10466                    mStats.externalDataSize -= mStats.externalCacheSize;
10467
10468                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10469                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10470
10471                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10472                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10473                }
10474            }
10475        }
10476
10477        @Override
10478        void handleReturnCode() {
10479            if (mObserver != null) {
10480                try {
10481                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10482                } catch (RemoteException e) {
10483                    Slog.i(TAG, "Observer no longer exists.");
10484                }
10485            }
10486        }
10487
10488        @Override
10489        void handleServiceError() {
10490            Slog.e(TAG, "Could not measure application " + mStats.packageName
10491                            + " external storage");
10492        }
10493    }
10494
10495    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10496            throws RemoteException {
10497        long result = 0;
10498        for (File path : paths) {
10499            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10500        }
10501        return result;
10502    }
10503
10504    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10505        for (File path : paths) {
10506            try {
10507                mcs.clearDirectory(path.getAbsolutePath());
10508            } catch (RemoteException e) {
10509            }
10510        }
10511    }
10512
10513    static class OriginInfo {
10514        /**
10515         * Location where install is coming from, before it has been
10516         * copied/renamed into place. This could be a single monolithic APK
10517         * file, or a cluster directory. This location may be untrusted.
10518         */
10519        final File file;
10520        final String cid;
10521
10522        /**
10523         * Flag indicating that {@link #file} or {@link #cid} has already been
10524         * staged, meaning downstream users don't need to defensively copy the
10525         * contents.
10526         */
10527        final boolean staged;
10528
10529        /**
10530         * Flag indicating that {@link #file} or {@link #cid} is an already
10531         * installed app that is being moved.
10532         */
10533        final boolean existing;
10534
10535        final String resolvedPath;
10536        final File resolvedFile;
10537
10538        static OriginInfo fromNothing() {
10539            return new OriginInfo(null, null, false, false);
10540        }
10541
10542        static OriginInfo fromUntrustedFile(File file) {
10543            return new OriginInfo(file, null, false, false);
10544        }
10545
10546        static OriginInfo fromExistingFile(File file) {
10547            return new OriginInfo(file, null, false, true);
10548        }
10549
10550        static OriginInfo fromStagedFile(File file) {
10551            return new OriginInfo(file, null, true, false);
10552        }
10553
10554        static OriginInfo fromStagedContainer(String cid) {
10555            return new OriginInfo(null, cid, true, false);
10556        }
10557
10558        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10559            this.file = file;
10560            this.cid = cid;
10561            this.staged = staged;
10562            this.existing = existing;
10563
10564            if (cid != null) {
10565                resolvedPath = PackageHelper.getSdDir(cid);
10566                resolvedFile = new File(resolvedPath);
10567            } else if (file != null) {
10568                resolvedPath = file.getAbsolutePath();
10569                resolvedFile = file;
10570            } else {
10571                resolvedPath = null;
10572                resolvedFile = null;
10573            }
10574        }
10575    }
10576
10577    class MoveInfo {
10578        final int moveId;
10579        final String fromUuid;
10580        final String toUuid;
10581        final String packageName;
10582        final String dataAppName;
10583        final int appId;
10584        final String seinfo;
10585
10586        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10587                String dataAppName, int appId, String seinfo) {
10588            this.moveId = moveId;
10589            this.fromUuid = fromUuid;
10590            this.toUuid = toUuid;
10591            this.packageName = packageName;
10592            this.dataAppName = dataAppName;
10593            this.appId = appId;
10594            this.seinfo = seinfo;
10595        }
10596    }
10597
10598    class InstallParams extends HandlerParams {
10599        final OriginInfo origin;
10600        final MoveInfo move;
10601        final IPackageInstallObserver2 observer;
10602        int installFlags;
10603        final String installerPackageName;
10604        final String volumeUuid;
10605        final VerificationParams verificationParams;
10606        private InstallArgs mArgs;
10607        private int mRet;
10608        final String packageAbiOverride;
10609        final String[] grantedRuntimePermissions;
10610
10611        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10612                int installFlags, String installerPackageName, String volumeUuid,
10613                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10614                String[] grantedPermissions) {
10615            super(user);
10616            this.origin = origin;
10617            this.move = move;
10618            this.observer = observer;
10619            this.installFlags = installFlags;
10620            this.installerPackageName = installerPackageName;
10621            this.volumeUuid = volumeUuid;
10622            this.verificationParams = verificationParams;
10623            this.packageAbiOverride = packageAbiOverride;
10624            this.grantedRuntimePermissions = grantedPermissions;
10625        }
10626
10627        @Override
10628        public String toString() {
10629            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10630                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10631        }
10632
10633        public ManifestDigest getManifestDigest() {
10634            if (verificationParams == null) {
10635                return null;
10636            }
10637            return verificationParams.getManifestDigest();
10638        }
10639
10640        private int installLocationPolicy(PackageInfoLite pkgLite) {
10641            String packageName = pkgLite.packageName;
10642            int installLocation = pkgLite.installLocation;
10643            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10644            // reader
10645            synchronized (mPackages) {
10646                PackageParser.Package pkg = mPackages.get(packageName);
10647                if (pkg != null) {
10648                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10649                        // Check for downgrading.
10650                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10651                            try {
10652                                checkDowngrade(pkg, pkgLite);
10653                            } catch (PackageManagerException e) {
10654                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10655                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10656                            }
10657                        }
10658                        // Check for updated system application.
10659                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10660                            if (onSd) {
10661                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10662                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10663                            }
10664                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10665                        } else {
10666                            if (onSd) {
10667                                // Install flag overrides everything.
10668                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10669                            }
10670                            // If current upgrade specifies particular preference
10671                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10672                                // Application explicitly specified internal.
10673                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10674                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10675                                // App explictly prefers external. Let policy decide
10676                            } else {
10677                                // Prefer previous location
10678                                if (isExternal(pkg)) {
10679                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10680                                }
10681                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10682                            }
10683                        }
10684                    } else {
10685                        // Invalid install. Return error code
10686                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10687                    }
10688                }
10689            }
10690            // All the special cases have been taken care of.
10691            // Return result based on recommended install location.
10692            if (onSd) {
10693                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10694            }
10695            return pkgLite.recommendedInstallLocation;
10696        }
10697
10698        /*
10699         * Invoke remote method to get package information and install
10700         * location values. Override install location based on default
10701         * policy if needed and then create install arguments based
10702         * on the install location.
10703         */
10704        public void handleStartCopy() throws RemoteException {
10705            int ret = PackageManager.INSTALL_SUCCEEDED;
10706
10707            // If we're already staged, we've firmly committed to an install location
10708            if (origin.staged) {
10709                if (origin.file != null) {
10710                    installFlags |= PackageManager.INSTALL_INTERNAL;
10711                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10712                } else if (origin.cid != null) {
10713                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10714                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10715                } else {
10716                    throw new IllegalStateException("Invalid stage location");
10717                }
10718            }
10719
10720            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10721            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10722            PackageInfoLite pkgLite = null;
10723
10724            if (onInt && onSd) {
10725                // Check if both bits are set.
10726                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10727                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10728            } else {
10729                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10730                        packageAbiOverride);
10731
10732                /*
10733                 * If we have too little free space, try to free cache
10734                 * before giving up.
10735                 */
10736                if (!origin.staged && pkgLite.recommendedInstallLocation
10737                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10738                    // TODO: focus freeing disk space on the target device
10739                    final StorageManager storage = StorageManager.from(mContext);
10740                    final long lowThreshold = storage.getStorageLowBytes(
10741                            Environment.getDataDirectory());
10742
10743                    final long sizeBytes = mContainerService.calculateInstalledSize(
10744                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10745
10746                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10747                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10748                                installFlags, packageAbiOverride);
10749                    }
10750
10751                    /*
10752                     * The cache free must have deleted the file we
10753                     * downloaded to install.
10754                     *
10755                     * TODO: fix the "freeCache" call to not delete
10756                     *       the file we care about.
10757                     */
10758                    if (pkgLite.recommendedInstallLocation
10759                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10760                        pkgLite.recommendedInstallLocation
10761                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10762                    }
10763                }
10764            }
10765
10766            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10767                int loc = pkgLite.recommendedInstallLocation;
10768                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10769                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10770                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10771                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10772                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10773                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10774                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10775                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10776                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10777                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10778                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10779                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10780                } else {
10781                    // Override with defaults if needed.
10782                    loc = installLocationPolicy(pkgLite);
10783                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10784                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10785                    } else if (!onSd && !onInt) {
10786                        // Override install location with flags
10787                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10788                            // Set the flag to install on external media.
10789                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10790                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10791                        } else {
10792                            // Make sure the flag for installing on external
10793                            // media is unset
10794                            installFlags |= PackageManager.INSTALL_INTERNAL;
10795                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10796                        }
10797                    }
10798                }
10799            }
10800
10801            final InstallArgs args = createInstallArgs(this);
10802            mArgs = args;
10803
10804            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10805                 /*
10806                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10807                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10808                 */
10809                int userIdentifier = getUser().getIdentifier();
10810                if (userIdentifier == UserHandle.USER_ALL
10811                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10812                    userIdentifier = UserHandle.USER_OWNER;
10813                }
10814
10815                /*
10816                 * Determine if we have any installed package verifiers. If we
10817                 * do, then we'll defer to them to verify the packages.
10818                 */
10819                final int requiredUid = mRequiredVerifierPackage == null ? -1
10820                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10821                if (!origin.existing && requiredUid != -1
10822                        && isVerificationEnabled(userIdentifier, installFlags)) {
10823                    final Intent verification = new Intent(
10824                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10825                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10826                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10827                            PACKAGE_MIME_TYPE);
10828                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10829
10830                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10831                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10832                            0 /* TODO: Which userId? */);
10833
10834                    if (DEBUG_VERIFY) {
10835                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10836                                + verification.toString() + " with " + pkgLite.verifiers.length
10837                                + " optional verifiers");
10838                    }
10839
10840                    final int verificationId = mPendingVerificationToken++;
10841
10842                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10843
10844                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10845                            installerPackageName);
10846
10847                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10848                            installFlags);
10849
10850                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10851                            pkgLite.packageName);
10852
10853                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10854                            pkgLite.versionCode);
10855
10856                    if (verificationParams != null) {
10857                        if (verificationParams.getVerificationURI() != null) {
10858                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10859                                 verificationParams.getVerificationURI());
10860                        }
10861                        if (verificationParams.getOriginatingURI() != null) {
10862                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10863                                  verificationParams.getOriginatingURI());
10864                        }
10865                        if (verificationParams.getReferrer() != null) {
10866                            verification.putExtra(Intent.EXTRA_REFERRER,
10867                                  verificationParams.getReferrer());
10868                        }
10869                        if (verificationParams.getOriginatingUid() >= 0) {
10870                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10871                                  verificationParams.getOriginatingUid());
10872                        }
10873                        if (verificationParams.getInstallerUid() >= 0) {
10874                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10875                                  verificationParams.getInstallerUid());
10876                        }
10877                    }
10878
10879                    final PackageVerificationState verificationState = new PackageVerificationState(
10880                            requiredUid, args);
10881
10882                    mPendingVerification.append(verificationId, verificationState);
10883
10884                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10885                            receivers, verificationState);
10886
10887                    // Apps installed for "all" users use the device owner to verify the app
10888                    UserHandle verifierUser = getUser();
10889                    if (verifierUser == UserHandle.ALL) {
10890                        verifierUser = UserHandle.OWNER;
10891                    }
10892
10893                    /*
10894                     * If any sufficient verifiers were listed in the package
10895                     * manifest, attempt to ask them.
10896                     */
10897                    if (sufficientVerifiers != null) {
10898                        final int N = sufficientVerifiers.size();
10899                        if (N == 0) {
10900                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10901                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10902                        } else {
10903                            for (int i = 0; i < N; i++) {
10904                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10905
10906                                final Intent sufficientIntent = new Intent(verification);
10907                                sufficientIntent.setComponent(verifierComponent);
10908                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10909                            }
10910                        }
10911                    }
10912
10913                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10914                            mRequiredVerifierPackage, receivers);
10915                    if (ret == PackageManager.INSTALL_SUCCEEDED
10916                            && mRequiredVerifierPackage != null) {
10917                        Trace.asyncTraceBegin(
10918                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
10919                        /*
10920                         * Send the intent to the required verification agent,
10921                         * but only start the verification timeout after the
10922                         * target BroadcastReceivers have run.
10923                         */
10924                        verification.setComponent(requiredVerifierComponent);
10925                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10926                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10927                                new BroadcastReceiver() {
10928                                    @Override
10929                                    public void onReceive(Context context, Intent intent) {
10930                                        final Message msg = mHandler
10931                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10932                                        msg.arg1 = verificationId;
10933                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10934                                    }
10935                                }, null, 0, null, null);
10936
10937                        /*
10938                         * We don't want the copy to proceed until verification
10939                         * succeeds, so null out this field.
10940                         */
10941                        mArgs = null;
10942                    }
10943                } else {
10944                    /*
10945                     * No package verification is enabled, so immediately start
10946                     * the remote call to initiate copy using temporary file.
10947                     */
10948                    ret = args.copyApk(mContainerService, true);
10949                }
10950            }
10951
10952            mRet = ret;
10953        }
10954
10955        @Override
10956        void handleReturnCode() {
10957            // If mArgs is null, then MCS couldn't be reached. When it
10958            // reconnects, it will try again to install. At that point, this
10959            // will succeed.
10960            if (mArgs != null) {
10961                processPendingInstall(mArgs, mRet);
10962            }
10963        }
10964
10965        @Override
10966        void handleServiceError() {
10967            mArgs = createInstallArgs(this);
10968            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10969        }
10970
10971        public boolean isForwardLocked() {
10972            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10973        }
10974    }
10975
10976    /**
10977     * Used during creation of InstallArgs
10978     *
10979     * @param installFlags package installation flags
10980     * @return true if should be installed on external storage
10981     */
10982    private static boolean installOnExternalAsec(int installFlags) {
10983        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10984            return false;
10985        }
10986        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10987            return true;
10988        }
10989        return false;
10990    }
10991
10992    /**
10993     * Used during creation of InstallArgs
10994     *
10995     * @param installFlags package installation flags
10996     * @return true if should be installed as forward locked
10997     */
10998    private static boolean installForwardLocked(int installFlags) {
10999        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11000    }
11001
11002    private InstallArgs createInstallArgs(InstallParams params) {
11003        if (params.move != null) {
11004            return new MoveInstallArgs(params);
11005        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11006            return new AsecInstallArgs(params);
11007        } else {
11008            return new FileInstallArgs(params);
11009        }
11010    }
11011
11012    /**
11013     * Create args that describe an existing installed package. Typically used
11014     * when cleaning up old installs, or used as a move source.
11015     */
11016    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11017            String resourcePath, String[] instructionSets) {
11018        final boolean isInAsec;
11019        if (installOnExternalAsec(installFlags)) {
11020            /* Apps on SD card are always in ASEC containers. */
11021            isInAsec = true;
11022        } else if (installForwardLocked(installFlags)
11023                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11024            /*
11025             * Forward-locked apps are only in ASEC containers if they're the
11026             * new style
11027             */
11028            isInAsec = true;
11029        } else {
11030            isInAsec = false;
11031        }
11032
11033        if (isInAsec) {
11034            return new AsecInstallArgs(codePath, instructionSets,
11035                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11036        } else {
11037            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11038        }
11039    }
11040
11041    static abstract class InstallArgs {
11042        /** @see InstallParams#origin */
11043        final OriginInfo origin;
11044        /** @see InstallParams#move */
11045        final MoveInfo move;
11046
11047        final IPackageInstallObserver2 observer;
11048        // Always refers to PackageManager flags only
11049        final int installFlags;
11050        final String installerPackageName;
11051        final String volumeUuid;
11052        final ManifestDigest manifestDigest;
11053        final UserHandle user;
11054        final String abiOverride;
11055        final String[] installGrantPermissions;
11056        /** If non-null, drop an async trace when the install completes */
11057        final String traceMethod;
11058        final int traceCookie;
11059
11060        // The list of instruction sets supported by this app. This is currently
11061        // only used during the rmdex() phase to clean up resources. We can get rid of this
11062        // if we move dex files under the common app path.
11063        /* nullable */ String[] instructionSets;
11064
11065        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11066                int installFlags, String installerPackageName, String volumeUuid,
11067                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11068                String abiOverride, String[] installGrantPermissions,
11069                String traceMethod, int traceCookie) {
11070            this.origin = origin;
11071            this.move = move;
11072            this.installFlags = installFlags;
11073            this.observer = observer;
11074            this.installerPackageName = installerPackageName;
11075            this.volumeUuid = volumeUuid;
11076            this.manifestDigest = manifestDigest;
11077            this.user = user;
11078            this.instructionSets = instructionSets;
11079            this.abiOverride = abiOverride;
11080            this.installGrantPermissions = installGrantPermissions;
11081            this.traceMethod = traceMethod;
11082            this.traceCookie = traceCookie;
11083        }
11084
11085        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11086        abstract int doPreInstall(int status);
11087
11088        /**
11089         * Rename package into final resting place. All paths on the given
11090         * scanned package should be updated to reflect the rename.
11091         */
11092        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11093        abstract int doPostInstall(int status, int uid);
11094
11095        /** @see PackageSettingBase#codePathString */
11096        abstract String getCodePath();
11097        /** @see PackageSettingBase#resourcePathString */
11098        abstract String getResourcePath();
11099
11100        // Need installer lock especially for dex file removal.
11101        abstract void cleanUpResourcesLI();
11102        abstract boolean doPostDeleteLI(boolean delete);
11103
11104        /**
11105         * Called before the source arguments are copied. This is used mostly
11106         * for MoveParams when it needs to read the source file to put it in the
11107         * destination.
11108         */
11109        int doPreCopy() {
11110            return PackageManager.INSTALL_SUCCEEDED;
11111        }
11112
11113        /**
11114         * Called after the source arguments are copied. This is used mostly for
11115         * MoveParams when it needs to read the source file to put it in the
11116         * destination.
11117         *
11118         * @return
11119         */
11120        int doPostCopy(int uid) {
11121            return PackageManager.INSTALL_SUCCEEDED;
11122        }
11123
11124        protected boolean isFwdLocked() {
11125            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11126        }
11127
11128        protected boolean isExternalAsec() {
11129            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11130        }
11131
11132        UserHandle getUser() {
11133            return user;
11134        }
11135    }
11136
11137    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11138        if (!allCodePaths.isEmpty()) {
11139            if (instructionSets == null) {
11140                throw new IllegalStateException("instructionSet == null");
11141            }
11142            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11143            for (String codePath : allCodePaths) {
11144                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11145                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11146                    if (retCode < 0) {
11147                        Slog.w(TAG, "Couldn't remove dex file for package: "
11148                                + " at location " + codePath + ", retcode=" + retCode);
11149                        // we don't consider this to be a failure of the core package deletion
11150                    }
11151                }
11152            }
11153        }
11154    }
11155
11156    /**
11157     * Logic to handle installation of non-ASEC applications, including copying
11158     * and renaming logic.
11159     */
11160    class FileInstallArgs extends InstallArgs {
11161        private File codeFile;
11162        private File resourceFile;
11163
11164        // Example topology:
11165        // /data/app/com.example/base.apk
11166        // /data/app/com.example/split_foo.apk
11167        // /data/app/com.example/lib/arm/libfoo.so
11168        // /data/app/com.example/lib/arm64/libfoo.so
11169        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11170
11171        /** New install */
11172        FileInstallArgs(InstallParams params) {
11173            super(params.origin, params.move, params.observer, params.installFlags,
11174                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11175                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11176                    params.grantedRuntimePermissions,
11177                    params.traceMethod, params.traceCookie);
11178            if (isFwdLocked()) {
11179                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11180            }
11181        }
11182
11183        /** Existing install */
11184        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11185            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11186                    null, null, null, 0);
11187            this.codeFile = (codePath != null) ? new File(codePath) : null;
11188            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11189        }
11190
11191        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11192            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11193            try {
11194                return doCopyApk(imcs, temp);
11195            } finally {
11196                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11197            }
11198        }
11199
11200        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11201            if (origin.staged) {
11202                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11203                codeFile = origin.file;
11204                resourceFile = origin.file;
11205                return PackageManager.INSTALL_SUCCEEDED;
11206            }
11207
11208            try {
11209                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11210                codeFile = tempDir;
11211                resourceFile = tempDir;
11212            } catch (IOException e) {
11213                Slog.w(TAG, "Failed to create copy file: " + e);
11214                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11215            }
11216
11217            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11218                @Override
11219                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11220                    if (!FileUtils.isValidExtFilename(name)) {
11221                        throw new IllegalArgumentException("Invalid filename: " + name);
11222                    }
11223                    try {
11224                        final File file = new File(codeFile, name);
11225                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11226                                O_RDWR | O_CREAT, 0644);
11227                        Os.chmod(file.getAbsolutePath(), 0644);
11228                        return new ParcelFileDescriptor(fd);
11229                    } catch (ErrnoException e) {
11230                        throw new RemoteException("Failed to open: " + e.getMessage());
11231                    }
11232                }
11233            };
11234
11235            int ret = PackageManager.INSTALL_SUCCEEDED;
11236            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11237            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11238                Slog.e(TAG, "Failed to copy package");
11239                return ret;
11240            }
11241
11242            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11243            NativeLibraryHelper.Handle handle = null;
11244            try {
11245                handle = NativeLibraryHelper.Handle.create(codeFile);
11246                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11247                        abiOverride);
11248            } catch (IOException e) {
11249                Slog.e(TAG, "Copying native libraries failed", e);
11250                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11251            } finally {
11252                IoUtils.closeQuietly(handle);
11253            }
11254
11255            return ret;
11256        }
11257
11258        int doPreInstall(int status) {
11259            if (status != PackageManager.INSTALL_SUCCEEDED) {
11260                cleanUp();
11261            }
11262            return status;
11263        }
11264
11265        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11266            if (status != PackageManager.INSTALL_SUCCEEDED) {
11267                cleanUp();
11268                return false;
11269            }
11270
11271            final File targetDir = codeFile.getParentFile();
11272            final File beforeCodeFile = codeFile;
11273            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11274
11275            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11276            try {
11277                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11278            } catch (ErrnoException e) {
11279                Slog.w(TAG, "Failed to rename", e);
11280                return false;
11281            }
11282
11283            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11284                Slog.w(TAG, "Failed to restorecon");
11285                return false;
11286            }
11287
11288            // Reflect the rename internally
11289            codeFile = afterCodeFile;
11290            resourceFile = afterCodeFile;
11291
11292            // Reflect the rename in scanned details
11293            pkg.codePath = afterCodeFile.getAbsolutePath();
11294            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11295                    pkg.baseCodePath);
11296            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11297                    pkg.splitCodePaths);
11298
11299            // Reflect the rename in app info
11300            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11301            pkg.applicationInfo.setCodePath(pkg.codePath);
11302            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11303            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11304            pkg.applicationInfo.setResourcePath(pkg.codePath);
11305            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11306            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11307
11308            return true;
11309        }
11310
11311        int doPostInstall(int status, int uid) {
11312            if (status != PackageManager.INSTALL_SUCCEEDED) {
11313                cleanUp();
11314            }
11315            return status;
11316        }
11317
11318        @Override
11319        String getCodePath() {
11320            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11321        }
11322
11323        @Override
11324        String getResourcePath() {
11325            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11326        }
11327
11328        private boolean cleanUp() {
11329            if (codeFile == null || !codeFile.exists()) {
11330                return false;
11331            }
11332
11333            if (codeFile.isDirectory()) {
11334                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11335            } else {
11336                codeFile.delete();
11337            }
11338
11339            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11340                resourceFile.delete();
11341            }
11342
11343            return true;
11344        }
11345
11346        void cleanUpResourcesLI() {
11347            // Try enumerating all code paths before deleting
11348            List<String> allCodePaths = Collections.EMPTY_LIST;
11349            if (codeFile != null && codeFile.exists()) {
11350                try {
11351                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11352                    allCodePaths = pkg.getAllCodePaths();
11353                } catch (PackageParserException e) {
11354                    // Ignored; we tried our best
11355                }
11356            }
11357
11358            cleanUp();
11359            removeDexFiles(allCodePaths, instructionSets);
11360        }
11361
11362        boolean doPostDeleteLI(boolean delete) {
11363            // XXX err, shouldn't we respect the delete flag?
11364            cleanUpResourcesLI();
11365            return true;
11366        }
11367    }
11368
11369    private boolean isAsecExternal(String cid) {
11370        final String asecPath = PackageHelper.getSdFilesystem(cid);
11371        return !asecPath.startsWith(mAsecInternalPath);
11372    }
11373
11374    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11375            PackageManagerException {
11376        if (copyRet < 0) {
11377            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11378                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11379                throw new PackageManagerException(copyRet, message);
11380            }
11381        }
11382    }
11383
11384    /**
11385     * Extract the MountService "container ID" from the full code path of an
11386     * .apk.
11387     */
11388    static String cidFromCodePath(String fullCodePath) {
11389        int eidx = fullCodePath.lastIndexOf("/");
11390        String subStr1 = fullCodePath.substring(0, eidx);
11391        int sidx = subStr1.lastIndexOf("/");
11392        return subStr1.substring(sidx+1, eidx);
11393    }
11394
11395    /**
11396     * Logic to handle installation of ASEC applications, including copying and
11397     * renaming logic.
11398     */
11399    class AsecInstallArgs extends InstallArgs {
11400        static final String RES_FILE_NAME = "pkg.apk";
11401        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11402
11403        String cid;
11404        String packagePath;
11405        String resourcePath;
11406
11407        /** New install */
11408        AsecInstallArgs(InstallParams params) {
11409            super(params.origin, params.move, params.observer, params.installFlags,
11410                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11411                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11412                    params.grantedRuntimePermissions,
11413                    params.traceMethod, params.traceCookie);
11414        }
11415
11416        /** Existing install */
11417        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11418                        boolean isExternal, boolean isForwardLocked) {
11419            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11420                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11421                    instructionSets, null, null, null, 0);
11422            // Hackily pretend we're still looking at a full code path
11423            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11424                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11425            }
11426
11427            // Extract cid from fullCodePath
11428            int eidx = fullCodePath.lastIndexOf("/");
11429            String subStr1 = fullCodePath.substring(0, eidx);
11430            int sidx = subStr1.lastIndexOf("/");
11431            cid = subStr1.substring(sidx+1, eidx);
11432            setMountPath(subStr1);
11433        }
11434
11435        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11436            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11437                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11438                    instructionSets, null, null, null, 0);
11439            this.cid = cid;
11440            setMountPath(PackageHelper.getSdDir(cid));
11441        }
11442
11443        void createCopyFile() {
11444            cid = mInstallerService.allocateExternalStageCidLegacy();
11445        }
11446
11447        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11448            if (origin.staged) {
11449                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11450                cid = origin.cid;
11451                setMountPath(PackageHelper.getSdDir(cid));
11452                return PackageManager.INSTALL_SUCCEEDED;
11453            }
11454
11455            if (temp) {
11456                createCopyFile();
11457            } else {
11458                /*
11459                 * Pre-emptively destroy the container since it's destroyed if
11460                 * copying fails due to it existing anyway.
11461                 */
11462                PackageHelper.destroySdDir(cid);
11463            }
11464
11465            final String newMountPath = imcs.copyPackageToContainer(
11466                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11467                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11468
11469            if (newMountPath != null) {
11470                setMountPath(newMountPath);
11471                return PackageManager.INSTALL_SUCCEEDED;
11472            } else {
11473                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11474            }
11475        }
11476
11477        @Override
11478        String getCodePath() {
11479            return packagePath;
11480        }
11481
11482        @Override
11483        String getResourcePath() {
11484            return resourcePath;
11485        }
11486
11487        int doPreInstall(int status) {
11488            if (status != PackageManager.INSTALL_SUCCEEDED) {
11489                // Destroy container
11490                PackageHelper.destroySdDir(cid);
11491            } else {
11492                boolean mounted = PackageHelper.isContainerMounted(cid);
11493                if (!mounted) {
11494                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11495                            Process.SYSTEM_UID);
11496                    if (newMountPath != null) {
11497                        setMountPath(newMountPath);
11498                    } else {
11499                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11500                    }
11501                }
11502            }
11503            return status;
11504        }
11505
11506        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11507            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11508            String newMountPath = null;
11509            if (PackageHelper.isContainerMounted(cid)) {
11510                // Unmount the container
11511                if (!PackageHelper.unMountSdDir(cid)) {
11512                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11513                    return false;
11514                }
11515            }
11516            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11517                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11518                        " which might be stale. Will try to clean up.");
11519                // Clean up the stale container and proceed to recreate.
11520                if (!PackageHelper.destroySdDir(newCacheId)) {
11521                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11522                    return false;
11523                }
11524                // Successfully cleaned up stale container. Try to rename again.
11525                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11526                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11527                            + " inspite of cleaning it up.");
11528                    return false;
11529                }
11530            }
11531            if (!PackageHelper.isContainerMounted(newCacheId)) {
11532                Slog.w(TAG, "Mounting container " + newCacheId);
11533                newMountPath = PackageHelper.mountSdDir(newCacheId,
11534                        getEncryptKey(), Process.SYSTEM_UID);
11535            } else {
11536                newMountPath = PackageHelper.getSdDir(newCacheId);
11537            }
11538            if (newMountPath == null) {
11539                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11540                return false;
11541            }
11542            Log.i(TAG, "Succesfully renamed " + cid +
11543                    " to " + newCacheId +
11544                    " at new path: " + newMountPath);
11545            cid = newCacheId;
11546
11547            final File beforeCodeFile = new File(packagePath);
11548            setMountPath(newMountPath);
11549            final File afterCodeFile = new File(packagePath);
11550
11551            // Reflect the rename in scanned details
11552            pkg.codePath = afterCodeFile.getAbsolutePath();
11553            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11554                    pkg.baseCodePath);
11555            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11556                    pkg.splitCodePaths);
11557
11558            // Reflect the rename in app info
11559            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11560            pkg.applicationInfo.setCodePath(pkg.codePath);
11561            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11562            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11563            pkg.applicationInfo.setResourcePath(pkg.codePath);
11564            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11565            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11566
11567            return true;
11568        }
11569
11570        private void setMountPath(String mountPath) {
11571            final File mountFile = new File(mountPath);
11572
11573            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11574            if (monolithicFile.exists()) {
11575                packagePath = monolithicFile.getAbsolutePath();
11576                if (isFwdLocked()) {
11577                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11578                } else {
11579                    resourcePath = packagePath;
11580                }
11581            } else {
11582                packagePath = mountFile.getAbsolutePath();
11583                resourcePath = packagePath;
11584            }
11585        }
11586
11587        int doPostInstall(int status, int uid) {
11588            if (status != PackageManager.INSTALL_SUCCEEDED) {
11589                cleanUp();
11590            } else {
11591                final int groupOwner;
11592                final String protectedFile;
11593                if (isFwdLocked()) {
11594                    groupOwner = UserHandle.getSharedAppGid(uid);
11595                    protectedFile = RES_FILE_NAME;
11596                } else {
11597                    groupOwner = -1;
11598                    protectedFile = null;
11599                }
11600
11601                if (uid < Process.FIRST_APPLICATION_UID
11602                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11603                    Slog.e(TAG, "Failed to finalize " + cid);
11604                    PackageHelper.destroySdDir(cid);
11605                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11606                }
11607
11608                boolean mounted = PackageHelper.isContainerMounted(cid);
11609                if (!mounted) {
11610                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11611                }
11612            }
11613            return status;
11614        }
11615
11616        private void cleanUp() {
11617            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11618
11619            // Destroy secure container
11620            PackageHelper.destroySdDir(cid);
11621        }
11622
11623        private List<String> getAllCodePaths() {
11624            final File codeFile = new File(getCodePath());
11625            if (codeFile != null && codeFile.exists()) {
11626                try {
11627                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11628                    return pkg.getAllCodePaths();
11629                } catch (PackageParserException e) {
11630                    // Ignored; we tried our best
11631                }
11632            }
11633            return Collections.EMPTY_LIST;
11634        }
11635
11636        void cleanUpResourcesLI() {
11637            // Enumerate all code paths before deleting
11638            cleanUpResourcesLI(getAllCodePaths());
11639        }
11640
11641        private void cleanUpResourcesLI(List<String> allCodePaths) {
11642            cleanUp();
11643            removeDexFiles(allCodePaths, instructionSets);
11644        }
11645
11646        String getPackageName() {
11647            return getAsecPackageName(cid);
11648        }
11649
11650        boolean doPostDeleteLI(boolean delete) {
11651            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11652            final List<String> allCodePaths = getAllCodePaths();
11653            boolean mounted = PackageHelper.isContainerMounted(cid);
11654            if (mounted) {
11655                // Unmount first
11656                if (PackageHelper.unMountSdDir(cid)) {
11657                    mounted = false;
11658                }
11659            }
11660            if (!mounted && delete) {
11661                cleanUpResourcesLI(allCodePaths);
11662            }
11663            return !mounted;
11664        }
11665
11666        @Override
11667        int doPreCopy() {
11668            if (isFwdLocked()) {
11669                if (!PackageHelper.fixSdPermissions(cid,
11670                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11671                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11672                }
11673            }
11674
11675            return PackageManager.INSTALL_SUCCEEDED;
11676        }
11677
11678        @Override
11679        int doPostCopy(int uid) {
11680            if (isFwdLocked()) {
11681                if (uid < Process.FIRST_APPLICATION_UID
11682                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11683                                RES_FILE_NAME)) {
11684                    Slog.e(TAG, "Failed to finalize " + cid);
11685                    PackageHelper.destroySdDir(cid);
11686                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11687                }
11688            }
11689
11690            return PackageManager.INSTALL_SUCCEEDED;
11691        }
11692    }
11693
11694    /**
11695     * Logic to handle movement of existing installed applications.
11696     */
11697    class MoveInstallArgs extends InstallArgs {
11698        private File codeFile;
11699        private File resourceFile;
11700
11701        /** New install */
11702        MoveInstallArgs(InstallParams params) {
11703            super(params.origin, params.move, params.observer, params.installFlags,
11704                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11705                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11706                    params.grantedRuntimePermissions,
11707                    params.traceMethod, params.traceCookie);
11708        }
11709
11710        int copyApk(IMediaContainerService imcs, boolean temp) {
11711            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11712                    + move.fromUuid + " to " + move.toUuid);
11713            synchronized (mInstaller) {
11714                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11715                        move.dataAppName, move.appId, move.seinfo) != 0) {
11716                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11717                }
11718            }
11719
11720            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11721            resourceFile = codeFile;
11722            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11723
11724            return PackageManager.INSTALL_SUCCEEDED;
11725        }
11726
11727        int doPreInstall(int status) {
11728            if (status != PackageManager.INSTALL_SUCCEEDED) {
11729                cleanUp(move.toUuid);
11730            }
11731            return status;
11732        }
11733
11734        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11735            if (status != PackageManager.INSTALL_SUCCEEDED) {
11736                cleanUp(move.toUuid);
11737                return false;
11738            }
11739
11740            // Reflect the move in app info
11741            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11742            pkg.applicationInfo.setCodePath(pkg.codePath);
11743            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11744            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11745            pkg.applicationInfo.setResourcePath(pkg.codePath);
11746            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11747            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11748
11749            return true;
11750        }
11751
11752        int doPostInstall(int status, int uid) {
11753            if (status == PackageManager.INSTALL_SUCCEEDED) {
11754                cleanUp(move.fromUuid);
11755            } else {
11756                cleanUp(move.toUuid);
11757            }
11758            return status;
11759        }
11760
11761        @Override
11762        String getCodePath() {
11763            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11764        }
11765
11766        @Override
11767        String getResourcePath() {
11768            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11769        }
11770
11771        private boolean cleanUp(String volumeUuid) {
11772            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11773                    move.dataAppName);
11774            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11775            synchronized (mInstallLock) {
11776                // Clean up both app data and code
11777                removeDataDirsLI(volumeUuid, move.packageName);
11778                if (codeFile.isDirectory()) {
11779                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11780                } else {
11781                    codeFile.delete();
11782                }
11783            }
11784            return true;
11785        }
11786
11787        void cleanUpResourcesLI() {
11788            throw new UnsupportedOperationException();
11789        }
11790
11791        boolean doPostDeleteLI(boolean delete) {
11792            throw new UnsupportedOperationException();
11793        }
11794    }
11795
11796    static String getAsecPackageName(String packageCid) {
11797        int idx = packageCid.lastIndexOf("-");
11798        if (idx == -1) {
11799            return packageCid;
11800        }
11801        return packageCid.substring(0, idx);
11802    }
11803
11804    // Utility method used to create code paths based on package name and available index.
11805    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11806        String idxStr = "";
11807        int idx = 1;
11808        // Fall back to default value of idx=1 if prefix is not
11809        // part of oldCodePath
11810        if (oldCodePath != null) {
11811            String subStr = oldCodePath;
11812            // Drop the suffix right away
11813            if (suffix != null && subStr.endsWith(suffix)) {
11814                subStr = subStr.substring(0, subStr.length() - suffix.length());
11815            }
11816            // If oldCodePath already contains prefix find out the
11817            // ending index to either increment or decrement.
11818            int sidx = subStr.lastIndexOf(prefix);
11819            if (sidx != -1) {
11820                subStr = subStr.substring(sidx + prefix.length());
11821                if (subStr != null) {
11822                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11823                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11824                    }
11825                    try {
11826                        idx = Integer.parseInt(subStr);
11827                        if (idx <= 1) {
11828                            idx++;
11829                        } else {
11830                            idx--;
11831                        }
11832                    } catch(NumberFormatException e) {
11833                    }
11834                }
11835            }
11836        }
11837        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11838        return prefix + idxStr;
11839    }
11840
11841    private File getNextCodePath(File targetDir, String packageName) {
11842        int suffix = 1;
11843        File result;
11844        do {
11845            result = new File(targetDir, packageName + "-" + suffix);
11846            suffix++;
11847        } while (result.exists());
11848        return result;
11849    }
11850
11851    // Utility method that returns the relative package path with respect
11852    // to the installation directory. Like say for /data/data/com.test-1.apk
11853    // string com.test-1 is returned.
11854    static String deriveCodePathName(String codePath) {
11855        if (codePath == null) {
11856            return null;
11857        }
11858        final File codeFile = new File(codePath);
11859        final String name = codeFile.getName();
11860        if (codeFile.isDirectory()) {
11861            return name;
11862        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11863            final int lastDot = name.lastIndexOf('.');
11864            return name.substring(0, lastDot);
11865        } else {
11866            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11867            return null;
11868        }
11869    }
11870
11871    class PackageInstalledInfo {
11872        String name;
11873        int uid;
11874        // The set of users that originally had this package installed.
11875        int[] origUsers;
11876        // The set of users that now have this package installed.
11877        int[] newUsers;
11878        PackageParser.Package pkg;
11879        int returnCode;
11880        String returnMsg;
11881        PackageRemovedInfo removedInfo;
11882
11883        public void setError(int code, String msg) {
11884            returnCode = code;
11885            returnMsg = msg;
11886            Slog.w(TAG, msg);
11887        }
11888
11889        public void setError(String msg, PackageParserException e) {
11890            returnCode = e.error;
11891            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11892            Slog.w(TAG, msg, e);
11893        }
11894
11895        public void setError(String msg, PackageManagerException e) {
11896            returnCode = e.error;
11897            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11898            Slog.w(TAG, msg, e);
11899        }
11900
11901        // In some error cases we want to convey more info back to the observer
11902        String origPackage;
11903        String origPermission;
11904    }
11905
11906    /*
11907     * Install a non-existing package.
11908     */
11909    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11910            UserHandle user, String installerPackageName, String volumeUuid,
11911            PackageInstalledInfo res) {
11912        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
11913
11914        // Remember this for later, in case we need to rollback this install
11915        String pkgName = pkg.packageName;
11916
11917        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11918        // TODO: b/23350563
11919        final boolean dataDirExists = Environment
11920                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
11921
11922        synchronized(mPackages) {
11923            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11924                // A package with the same name is already installed, though
11925                // it has been renamed to an older name.  The package we
11926                // are trying to install should be installed as an update to
11927                // the existing one, but that has not been requested, so bail.
11928                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11929                        + " without first uninstalling package running as "
11930                        + mSettings.mRenamedPackages.get(pkgName));
11931                return;
11932            }
11933            if (mPackages.containsKey(pkgName)) {
11934                // Don't allow installation over an existing package with the same name.
11935                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11936                        + " without first uninstalling.");
11937                return;
11938            }
11939        }
11940
11941        try {
11942            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
11943                    System.currentTimeMillis(), user);
11944
11945            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11946            // delete the partially installed application. the data directory will have to be
11947            // restored if it was already existing
11948            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11949                // remove package from internal structures.  Note that we want deletePackageX to
11950                // delete the package data and cache directories that it created in
11951                // scanPackageLocked, unless those directories existed before we even tried to
11952                // install.
11953                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11954                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11955                                res.removedInfo, true);
11956            }
11957
11958        } catch (PackageManagerException e) {
11959            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11960        }
11961
11962        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11963    }
11964
11965    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11966        // Can't rotate keys during boot or if sharedUser.
11967        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11968                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11969            return false;
11970        }
11971        // app is using upgradeKeySets; make sure all are valid
11972        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11973        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11974        for (int i = 0; i < upgradeKeySets.length; i++) {
11975            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11976                Slog.wtf(TAG, "Package "
11977                         + (oldPs.name != null ? oldPs.name : "<null>")
11978                         + " contains upgrade-key-set reference to unknown key-set: "
11979                         + upgradeKeySets[i]
11980                         + " reverting to signatures check.");
11981                return false;
11982            }
11983        }
11984        return true;
11985    }
11986
11987    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11988        // Upgrade keysets are being used.  Determine if new package has a superset of the
11989        // required keys.
11990        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11991        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11992        for (int i = 0; i < upgradeKeySets.length; i++) {
11993            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11994            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11995                return true;
11996            }
11997        }
11998        return false;
11999    }
12000
12001    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12002            UserHandle user, String installerPackageName, String volumeUuid,
12003            PackageInstalledInfo res) {
12004        final PackageParser.Package oldPackage;
12005        final String pkgName = pkg.packageName;
12006        final int[] allUsers;
12007        final boolean[] perUserInstalled;
12008
12009        // First find the old package info and check signatures
12010        synchronized(mPackages) {
12011            oldPackage = mPackages.get(pkgName);
12012            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12013            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12014            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12015                if(!checkUpgradeKeySetLP(ps, pkg)) {
12016                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12017                            "New package not signed by keys specified by upgrade-keysets: "
12018                            + pkgName);
12019                    return;
12020                }
12021            } else {
12022                // default to original signature matching
12023                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12024                    != PackageManager.SIGNATURE_MATCH) {
12025                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12026                            "New package has a different signature: " + pkgName);
12027                    return;
12028                }
12029            }
12030
12031            // In case of rollback, remember per-user/profile install state
12032            allUsers = sUserManager.getUserIds();
12033            perUserInstalled = new boolean[allUsers.length];
12034            for (int i = 0; i < allUsers.length; i++) {
12035                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12036            }
12037        }
12038
12039        boolean sysPkg = (isSystemApp(oldPackage));
12040        if (sysPkg) {
12041            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12042                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12043        } else {
12044            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12045                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12046        }
12047    }
12048
12049    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12050            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12051            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12052            String volumeUuid, PackageInstalledInfo res) {
12053        String pkgName = deletedPackage.packageName;
12054        boolean deletedPkg = true;
12055        boolean updatedSettings = false;
12056
12057        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12058                + deletedPackage);
12059        long origUpdateTime;
12060        if (pkg.mExtras != null) {
12061            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12062        } else {
12063            origUpdateTime = 0;
12064        }
12065
12066        // First delete the existing package while retaining the data directory
12067        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12068                res.removedInfo, true)) {
12069            // If the existing package wasn't successfully deleted
12070            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12071            deletedPkg = false;
12072        } else {
12073            // Successfully deleted the old package; proceed with replace.
12074
12075            // If deleted package lived in a container, give users a chance to
12076            // relinquish resources before killing.
12077            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12078                if (DEBUG_INSTALL) {
12079                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12080                }
12081                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12082                final ArrayList<String> pkgList = new ArrayList<String>(1);
12083                pkgList.add(deletedPackage.applicationInfo.packageName);
12084                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12085            }
12086
12087            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12088            try {
12089                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12090                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12091                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12092                        perUserInstalled, res, user);
12093                updatedSettings = true;
12094            } catch (PackageManagerException e) {
12095                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12096            }
12097        }
12098
12099        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12100            // remove package from internal structures.  Note that we want deletePackageX to
12101            // delete the package data and cache directories that it created in
12102            // scanPackageLocked, unless those directories existed before we even tried to
12103            // install.
12104            if(updatedSettings) {
12105                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12106                deletePackageLI(
12107                        pkgName, null, true, allUsers, perUserInstalled,
12108                        PackageManager.DELETE_KEEP_DATA,
12109                                res.removedInfo, true);
12110            }
12111            // Since we failed to install the new package we need to restore the old
12112            // package that we deleted.
12113            if (deletedPkg) {
12114                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12115                File restoreFile = new File(deletedPackage.codePath);
12116                // Parse old package
12117                boolean oldExternal = isExternal(deletedPackage);
12118                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12119                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12120                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12121                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12122                try {
12123                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
12124                } catch (PackageManagerException e) {
12125                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12126                            + e.getMessage());
12127                    return;
12128                }
12129                // Restore of old package succeeded. Update permissions.
12130                // writer
12131                synchronized (mPackages) {
12132                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12133                            UPDATE_PERMISSIONS_ALL);
12134                    // can downgrade to reader
12135                    mSettings.writeLPr();
12136                }
12137                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12138            }
12139        }
12140    }
12141
12142    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12143            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12144            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12145            String volumeUuid, PackageInstalledInfo res) {
12146        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12147                + ", old=" + deletedPackage);
12148        boolean disabledSystem = false;
12149        boolean updatedSettings = false;
12150        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12151        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12152                != 0) {
12153            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12154        }
12155        String packageName = deletedPackage.packageName;
12156        if (packageName == null) {
12157            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12158                    "Attempt to delete null packageName.");
12159            return;
12160        }
12161        PackageParser.Package oldPkg;
12162        PackageSetting oldPkgSetting;
12163        // reader
12164        synchronized (mPackages) {
12165            oldPkg = mPackages.get(packageName);
12166            oldPkgSetting = mSettings.mPackages.get(packageName);
12167            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12168                    (oldPkgSetting == null)) {
12169                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12170                        "Couldn't find package:" + packageName + " information");
12171                return;
12172            }
12173        }
12174
12175        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12176
12177        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12178        res.removedInfo.removedPackage = packageName;
12179        // Remove existing system package
12180        removePackageLI(oldPkgSetting, true);
12181        // writer
12182        synchronized (mPackages) {
12183            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12184            if (!disabledSystem && deletedPackage != null) {
12185                // We didn't need to disable the .apk as a current system package,
12186                // which means we are replacing another update that is already
12187                // installed.  We need to make sure to delete the older one's .apk.
12188                res.removedInfo.args = createInstallArgsForExisting(0,
12189                        deletedPackage.applicationInfo.getCodePath(),
12190                        deletedPackage.applicationInfo.getResourcePath(),
12191                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12192            } else {
12193                res.removedInfo.args = null;
12194            }
12195        }
12196
12197        // Successfully disabled the old package. Now proceed with re-installation
12198        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12199
12200        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12201        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12202
12203        PackageParser.Package newPackage = null;
12204        try {
12205            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12206            if (newPackage.mExtras != null) {
12207                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12208                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12209                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12210
12211                // is the update attempting to change shared user? that isn't going to work...
12212                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12213                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12214                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12215                            + " to " + newPkgSetting.sharedUser);
12216                    updatedSettings = true;
12217                }
12218            }
12219
12220            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12221                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12222                        perUserInstalled, res, user);
12223                updatedSettings = true;
12224            }
12225
12226        } catch (PackageManagerException e) {
12227            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12228        }
12229
12230        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12231            // Re installation failed. Restore old information
12232            // Remove new pkg information
12233            if (newPackage != null) {
12234                removeInstalledPackageLI(newPackage, true);
12235            }
12236            // Add back the old system package
12237            try {
12238                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12239            } catch (PackageManagerException e) {
12240                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12241            }
12242            // Restore the old system information in Settings
12243            synchronized (mPackages) {
12244                if (disabledSystem) {
12245                    mSettings.enableSystemPackageLPw(packageName);
12246                }
12247                if (updatedSettings) {
12248                    mSettings.setInstallerPackageName(packageName,
12249                            oldPkgSetting.installerPackageName);
12250                }
12251                mSettings.writeLPr();
12252            }
12253        }
12254    }
12255
12256    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12257            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12258            UserHandle user) {
12259        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12260
12261        String pkgName = newPackage.packageName;
12262        synchronized (mPackages) {
12263            //write settings. the installStatus will be incomplete at this stage.
12264            //note that the new package setting would have already been
12265            //added to mPackages. It hasn't been persisted yet.
12266            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12267            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12268            mSettings.writeLPr();
12269            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12270        }
12271
12272        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12273        synchronized (mPackages) {
12274            updatePermissionsLPw(newPackage.packageName, newPackage,
12275                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12276                            ? UPDATE_PERMISSIONS_ALL : 0));
12277            // For system-bundled packages, we assume that installing an upgraded version
12278            // of the package implies that the user actually wants to run that new code,
12279            // so we enable the package.
12280            PackageSetting ps = mSettings.mPackages.get(pkgName);
12281            if (ps != null) {
12282                if (isSystemApp(newPackage)) {
12283                    // NB: implicit assumption that system package upgrades apply to all users
12284                    if (DEBUG_INSTALL) {
12285                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12286                    }
12287                    if (res.origUsers != null) {
12288                        for (int userHandle : res.origUsers) {
12289                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12290                                    userHandle, installerPackageName);
12291                        }
12292                    }
12293                    // Also convey the prior install/uninstall state
12294                    if (allUsers != null && perUserInstalled != null) {
12295                        for (int i = 0; i < allUsers.length; i++) {
12296                            if (DEBUG_INSTALL) {
12297                                Slog.d(TAG, "    user " + allUsers[i]
12298                                        + " => " + perUserInstalled[i]);
12299                            }
12300                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12301                        }
12302                        // these install state changes will be persisted in the
12303                        // upcoming call to mSettings.writeLPr().
12304                    }
12305                }
12306                // It's implied that when a user requests installation, they want the app to be
12307                // installed and enabled.
12308                int userId = user.getIdentifier();
12309                if (userId != UserHandle.USER_ALL) {
12310                    ps.setInstalled(true, userId);
12311                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12312                }
12313            }
12314            res.name = pkgName;
12315            res.uid = newPackage.applicationInfo.uid;
12316            res.pkg = newPackage;
12317            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12318            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12319            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12320            //to update install status
12321            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12322            mSettings.writeLPr();
12323            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12324        }
12325
12326        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12327    }
12328
12329    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12330        try {
12331            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12332            installPackageLI(args, res);
12333        } finally {
12334            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12335        }
12336    }
12337
12338    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12339        final int installFlags = args.installFlags;
12340        final String installerPackageName = args.installerPackageName;
12341        final String volumeUuid = args.volumeUuid;
12342        final File tmpPackageFile = new File(args.getCodePath());
12343        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12344        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12345                || (args.volumeUuid != null));
12346        boolean replace = false;
12347        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12348        if (args.move != null) {
12349            // moving a complete application; perfom an initial scan on the new install location
12350            scanFlags |= SCAN_INITIAL;
12351        }
12352        // Result object to be returned
12353        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12354
12355        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12356
12357        // Retrieve PackageSettings and parse package
12358        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12359                | PackageParser.PARSE_ENFORCE_CODE
12360                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12361                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12362        PackageParser pp = new PackageParser();
12363        pp.setSeparateProcesses(mSeparateProcesses);
12364        pp.setDisplayMetrics(mMetrics);
12365
12366        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12367        final PackageParser.Package pkg;
12368        try {
12369            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12370        } catch (PackageParserException e) {
12371            res.setError("Failed parse during installPackageLI", e);
12372            return;
12373        } finally {
12374            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12375        }
12376
12377        // Mark that we have an install time CPU ABI override.
12378        pkg.cpuAbiOverride = args.abiOverride;
12379
12380        String pkgName = res.name = pkg.packageName;
12381        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12382            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12383                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12384                return;
12385            }
12386        }
12387
12388        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12389        try {
12390            pp.collectCertificates(pkg, parseFlags);
12391            pp.collectManifestDigest(pkg);
12392        } catch (PackageParserException e) {
12393            res.setError("Failed collect during installPackageLI", e);
12394            return;
12395        } finally {
12396            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12397        }
12398
12399        /* If the installer passed in a manifest digest, compare it now. */
12400        if (args.manifestDigest != null) {
12401            if (DEBUG_INSTALL) {
12402                final String parsedManifest = pkg.manifestDigest == null ? "null"
12403                        : pkg.manifestDigest.toString();
12404                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12405                        + parsedManifest);
12406            }
12407
12408            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12409                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12410                return;
12411            }
12412        } else if (DEBUG_INSTALL) {
12413            final String parsedManifest = pkg.manifestDigest == null
12414                    ? "null" : pkg.manifestDigest.toString();
12415            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12416        }
12417
12418        // Get rid of all references to package scan path via parser.
12419        pp = null;
12420        String oldCodePath = null;
12421        boolean systemApp = false;
12422        synchronized (mPackages) {
12423            // Check if installing already existing package
12424            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12425                String oldName = mSettings.mRenamedPackages.get(pkgName);
12426                if (pkg.mOriginalPackages != null
12427                        && pkg.mOriginalPackages.contains(oldName)
12428                        && mPackages.containsKey(oldName)) {
12429                    // This package is derived from an original package,
12430                    // and this device has been updating from that original
12431                    // name.  We must continue using the original name, so
12432                    // rename the new package here.
12433                    pkg.setPackageName(oldName);
12434                    pkgName = pkg.packageName;
12435                    replace = true;
12436                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12437                            + oldName + " pkgName=" + pkgName);
12438                } else if (mPackages.containsKey(pkgName)) {
12439                    // This package, under its official name, already exists
12440                    // on the device; we should replace it.
12441                    replace = true;
12442                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12443                }
12444
12445                // Prevent apps opting out from runtime permissions
12446                if (replace) {
12447                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12448                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12449                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12450                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12451                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12452                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12453                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12454                                        + " doesn't support runtime permissions but the old"
12455                                        + " target SDK " + oldTargetSdk + " does.");
12456                        return;
12457                    }
12458                }
12459            }
12460
12461            PackageSetting ps = mSettings.mPackages.get(pkgName);
12462            if (ps != null) {
12463                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12464
12465                // Quick sanity check that we're signed correctly if updating;
12466                // we'll check this again later when scanning, but we want to
12467                // bail early here before tripping over redefined permissions.
12468                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12469                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12470                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12471                                + pkg.packageName + " upgrade keys do not match the "
12472                                + "previously installed version");
12473                        return;
12474                    }
12475                } else {
12476                    try {
12477                        verifySignaturesLP(ps, pkg);
12478                    } catch (PackageManagerException e) {
12479                        res.setError(e.error, e.getMessage());
12480                        return;
12481                    }
12482                }
12483
12484                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12485                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12486                    systemApp = (ps.pkg.applicationInfo.flags &
12487                            ApplicationInfo.FLAG_SYSTEM) != 0;
12488                }
12489                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12490            }
12491
12492            // Check whether the newly-scanned package wants to define an already-defined perm
12493            int N = pkg.permissions.size();
12494            for (int i = N-1; i >= 0; i--) {
12495                PackageParser.Permission perm = pkg.permissions.get(i);
12496                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12497                if (bp != null) {
12498                    // If the defining package is signed with our cert, it's okay.  This
12499                    // also includes the "updating the same package" case, of course.
12500                    // "updating same package" could also involve key-rotation.
12501                    final boolean sigsOk;
12502                    if (bp.sourcePackage.equals(pkg.packageName)
12503                            && (bp.packageSetting instanceof PackageSetting)
12504                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12505                                    scanFlags))) {
12506                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12507                    } else {
12508                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12509                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12510                    }
12511                    if (!sigsOk) {
12512                        // If the owning package is the system itself, we log but allow
12513                        // install to proceed; we fail the install on all other permission
12514                        // redefinitions.
12515                        if (!bp.sourcePackage.equals("android")) {
12516                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12517                                    + pkg.packageName + " attempting to redeclare permission "
12518                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12519                            res.origPermission = perm.info.name;
12520                            res.origPackage = bp.sourcePackage;
12521                            return;
12522                        } else {
12523                            Slog.w(TAG, "Package " + pkg.packageName
12524                                    + " attempting to redeclare system permission "
12525                                    + perm.info.name + "; ignoring new declaration");
12526                            pkg.permissions.remove(i);
12527                        }
12528                    }
12529                }
12530            }
12531
12532        }
12533
12534        if (systemApp && onExternal) {
12535            // Disable updates to system apps on sdcard
12536            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12537                    "Cannot install updates to system apps on sdcard");
12538            return;
12539        }
12540
12541        if (args.move != null) {
12542            // We did an in-place move, so dex is ready to roll
12543            scanFlags |= SCAN_NO_DEX;
12544            scanFlags |= SCAN_MOVE;
12545
12546            synchronized (mPackages) {
12547                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12548                if (ps == null) {
12549                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12550                            "Missing settings for moved package " + pkgName);
12551                }
12552
12553                // We moved the entire application as-is, so bring over the
12554                // previously derived ABI information.
12555                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12556                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12557            }
12558
12559        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12560            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12561            scanFlags |= SCAN_NO_DEX;
12562
12563            try {
12564                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12565                        true /* extract libs */);
12566            } catch (PackageManagerException pme) {
12567                Slog.e(TAG, "Error deriving application ABI", pme);
12568                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12569                return;
12570            }
12571
12572            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12573            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
12574
12575            int result = mPackageDexOptimizer
12576                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12577                            false /* defer */, false /* inclDependencies */,
12578                            true /*bootComplete*/);
12579            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12580            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12581                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12582                return;
12583            }
12584        }
12585
12586        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12587            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12588            return;
12589        }
12590
12591        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12592
12593        if (replace) {
12594            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12595                    installerPackageName, volumeUuid, res);
12596        } else {
12597            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12598                    args.user, installerPackageName, volumeUuid, res);
12599        }
12600        synchronized (mPackages) {
12601            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12602            if (ps != null) {
12603                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12604            }
12605        }
12606    }
12607
12608    private void startIntentFilterVerifications(int userId, boolean replacing,
12609            PackageParser.Package pkg) {
12610        if (mIntentFilterVerifierComponent == null) {
12611            Slog.w(TAG, "No IntentFilter verification will not be done as "
12612                    + "there is no IntentFilterVerifier available!");
12613            return;
12614        }
12615
12616        final int verifierUid = getPackageUid(
12617                mIntentFilterVerifierComponent.getPackageName(),
12618                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12619
12620        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12621        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12622        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12623        mHandler.sendMessage(msg);
12624    }
12625
12626    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12627            PackageParser.Package pkg) {
12628        int size = pkg.activities.size();
12629        if (size == 0) {
12630            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12631                    "No activity, so no need to verify any IntentFilter!");
12632            return;
12633        }
12634
12635        final boolean hasDomainURLs = hasDomainURLs(pkg);
12636        if (!hasDomainURLs) {
12637            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12638                    "No domain URLs, so no need to verify any IntentFilter!");
12639            return;
12640        }
12641
12642        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12643                + " if any IntentFilter from the " + size
12644                + " Activities needs verification ...");
12645
12646        int count = 0;
12647        final String packageName = pkg.packageName;
12648
12649        synchronized (mPackages) {
12650            // If this is a new install and we see that we've already run verification for this
12651            // package, we have nothing to do: it means the state was restored from backup.
12652            if (!replacing) {
12653                IntentFilterVerificationInfo ivi =
12654                        mSettings.getIntentFilterVerificationLPr(packageName);
12655                if (ivi != null) {
12656                    if (DEBUG_DOMAIN_VERIFICATION) {
12657                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12658                                + ivi.getStatusString());
12659                    }
12660                    return;
12661                }
12662            }
12663
12664            // If any filters need to be verified, then all need to be.
12665            boolean needToVerify = false;
12666            for (PackageParser.Activity a : pkg.activities) {
12667                for (ActivityIntentInfo filter : a.intents) {
12668                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12669                        if (DEBUG_DOMAIN_VERIFICATION) {
12670                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12671                        }
12672                        needToVerify = true;
12673                        break;
12674                    }
12675                }
12676            }
12677
12678            if (needToVerify) {
12679                final int verificationId = mIntentFilterVerificationToken++;
12680                for (PackageParser.Activity a : pkg.activities) {
12681                    for (ActivityIntentInfo filter : a.intents) {
12682                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12683                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12684                                    "Verification needed for IntentFilter:" + filter.toString());
12685                            mIntentFilterVerifier.addOneIntentFilterVerification(
12686                                    verifierUid, userId, verificationId, filter, packageName);
12687                            count++;
12688                        }
12689                    }
12690                }
12691            }
12692        }
12693
12694        if (count > 0) {
12695            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12696                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12697                    +  " for userId:" + userId);
12698            mIntentFilterVerifier.startVerifications(userId);
12699        } else {
12700            if (DEBUG_DOMAIN_VERIFICATION) {
12701                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12702            }
12703        }
12704    }
12705
12706    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12707        final ComponentName cn  = filter.activity.getComponentName();
12708        final String packageName = cn.getPackageName();
12709
12710        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12711                packageName);
12712        if (ivi == null) {
12713            return true;
12714        }
12715        int status = ivi.getStatus();
12716        switch (status) {
12717            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12718            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12719                return true;
12720
12721            default:
12722                // Nothing to do
12723                return false;
12724        }
12725    }
12726
12727    private static boolean isMultiArch(PackageSetting ps) {
12728        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12729    }
12730
12731    private static boolean isMultiArch(ApplicationInfo info) {
12732        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12733    }
12734
12735    private static boolean isExternal(PackageParser.Package pkg) {
12736        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12737    }
12738
12739    private static boolean isExternal(PackageSetting ps) {
12740        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12741    }
12742
12743    private static boolean isExternal(ApplicationInfo info) {
12744        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12745    }
12746
12747    private static boolean isSystemApp(PackageParser.Package pkg) {
12748        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12749    }
12750
12751    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12752        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12753    }
12754
12755    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12756        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12757    }
12758
12759    private static boolean isSystemApp(PackageSetting ps) {
12760        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12761    }
12762
12763    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12764        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12765    }
12766
12767    private int packageFlagsToInstallFlags(PackageSetting ps) {
12768        int installFlags = 0;
12769        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12770            // This existing package was an external ASEC install when we have
12771            // the external flag without a UUID
12772            installFlags |= PackageManager.INSTALL_EXTERNAL;
12773        }
12774        if (ps.isForwardLocked()) {
12775            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12776        }
12777        return installFlags;
12778    }
12779
12780    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12781        if (isExternal(pkg)) {
12782            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12783                return mSettings.getExternalVersion();
12784            } else {
12785                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12786            }
12787        } else {
12788            return mSettings.getInternalVersion();
12789        }
12790    }
12791
12792    private void deleteTempPackageFiles() {
12793        final FilenameFilter filter = new FilenameFilter() {
12794            public boolean accept(File dir, String name) {
12795                return name.startsWith("vmdl") && name.endsWith(".tmp");
12796            }
12797        };
12798        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12799            file.delete();
12800        }
12801    }
12802
12803    @Override
12804    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12805            int flags) {
12806        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12807                flags);
12808    }
12809
12810    @Override
12811    public void deletePackage(final String packageName,
12812            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12813        mContext.enforceCallingOrSelfPermission(
12814                android.Manifest.permission.DELETE_PACKAGES, null);
12815        Preconditions.checkNotNull(packageName);
12816        Preconditions.checkNotNull(observer);
12817        final int uid = Binder.getCallingUid();
12818        if (UserHandle.getUserId(uid) != userId) {
12819            mContext.enforceCallingPermission(
12820                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12821                    "deletePackage for user " + userId);
12822        }
12823        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12824            try {
12825                observer.onPackageDeleted(packageName,
12826                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12827            } catch (RemoteException re) {
12828            }
12829            return;
12830        }
12831
12832        boolean uninstallBlocked = false;
12833        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12834            int[] users = sUserManager.getUserIds();
12835            for (int i = 0; i < users.length; ++i) {
12836                if (getBlockUninstallForUser(packageName, users[i])) {
12837                    uninstallBlocked = true;
12838                    break;
12839                }
12840            }
12841        } else {
12842            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12843        }
12844        if (uninstallBlocked) {
12845            try {
12846                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12847                        null);
12848            } catch (RemoteException re) {
12849            }
12850            return;
12851        }
12852
12853        if (DEBUG_REMOVE) {
12854            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12855        }
12856        // Queue up an async operation since the package deletion may take a little while.
12857        mHandler.post(new Runnable() {
12858            public void run() {
12859                mHandler.removeCallbacks(this);
12860                final int returnCode = deletePackageX(packageName, userId, flags);
12861                if (observer != null) {
12862                    try {
12863                        observer.onPackageDeleted(packageName, returnCode, null);
12864                    } catch (RemoteException e) {
12865                        Log.i(TAG, "Observer no longer exists.");
12866                    } //end catch
12867                } //end if
12868            } //end run
12869        });
12870    }
12871
12872    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12873        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12874                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12875        try {
12876            if (dpm != null) {
12877                if (dpm.isDeviceOwner(packageName)) {
12878                    return true;
12879                }
12880                int[] users;
12881                if (userId == UserHandle.USER_ALL) {
12882                    users = sUserManager.getUserIds();
12883                } else {
12884                    users = new int[]{userId};
12885                }
12886                for (int i = 0; i < users.length; ++i) {
12887                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12888                        return true;
12889                    }
12890                }
12891            }
12892        } catch (RemoteException e) {
12893        }
12894        return false;
12895    }
12896
12897    /**
12898     *  This method is an internal method that could be get invoked either
12899     *  to delete an installed package or to clean up a failed installation.
12900     *  After deleting an installed package, a broadcast is sent to notify any
12901     *  listeners that the package has been installed. For cleaning up a failed
12902     *  installation, the broadcast is not necessary since the package's
12903     *  installation wouldn't have sent the initial broadcast either
12904     *  The key steps in deleting a package are
12905     *  deleting the package information in internal structures like mPackages,
12906     *  deleting the packages base directories through installd
12907     *  updating mSettings to reflect current status
12908     *  persisting settings for later use
12909     *  sending a broadcast if necessary
12910     */
12911    private int deletePackageX(String packageName, int userId, int flags) {
12912        final PackageRemovedInfo info = new PackageRemovedInfo();
12913        final boolean res;
12914
12915        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12916                ? UserHandle.ALL : new UserHandle(userId);
12917
12918        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12919            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12920            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12921        }
12922
12923        boolean removedForAllUsers = false;
12924        boolean systemUpdate = false;
12925
12926        // for the uninstall-updates case and restricted profiles, remember the per-
12927        // userhandle installed state
12928        int[] allUsers;
12929        boolean[] perUserInstalled;
12930        synchronized (mPackages) {
12931            PackageSetting ps = mSettings.mPackages.get(packageName);
12932            allUsers = sUserManager.getUserIds();
12933            perUserInstalled = new boolean[allUsers.length];
12934            for (int i = 0; i < allUsers.length; i++) {
12935                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12936            }
12937        }
12938
12939        synchronized (mInstallLock) {
12940            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12941            res = deletePackageLI(packageName, removeForUser,
12942                    true, allUsers, perUserInstalled,
12943                    flags | REMOVE_CHATTY, info, true);
12944            systemUpdate = info.isRemovedPackageSystemUpdate;
12945            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12946                removedForAllUsers = true;
12947            }
12948            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12949                    + " removedForAllUsers=" + removedForAllUsers);
12950        }
12951
12952        if (res) {
12953            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12954
12955            // If the removed package was a system update, the old system package
12956            // was re-enabled; we need to broadcast this information
12957            if (systemUpdate) {
12958                Bundle extras = new Bundle(1);
12959                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12960                        ? info.removedAppId : info.uid);
12961                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12962
12963                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12964                        extras, null, null, null);
12965                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12966                        extras, null, null, null);
12967                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12968                        null, packageName, null, null);
12969            }
12970        }
12971        // Force a gc here.
12972        Runtime.getRuntime().gc();
12973        // Delete the resources here after sending the broadcast to let
12974        // other processes clean up before deleting resources.
12975        if (info.args != null) {
12976            synchronized (mInstallLock) {
12977                info.args.doPostDeleteLI(true);
12978            }
12979        }
12980
12981        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12982    }
12983
12984    class PackageRemovedInfo {
12985        String removedPackage;
12986        int uid = -1;
12987        int removedAppId = -1;
12988        int[] removedUsers = null;
12989        boolean isRemovedPackageSystemUpdate = false;
12990        // Clean up resources deleted packages.
12991        InstallArgs args = null;
12992
12993        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12994            Bundle extras = new Bundle(1);
12995            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12996            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12997            if (replacing) {
12998                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12999            }
13000            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13001            if (removedPackage != null) {
13002                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13003                        extras, null, null, removedUsers);
13004                if (fullRemove && !replacing) {
13005                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13006                            extras, null, null, removedUsers);
13007                }
13008            }
13009            if (removedAppId >= 0) {
13010                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
13011                        removedUsers);
13012            }
13013        }
13014    }
13015
13016    /*
13017     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13018     * flag is not set, the data directory is removed as well.
13019     * make sure this flag is set for partially installed apps. If not its meaningless to
13020     * delete a partially installed application.
13021     */
13022    private void removePackageDataLI(PackageSetting ps,
13023            int[] allUserHandles, boolean[] perUserInstalled,
13024            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13025        String packageName = ps.name;
13026        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13027        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13028        // Retrieve object to delete permissions for shared user later on
13029        final PackageSetting deletedPs;
13030        // reader
13031        synchronized (mPackages) {
13032            deletedPs = mSettings.mPackages.get(packageName);
13033            if (outInfo != null) {
13034                outInfo.removedPackage = packageName;
13035                outInfo.removedUsers = deletedPs != null
13036                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13037                        : null;
13038            }
13039        }
13040        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13041            removeDataDirsLI(ps.volumeUuid, packageName);
13042            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13043        }
13044        // writer
13045        synchronized (mPackages) {
13046            if (deletedPs != null) {
13047                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13048                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13049                    clearDefaultBrowserIfNeeded(packageName);
13050                    if (outInfo != null) {
13051                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13052                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13053                    }
13054                    updatePermissionsLPw(deletedPs.name, null, 0);
13055                    if (deletedPs.sharedUser != null) {
13056                        // Remove permissions associated with package. Since runtime
13057                        // permissions are per user we have to kill the removed package
13058                        // or packages running under the shared user of the removed
13059                        // package if revoking the permissions requested only by the removed
13060                        // package is successful and this causes a change in gids.
13061                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13062                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13063                                    userId);
13064                            if (userIdToKill == UserHandle.USER_ALL
13065                                    || userIdToKill >= UserHandle.USER_OWNER) {
13066                                // If gids changed for this user, kill all affected packages.
13067                                mHandler.post(new Runnable() {
13068                                    @Override
13069                                    public void run() {
13070                                        // This has to happen with no lock held.
13071                                        killApplication(deletedPs.name, deletedPs.appId,
13072                                                KILL_APP_REASON_GIDS_CHANGED);
13073                                    }
13074                                });
13075                                break;
13076                            }
13077                        }
13078                    }
13079                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13080                }
13081                // make sure to preserve per-user disabled state if this removal was just
13082                // a downgrade of a system app to the factory package
13083                if (allUserHandles != null && perUserInstalled != null) {
13084                    if (DEBUG_REMOVE) {
13085                        Slog.d(TAG, "Propagating install state across downgrade");
13086                    }
13087                    for (int i = 0; i < allUserHandles.length; i++) {
13088                        if (DEBUG_REMOVE) {
13089                            Slog.d(TAG, "    user " + allUserHandles[i]
13090                                    + " => " + perUserInstalled[i]);
13091                        }
13092                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13093                    }
13094                }
13095            }
13096            // can downgrade to reader
13097            if (writeSettings) {
13098                // Save settings now
13099                mSettings.writeLPr();
13100            }
13101        }
13102        if (outInfo != null) {
13103            // A user ID was deleted here. Go through all users and remove it
13104            // from KeyStore.
13105            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13106        }
13107    }
13108
13109    static boolean locationIsPrivileged(File path) {
13110        try {
13111            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13112                    .getCanonicalPath();
13113            return path.getCanonicalPath().startsWith(privilegedAppDir);
13114        } catch (IOException e) {
13115            Slog.e(TAG, "Unable to access code path " + path);
13116        }
13117        return false;
13118    }
13119
13120    /*
13121     * Tries to delete system package.
13122     */
13123    private boolean deleteSystemPackageLI(PackageSetting newPs,
13124            int[] allUserHandles, boolean[] perUserInstalled,
13125            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13126        final boolean applyUserRestrictions
13127                = (allUserHandles != null) && (perUserInstalled != null);
13128        PackageSetting disabledPs = null;
13129        // Confirm if the system package has been updated
13130        // An updated system app can be deleted. This will also have to restore
13131        // the system pkg from system partition
13132        // reader
13133        synchronized (mPackages) {
13134            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13135        }
13136        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13137                + " disabledPs=" + disabledPs);
13138        if (disabledPs == null) {
13139            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13140            return false;
13141        } else if (DEBUG_REMOVE) {
13142            Slog.d(TAG, "Deleting system pkg from data partition");
13143        }
13144        if (DEBUG_REMOVE) {
13145            if (applyUserRestrictions) {
13146                Slog.d(TAG, "Remembering install states:");
13147                for (int i = 0; i < allUserHandles.length; i++) {
13148                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13149                }
13150            }
13151        }
13152        // Delete the updated package
13153        outInfo.isRemovedPackageSystemUpdate = true;
13154        if (disabledPs.versionCode < newPs.versionCode) {
13155            // Delete data for downgrades
13156            flags &= ~PackageManager.DELETE_KEEP_DATA;
13157        } else {
13158            // Preserve data by setting flag
13159            flags |= PackageManager.DELETE_KEEP_DATA;
13160        }
13161        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13162                allUserHandles, perUserInstalled, outInfo, writeSettings);
13163        if (!ret) {
13164            return false;
13165        }
13166        // writer
13167        synchronized (mPackages) {
13168            // Reinstate the old system package
13169            mSettings.enableSystemPackageLPw(newPs.name);
13170            // Remove any native libraries from the upgraded package.
13171            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13172        }
13173        // Install the system package
13174        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13175        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13176        if (locationIsPrivileged(disabledPs.codePath)) {
13177            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13178        }
13179
13180        final PackageParser.Package newPkg;
13181        try {
13182            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13183        } catch (PackageManagerException e) {
13184            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13185            return false;
13186        }
13187
13188        // writer
13189        synchronized (mPackages) {
13190            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13191
13192            // Propagate the permissions state as we do not want to drop on the floor
13193            // runtime permissions. The update permissions method below will take
13194            // care of removing obsolete permissions and grant install permissions.
13195            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13196            updatePermissionsLPw(newPkg.packageName, newPkg,
13197                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13198
13199            if (applyUserRestrictions) {
13200                if (DEBUG_REMOVE) {
13201                    Slog.d(TAG, "Propagating install state across reinstall");
13202                }
13203                for (int i = 0; i < allUserHandles.length; i++) {
13204                    if (DEBUG_REMOVE) {
13205                        Slog.d(TAG, "    user " + allUserHandles[i]
13206                                + " => " + perUserInstalled[i]);
13207                    }
13208                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13209
13210                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13211                }
13212                // Regardless of writeSettings we need to ensure that this restriction
13213                // state propagation is persisted
13214                mSettings.writeAllUsersPackageRestrictionsLPr();
13215            }
13216            // can downgrade to reader here
13217            if (writeSettings) {
13218                mSettings.writeLPr();
13219            }
13220        }
13221        return true;
13222    }
13223
13224    private boolean deleteInstalledPackageLI(PackageSetting ps,
13225            boolean deleteCodeAndResources, int flags,
13226            int[] allUserHandles, boolean[] perUserInstalled,
13227            PackageRemovedInfo outInfo, boolean writeSettings) {
13228        if (outInfo != null) {
13229            outInfo.uid = ps.appId;
13230        }
13231
13232        // Delete package data from internal structures and also remove data if flag is set
13233        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13234
13235        // Delete application code and resources
13236        if (deleteCodeAndResources && (outInfo != null)) {
13237            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13238                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13239            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13240        }
13241        return true;
13242    }
13243
13244    @Override
13245    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13246            int userId) {
13247        mContext.enforceCallingOrSelfPermission(
13248                android.Manifest.permission.DELETE_PACKAGES, null);
13249        synchronized (mPackages) {
13250            PackageSetting ps = mSettings.mPackages.get(packageName);
13251            if (ps == null) {
13252                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13253                return false;
13254            }
13255            if (!ps.getInstalled(userId)) {
13256                // Can't block uninstall for an app that is not installed or enabled.
13257                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13258                return false;
13259            }
13260            ps.setBlockUninstall(blockUninstall, userId);
13261            mSettings.writePackageRestrictionsLPr(userId);
13262        }
13263        return true;
13264    }
13265
13266    @Override
13267    public boolean getBlockUninstallForUser(String packageName, int userId) {
13268        synchronized (mPackages) {
13269            PackageSetting ps = mSettings.mPackages.get(packageName);
13270            if (ps == null) {
13271                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13272                return false;
13273            }
13274            return ps.getBlockUninstall(userId);
13275        }
13276    }
13277
13278    /*
13279     * This method handles package deletion in general
13280     */
13281    private boolean deletePackageLI(String packageName, UserHandle user,
13282            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13283            int flags, PackageRemovedInfo outInfo,
13284            boolean writeSettings) {
13285        if (packageName == null) {
13286            Slog.w(TAG, "Attempt to delete null packageName.");
13287            return false;
13288        }
13289        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13290        PackageSetting ps;
13291        boolean dataOnly = false;
13292        int removeUser = -1;
13293        int appId = -1;
13294        synchronized (mPackages) {
13295            ps = mSettings.mPackages.get(packageName);
13296            if (ps == null) {
13297                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13298                return false;
13299            }
13300            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13301                    && user.getIdentifier() != UserHandle.USER_ALL) {
13302                // The caller is asking that the package only be deleted for a single
13303                // user.  To do this, we just mark its uninstalled state and delete
13304                // its data.  If this is a system app, we only allow this to happen if
13305                // they have set the special DELETE_SYSTEM_APP which requests different
13306                // semantics than normal for uninstalling system apps.
13307                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13308                final int userId = user.getIdentifier();
13309                ps.setUserState(userId,
13310                        COMPONENT_ENABLED_STATE_DEFAULT,
13311                        false, //installed
13312                        true,  //stopped
13313                        true,  //notLaunched
13314                        false, //hidden
13315                        null, null, null,
13316                        false, // blockUninstall
13317                        ps.readUserState(userId).domainVerificationStatus, 0);
13318                if (!isSystemApp(ps)) {
13319                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13320                        // Other user still have this package installed, so all
13321                        // we need to do is clear this user's data and save that
13322                        // it is uninstalled.
13323                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13324                        removeUser = user.getIdentifier();
13325                        appId = ps.appId;
13326                        scheduleWritePackageRestrictionsLocked(removeUser);
13327                    } else {
13328                        // We need to set it back to 'installed' so the uninstall
13329                        // broadcasts will be sent correctly.
13330                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13331                        ps.setInstalled(true, user.getIdentifier());
13332                    }
13333                } else {
13334                    // This is a system app, so we assume that the
13335                    // other users still have this package installed, so all
13336                    // we need to do is clear this user's data and save that
13337                    // it is uninstalled.
13338                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13339                    removeUser = user.getIdentifier();
13340                    appId = ps.appId;
13341                    scheduleWritePackageRestrictionsLocked(removeUser);
13342                }
13343            }
13344        }
13345
13346        if (removeUser >= 0) {
13347            // From above, we determined that we are deleting this only
13348            // for a single user.  Continue the work here.
13349            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13350            if (outInfo != null) {
13351                outInfo.removedPackage = packageName;
13352                outInfo.removedAppId = appId;
13353                outInfo.removedUsers = new int[] {removeUser};
13354            }
13355            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13356            removeKeystoreDataIfNeeded(removeUser, appId);
13357            schedulePackageCleaning(packageName, removeUser, false);
13358            synchronized (mPackages) {
13359                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13360                    scheduleWritePackageRestrictionsLocked(removeUser);
13361                }
13362                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13363            }
13364            return true;
13365        }
13366
13367        if (dataOnly) {
13368            // Delete application data first
13369            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13370            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13371            return true;
13372        }
13373
13374        boolean ret = false;
13375        if (isSystemApp(ps)) {
13376            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13377            // When an updated system application is deleted we delete the existing resources as well and
13378            // fall back to existing code in system partition
13379            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13380                    flags, outInfo, writeSettings);
13381        } else {
13382            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13383            // Kill application pre-emptively especially for apps on sd.
13384            killApplication(packageName, ps.appId, "uninstall pkg");
13385            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13386                    allUserHandles, perUserInstalled,
13387                    outInfo, writeSettings);
13388        }
13389
13390        return ret;
13391    }
13392
13393    private final class ClearStorageConnection implements ServiceConnection {
13394        IMediaContainerService mContainerService;
13395
13396        @Override
13397        public void onServiceConnected(ComponentName name, IBinder service) {
13398            synchronized (this) {
13399                mContainerService = IMediaContainerService.Stub.asInterface(service);
13400                notifyAll();
13401            }
13402        }
13403
13404        @Override
13405        public void onServiceDisconnected(ComponentName name) {
13406        }
13407    }
13408
13409    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13410        final boolean mounted;
13411        if (Environment.isExternalStorageEmulated()) {
13412            mounted = true;
13413        } else {
13414            final String status = Environment.getExternalStorageState();
13415
13416            mounted = status.equals(Environment.MEDIA_MOUNTED)
13417                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13418        }
13419
13420        if (!mounted) {
13421            return;
13422        }
13423
13424        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13425        int[] users;
13426        if (userId == UserHandle.USER_ALL) {
13427            users = sUserManager.getUserIds();
13428        } else {
13429            users = new int[] { userId };
13430        }
13431        final ClearStorageConnection conn = new ClearStorageConnection();
13432        if (mContext.bindServiceAsUser(
13433                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13434            try {
13435                for (int curUser : users) {
13436                    long timeout = SystemClock.uptimeMillis() + 5000;
13437                    synchronized (conn) {
13438                        long now = SystemClock.uptimeMillis();
13439                        while (conn.mContainerService == null && now < timeout) {
13440                            try {
13441                                conn.wait(timeout - now);
13442                            } catch (InterruptedException e) {
13443                            }
13444                        }
13445                    }
13446                    if (conn.mContainerService == null) {
13447                        return;
13448                    }
13449
13450                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13451                    clearDirectory(conn.mContainerService,
13452                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13453                    if (allData) {
13454                        clearDirectory(conn.mContainerService,
13455                                userEnv.buildExternalStorageAppDataDirs(packageName));
13456                        clearDirectory(conn.mContainerService,
13457                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13458                    }
13459                }
13460            } finally {
13461                mContext.unbindService(conn);
13462            }
13463        }
13464    }
13465
13466    @Override
13467    public void clearApplicationUserData(final String packageName,
13468            final IPackageDataObserver observer, final int userId) {
13469        mContext.enforceCallingOrSelfPermission(
13470                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13471        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13472        // Queue up an async operation since the package deletion may take a little while.
13473        mHandler.post(new Runnable() {
13474            public void run() {
13475                mHandler.removeCallbacks(this);
13476                final boolean succeeded;
13477                synchronized (mInstallLock) {
13478                    succeeded = clearApplicationUserDataLI(packageName, userId);
13479                }
13480                clearExternalStorageDataSync(packageName, userId, true);
13481                if (succeeded) {
13482                    // invoke DeviceStorageMonitor's update method to clear any notifications
13483                    DeviceStorageMonitorInternal
13484                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13485                    if (dsm != null) {
13486                        dsm.checkMemory();
13487                    }
13488                }
13489                if(observer != null) {
13490                    try {
13491                        observer.onRemoveCompleted(packageName, succeeded);
13492                    } catch (RemoteException e) {
13493                        Log.i(TAG, "Observer no longer exists.");
13494                    }
13495                } //end if observer
13496            } //end run
13497        });
13498    }
13499
13500    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13501        if (packageName == null) {
13502            Slog.w(TAG, "Attempt to delete null packageName.");
13503            return false;
13504        }
13505
13506        // Try finding details about the requested package
13507        PackageParser.Package pkg;
13508        synchronized (mPackages) {
13509            pkg = mPackages.get(packageName);
13510            if (pkg == null) {
13511                final PackageSetting ps = mSettings.mPackages.get(packageName);
13512                if (ps != null) {
13513                    pkg = ps.pkg;
13514                }
13515            }
13516
13517            if (pkg == null) {
13518                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13519                return false;
13520            }
13521
13522            PackageSetting ps = (PackageSetting) pkg.mExtras;
13523            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13524        }
13525
13526        // Always delete data directories for package, even if we found no other
13527        // record of app. This helps users recover from UID mismatches without
13528        // resorting to a full data wipe.
13529        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13530        if (retCode < 0) {
13531            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13532            return false;
13533        }
13534
13535        final int appId = pkg.applicationInfo.uid;
13536        removeKeystoreDataIfNeeded(userId, appId);
13537
13538        // Create a native library symlink only if we have native libraries
13539        // and if the native libraries are 32 bit libraries. We do not provide
13540        // this symlink for 64 bit libraries.
13541        if (pkg.applicationInfo.primaryCpuAbi != null &&
13542                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13543            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13544            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13545                    nativeLibPath, userId) < 0) {
13546                Slog.w(TAG, "Failed linking native library dir");
13547                return false;
13548            }
13549        }
13550
13551        return true;
13552    }
13553
13554    /**
13555     * Reverts user permission state changes (permissions and flags) in
13556     * all packages for a given user.
13557     *
13558     * @param userId The device user for which to do a reset.
13559     */
13560    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13561        final int packageCount = mPackages.size();
13562        for (int i = 0; i < packageCount; i++) {
13563            PackageParser.Package pkg = mPackages.valueAt(i);
13564            PackageSetting ps = (PackageSetting) pkg.mExtras;
13565            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13566        }
13567    }
13568
13569    /**
13570     * Reverts user permission state changes (permissions and flags).
13571     *
13572     * @param ps The package for which to reset.
13573     * @param userId The device user for which to do a reset.
13574     */
13575    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13576            final PackageSetting ps, final int userId) {
13577        if (ps.pkg == null) {
13578            return;
13579        }
13580
13581        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13582                | FLAG_PERMISSION_USER_FIXED
13583                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13584
13585        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13586                | FLAG_PERMISSION_POLICY_FIXED;
13587
13588        boolean writeInstallPermissions = false;
13589        boolean writeRuntimePermissions = false;
13590
13591        final int permissionCount = ps.pkg.requestedPermissions.size();
13592        for (int i = 0; i < permissionCount; i++) {
13593            String permission = ps.pkg.requestedPermissions.get(i);
13594
13595            BasePermission bp = mSettings.mPermissions.get(permission);
13596            if (bp == null) {
13597                continue;
13598            }
13599
13600            // If shared user we just reset the state to which only this app contributed.
13601            if (ps.sharedUser != null) {
13602                boolean used = false;
13603                final int packageCount = ps.sharedUser.packages.size();
13604                for (int j = 0; j < packageCount; j++) {
13605                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13606                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13607                            && pkg.pkg.requestedPermissions.contains(permission)) {
13608                        used = true;
13609                        break;
13610                    }
13611                }
13612                if (used) {
13613                    continue;
13614                }
13615            }
13616
13617            PermissionsState permissionsState = ps.getPermissionsState();
13618
13619            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13620
13621            // Always clear the user settable flags.
13622            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13623                    bp.name) != null;
13624            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13625                if (hasInstallState) {
13626                    writeInstallPermissions = true;
13627                } else {
13628                    writeRuntimePermissions = true;
13629                }
13630            }
13631
13632            // Below is only runtime permission handling.
13633            if (!bp.isRuntime()) {
13634                continue;
13635            }
13636
13637            // Never clobber system or policy.
13638            if ((oldFlags & policyOrSystemFlags) != 0) {
13639                continue;
13640            }
13641
13642            // If this permission was granted by default, make sure it is.
13643            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13644                if (permissionsState.grantRuntimePermission(bp, userId)
13645                        != PERMISSION_OPERATION_FAILURE) {
13646                    writeRuntimePermissions = true;
13647                }
13648            } else {
13649                // Otherwise, reset the permission.
13650                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13651                switch (revokeResult) {
13652                    case PERMISSION_OPERATION_SUCCESS: {
13653                        writeRuntimePermissions = true;
13654                    } break;
13655
13656                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13657                        writeRuntimePermissions = true;
13658                        final int appId = ps.appId;
13659                        mHandler.post(new Runnable() {
13660                            @Override
13661                            public void run() {
13662                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13663                            }
13664                        });
13665                    } break;
13666                }
13667            }
13668        }
13669
13670        // Synchronously write as we are taking permissions away.
13671        if (writeRuntimePermissions) {
13672            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13673        }
13674
13675        // Synchronously write as we are taking permissions away.
13676        if (writeInstallPermissions) {
13677            mSettings.writeLPr();
13678        }
13679    }
13680
13681    /**
13682     * Remove entries from the keystore daemon. Will only remove it if the
13683     * {@code appId} is valid.
13684     */
13685    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13686        if (appId < 0) {
13687            return;
13688        }
13689
13690        final KeyStore keyStore = KeyStore.getInstance();
13691        if (keyStore != null) {
13692            if (userId == UserHandle.USER_ALL) {
13693                for (final int individual : sUserManager.getUserIds()) {
13694                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13695                }
13696            } else {
13697                keyStore.clearUid(UserHandle.getUid(userId, appId));
13698            }
13699        } else {
13700            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13701        }
13702    }
13703
13704    @Override
13705    public void deleteApplicationCacheFiles(final String packageName,
13706            final IPackageDataObserver observer) {
13707        mContext.enforceCallingOrSelfPermission(
13708                android.Manifest.permission.DELETE_CACHE_FILES, null);
13709        // Queue up an async operation since the package deletion may take a little while.
13710        final int userId = UserHandle.getCallingUserId();
13711        mHandler.post(new Runnable() {
13712            public void run() {
13713                mHandler.removeCallbacks(this);
13714                final boolean succeded;
13715                synchronized (mInstallLock) {
13716                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13717                }
13718                clearExternalStorageDataSync(packageName, userId, false);
13719                if (observer != null) {
13720                    try {
13721                        observer.onRemoveCompleted(packageName, succeded);
13722                    } catch (RemoteException e) {
13723                        Log.i(TAG, "Observer no longer exists.");
13724                    }
13725                } //end if observer
13726            } //end run
13727        });
13728    }
13729
13730    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13731        if (packageName == null) {
13732            Slog.w(TAG, "Attempt to delete null packageName.");
13733            return false;
13734        }
13735        PackageParser.Package p;
13736        synchronized (mPackages) {
13737            p = mPackages.get(packageName);
13738        }
13739        if (p == null) {
13740            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13741            return false;
13742        }
13743        final ApplicationInfo applicationInfo = p.applicationInfo;
13744        if (applicationInfo == null) {
13745            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13746            return false;
13747        }
13748        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13749        if (retCode < 0) {
13750            Slog.w(TAG, "Couldn't remove cache files for package: "
13751                       + packageName + " u" + userId);
13752            return false;
13753        }
13754        return true;
13755    }
13756
13757    @Override
13758    public void getPackageSizeInfo(final String packageName, int userHandle,
13759            final IPackageStatsObserver observer) {
13760        mContext.enforceCallingOrSelfPermission(
13761                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13762        if (packageName == null) {
13763            throw new IllegalArgumentException("Attempt to get size of null packageName");
13764        }
13765
13766        PackageStats stats = new PackageStats(packageName, userHandle);
13767
13768        /*
13769         * Queue up an async operation since the package measurement may take a
13770         * little while.
13771         */
13772        Message msg = mHandler.obtainMessage(INIT_COPY);
13773        msg.obj = new MeasureParams(stats, observer);
13774        mHandler.sendMessage(msg);
13775    }
13776
13777    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13778            PackageStats pStats) {
13779        if (packageName == null) {
13780            Slog.w(TAG, "Attempt to get size of null packageName.");
13781            return false;
13782        }
13783        PackageParser.Package p;
13784        boolean dataOnly = false;
13785        String libDirRoot = null;
13786        String asecPath = null;
13787        PackageSetting ps = null;
13788        synchronized (mPackages) {
13789            p = mPackages.get(packageName);
13790            ps = mSettings.mPackages.get(packageName);
13791            if(p == null) {
13792                dataOnly = true;
13793                if((ps == null) || (ps.pkg == null)) {
13794                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13795                    return false;
13796                }
13797                p = ps.pkg;
13798            }
13799            if (ps != null) {
13800                libDirRoot = ps.legacyNativeLibraryPathString;
13801            }
13802            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13803                final long token = Binder.clearCallingIdentity();
13804                try {
13805                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13806                    if (secureContainerId != null) {
13807                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13808                    }
13809                } finally {
13810                    Binder.restoreCallingIdentity(token);
13811                }
13812            }
13813        }
13814        String publicSrcDir = null;
13815        if(!dataOnly) {
13816            final ApplicationInfo applicationInfo = p.applicationInfo;
13817            if (applicationInfo == null) {
13818                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13819                return false;
13820            }
13821            if (p.isForwardLocked()) {
13822                publicSrcDir = applicationInfo.getBaseResourcePath();
13823            }
13824        }
13825        // TODO: extend to measure size of split APKs
13826        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13827        // not just the first level.
13828        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13829        // just the primary.
13830        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13831
13832        String apkPath;
13833        File packageDir = new File(p.codePath);
13834
13835        if (packageDir.isDirectory() && p.canHaveOatDir()) {
13836            apkPath = packageDir.getAbsolutePath();
13837            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
13838            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
13839                libDirRoot = null;
13840            }
13841        } else {
13842            apkPath = p.baseCodePath;
13843        }
13844
13845        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
13846                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13847        if (res < 0) {
13848            return false;
13849        }
13850
13851        // Fix-up for forward-locked applications in ASEC containers.
13852        if (!isExternal(p)) {
13853            pStats.codeSize += pStats.externalCodeSize;
13854            pStats.externalCodeSize = 0L;
13855        }
13856
13857        return true;
13858    }
13859
13860
13861    @Override
13862    public void addPackageToPreferred(String packageName) {
13863        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13864    }
13865
13866    @Override
13867    public void removePackageFromPreferred(String packageName) {
13868        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13869    }
13870
13871    @Override
13872    public List<PackageInfo> getPreferredPackages(int flags) {
13873        return new ArrayList<PackageInfo>();
13874    }
13875
13876    private int getUidTargetSdkVersionLockedLPr(int uid) {
13877        Object obj = mSettings.getUserIdLPr(uid);
13878        if (obj instanceof SharedUserSetting) {
13879            final SharedUserSetting sus = (SharedUserSetting) obj;
13880            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13881            final Iterator<PackageSetting> it = sus.packages.iterator();
13882            while (it.hasNext()) {
13883                final PackageSetting ps = it.next();
13884                if (ps.pkg != null) {
13885                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13886                    if (v < vers) vers = v;
13887                }
13888            }
13889            return vers;
13890        } else if (obj instanceof PackageSetting) {
13891            final PackageSetting ps = (PackageSetting) obj;
13892            if (ps.pkg != null) {
13893                return ps.pkg.applicationInfo.targetSdkVersion;
13894            }
13895        }
13896        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13897    }
13898
13899    @Override
13900    public void addPreferredActivity(IntentFilter filter, int match,
13901            ComponentName[] set, ComponentName activity, int userId) {
13902        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13903                "Adding preferred");
13904    }
13905
13906    private void addPreferredActivityInternal(IntentFilter filter, int match,
13907            ComponentName[] set, ComponentName activity, boolean always, int userId,
13908            String opname) {
13909        // writer
13910        int callingUid = Binder.getCallingUid();
13911        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13912        if (filter.countActions() == 0) {
13913            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13914            return;
13915        }
13916        synchronized (mPackages) {
13917            if (mContext.checkCallingOrSelfPermission(
13918                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13919                    != PackageManager.PERMISSION_GRANTED) {
13920                if (getUidTargetSdkVersionLockedLPr(callingUid)
13921                        < Build.VERSION_CODES.FROYO) {
13922                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13923                            + callingUid);
13924                    return;
13925                }
13926                mContext.enforceCallingOrSelfPermission(
13927                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13928            }
13929
13930            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13931            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13932                    + userId + ":");
13933            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13934            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13935            scheduleWritePackageRestrictionsLocked(userId);
13936        }
13937    }
13938
13939    @Override
13940    public void replacePreferredActivity(IntentFilter filter, int match,
13941            ComponentName[] set, ComponentName activity, int userId) {
13942        if (filter.countActions() != 1) {
13943            throw new IllegalArgumentException(
13944                    "replacePreferredActivity expects filter to have only 1 action.");
13945        }
13946        if (filter.countDataAuthorities() != 0
13947                || filter.countDataPaths() != 0
13948                || filter.countDataSchemes() > 1
13949                || filter.countDataTypes() != 0) {
13950            throw new IllegalArgumentException(
13951                    "replacePreferredActivity expects filter to have no data authorities, " +
13952                    "paths, or types; and at most one scheme.");
13953        }
13954
13955        final int callingUid = Binder.getCallingUid();
13956        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13957        synchronized (mPackages) {
13958            if (mContext.checkCallingOrSelfPermission(
13959                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13960                    != PackageManager.PERMISSION_GRANTED) {
13961                if (getUidTargetSdkVersionLockedLPr(callingUid)
13962                        < Build.VERSION_CODES.FROYO) {
13963                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13964                            + Binder.getCallingUid());
13965                    return;
13966                }
13967                mContext.enforceCallingOrSelfPermission(
13968                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13969            }
13970
13971            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13972            if (pir != null) {
13973                // Get all of the existing entries that exactly match this filter.
13974                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13975                if (existing != null && existing.size() == 1) {
13976                    PreferredActivity cur = existing.get(0);
13977                    if (DEBUG_PREFERRED) {
13978                        Slog.i(TAG, "Checking replace of preferred:");
13979                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13980                        if (!cur.mPref.mAlways) {
13981                            Slog.i(TAG, "  -- CUR; not mAlways!");
13982                        } else {
13983                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13984                            Slog.i(TAG, "  -- CUR: mSet="
13985                                    + Arrays.toString(cur.mPref.mSetComponents));
13986                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13987                            Slog.i(TAG, "  -- NEW: mMatch="
13988                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13989                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13990                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13991                        }
13992                    }
13993                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13994                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13995                            && cur.mPref.sameSet(set)) {
13996                        // Setting the preferred activity to what it happens to be already
13997                        if (DEBUG_PREFERRED) {
13998                            Slog.i(TAG, "Replacing with same preferred activity "
13999                                    + cur.mPref.mShortComponent + " for user "
14000                                    + userId + ":");
14001                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14002                        }
14003                        return;
14004                    }
14005                }
14006
14007                if (existing != null) {
14008                    if (DEBUG_PREFERRED) {
14009                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14010                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14011                    }
14012                    for (int i = 0; i < existing.size(); i++) {
14013                        PreferredActivity pa = existing.get(i);
14014                        if (DEBUG_PREFERRED) {
14015                            Slog.i(TAG, "Removing existing preferred activity "
14016                                    + pa.mPref.mComponent + ":");
14017                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14018                        }
14019                        pir.removeFilter(pa);
14020                    }
14021                }
14022            }
14023            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14024                    "Replacing preferred");
14025        }
14026    }
14027
14028    @Override
14029    public void clearPackagePreferredActivities(String packageName) {
14030        final int uid = Binder.getCallingUid();
14031        // writer
14032        synchronized (mPackages) {
14033            PackageParser.Package pkg = mPackages.get(packageName);
14034            if (pkg == null || pkg.applicationInfo.uid != uid) {
14035                if (mContext.checkCallingOrSelfPermission(
14036                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14037                        != PackageManager.PERMISSION_GRANTED) {
14038                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14039                            < Build.VERSION_CODES.FROYO) {
14040                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14041                                + Binder.getCallingUid());
14042                        return;
14043                    }
14044                    mContext.enforceCallingOrSelfPermission(
14045                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14046                }
14047            }
14048
14049            int user = UserHandle.getCallingUserId();
14050            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14051                scheduleWritePackageRestrictionsLocked(user);
14052            }
14053        }
14054    }
14055
14056    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14057    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14058        ArrayList<PreferredActivity> removed = null;
14059        boolean changed = false;
14060        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14061            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14062            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14063            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14064                continue;
14065            }
14066            Iterator<PreferredActivity> it = pir.filterIterator();
14067            while (it.hasNext()) {
14068                PreferredActivity pa = it.next();
14069                // Mark entry for removal only if it matches the package name
14070                // and the entry is of type "always".
14071                if (packageName == null ||
14072                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14073                                && pa.mPref.mAlways)) {
14074                    if (removed == null) {
14075                        removed = new ArrayList<PreferredActivity>();
14076                    }
14077                    removed.add(pa);
14078                }
14079            }
14080            if (removed != null) {
14081                for (int j=0; j<removed.size(); j++) {
14082                    PreferredActivity pa = removed.get(j);
14083                    pir.removeFilter(pa);
14084                }
14085                changed = true;
14086            }
14087        }
14088        return changed;
14089    }
14090
14091    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14092    private void clearIntentFilterVerificationsLPw(int userId) {
14093        final int packageCount = mPackages.size();
14094        for (int i = 0; i < packageCount; i++) {
14095            PackageParser.Package pkg = mPackages.valueAt(i);
14096            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14097        }
14098    }
14099
14100    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14101    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14102        if (userId == UserHandle.USER_ALL) {
14103            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14104                    sUserManager.getUserIds())) {
14105                for (int oneUserId : sUserManager.getUserIds()) {
14106                    scheduleWritePackageRestrictionsLocked(oneUserId);
14107                }
14108            }
14109        } else {
14110            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14111                scheduleWritePackageRestrictionsLocked(userId);
14112            }
14113        }
14114    }
14115
14116    void clearDefaultBrowserIfNeeded(String packageName) {
14117        for (int oneUserId : sUserManager.getUserIds()) {
14118            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14119            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14120            if (packageName.equals(defaultBrowserPackageName)) {
14121                setDefaultBrowserPackageName(null, oneUserId);
14122            }
14123        }
14124    }
14125
14126    @Override
14127    public void resetApplicationPreferences(int userId) {
14128        mContext.enforceCallingOrSelfPermission(
14129                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14130        // writer
14131        synchronized (mPackages) {
14132            final long identity = Binder.clearCallingIdentity();
14133            try {
14134                clearPackagePreferredActivitiesLPw(null, userId);
14135                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14136                // TODO: We have to reset the default SMS and Phone. This requires
14137                // significant refactoring to keep all default apps in the package
14138                // manager (cleaner but more work) or have the services provide
14139                // callbacks to the package manager to request a default app reset.
14140                applyFactoryDefaultBrowserLPw(userId);
14141                clearIntentFilterVerificationsLPw(userId);
14142                primeDomainVerificationsLPw(userId);
14143                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14144                scheduleWritePackageRestrictionsLocked(userId);
14145            } finally {
14146                Binder.restoreCallingIdentity(identity);
14147            }
14148        }
14149    }
14150
14151    @Override
14152    public int getPreferredActivities(List<IntentFilter> outFilters,
14153            List<ComponentName> outActivities, String packageName) {
14154
14155        int num = 0;
14156        final int userId = UserHandle.getCallingUserId();
14157        // reader
14158        synchronized (mPackages) {
14159            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14160            if (pir != null) {
14161                final Iterator<PreferredActivity> it = pir.filterIterator();
14162                while (it.hasNext()) {
14163                    final PreferredActivity pa = it.next();
14164                    if (packageName == null
14165                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14166                                    && pa.mPref.mAlways)) {
14167                        if (outFilters != null) {
14168                            outFilters.add(new IntentFilter(pa));
14169                        }
14170                        if (outActivities != null) {
14171                            outActivities.add(pa.mPref.mComponent);
14172                        }
14173                    }
14174                }
14175            }
14176        }
14177
14178        return num;
14179    }
14180
14181    @Override
14182    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14183            int userId) {
14184        int callingUid = Binder.getCallingUid();
14185        if (callingUid != Process.SYSTEM_UID) {
14186            throw new SecurityException(
14187                    "addPersistentPreferredActivity can only be run by the system");
14188        }
14189        if (filter.countActions() == 0) {
14190            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14191            return;
14192        }
14193        synchronized (mPackages) {
14194            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14195                    " :");
14196            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14197            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14198                    new PersistentPreferredActivity(filter, activity));
14199            scheduleWritePackageRestrictionsLocked(userId);
14200        }
14201    }
14202
14203    @Override
14204    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14205        int callingUid = Binder.getCallingUid();
14206        if (callingUid != Process.SYSTEM_UID) {
14207            throw new SecurityException(
14208                    "clearPackagePersistentPreferredActivities can only be run by the system");
14209        }
14210        ArrayList<PersistentPreferredActivity> removed = null;
14211        boolean changed = false;
14212        synchronized (mPackages) {
14213            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14214                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14215                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14216                        .valueAt(i);
14217                if (userId != thisUserId) {
14218                    continue;
14219                }
14220                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14221                while (it.hasNext()) {
14222                    PersistentPreferredActivity ppa = it.next();
14223                    // Mark entry for removal only if it matches the package name.
14224                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14225                        if (removed == null) {
14226                            removed = new ArrayList<PersistentPreferredActivity>();
14227                        }
14228                        removed.add(ppa);
14229                    }
14230                }
14231                if (removed != null) {
14232                    for (int j=0; j<removed.size(); j++) {
14233                        PersistentPreferredActivity ppa = removed.get(j);
14234                        ppir.removeFilter(ppa);
14235                    }
14236                    changed = true;
14237                }
14238            }
14239
14240            if (changed) {
14241                scheduleWritePackageRestrictionsLocked(userId);
14242            }
14243        }
14244    }
14245
14246    /**
14247     * Common machinery for picking apart a restored XML blob and passing
14248     * it to a caller-supplied functor to be applied to the running system.
14249     */
14250    private void restoreFromXml(XmlPullParser parser, int userId,
14251            String expectedStartTag, BlobXmlRestorer functor)
14252            throws IOException, XmlPullParserException {
14253        int type;
14254        while ((type = parser.next()) != XmlPullParser.START_TAG
14255                && type != XmlPullParser.END_DOCUMENT) {
14256        }
14257        if (type != XmlPullParser.START_TAG) {
14258            // oops didn't find a start tag?!
14259            if (DEBUG_BACKUP) {
14260                Slog.e(TAG, "Didn't find start tag during restore");
14261            }
14262            return;
14263        }
14264
14265        // this is supposed to be TAG_PREFERRED_BACKUP
14266        if (!expectedStartTag.equals(parser.getName())) {
14267            if (DEBUG_BACKUP) {
14268                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14269            }
14270            return;
14271        }
14272
14273        // skip interfering stuff, then we're aligned with the backing implementation
14274        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14275        functor.apply(parser, userId);
14276    }
14277
14278    private interface BlobXmlRestorer {
14279        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14280    }
14281
14282    /**
14283     * Non-Binder method, support for the backup/restore mechanism: write the
14284     * full set of preferred activities in its canonical XML format.  Returns the
14285     * XML output as a byte array, or null if there is none.
14286     */
14287    @Override
14288    public byte[] getPreferredActivityBackup(int userId) {
14289        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14290            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14291        }
14292
14293        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14294        try {
14295            final XmlSerializer serializer = new FastXmlSerializer();
14296            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14297            serializer.startDocument(null, true);
14298            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14299
14300            synchronized (mPackages) {
14301                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14302            }
14303
14304            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14305            serializer.endDocument();
14306            serializer.flush();
14307        } catch (Exception e) {
14308            if (DEBUG_BACKUP) {
14309                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14310            }
14311            return null;
14312        }
14313
14314        return dataStream.toByteArray();
14315    }
14316
14317    @Override
14318    public void restorePreferredActivities(byte[] backup, int userId) {
14319        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14320            throw new SecurityException("Only the system may call restorePreferredActivities()");
14321        }
14322
14323        try {
14324            final XmlPullParser parser = Xml.newPullParser();
14325            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14326            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14327                    new BlobXmlRestorer() {
14328                        @Override
14329                        public void apply(XmlPullParser parser, int userId)
14330                                throws XmlPullParserException, IOException {
14331                            synchronized (mPackages) {
14332                                mSettings.readPreferredActivitiesLPw(parser, userId);
14333                            }
14334                        }
14335                    } );
14336        } catch (Exception e) {
14337            if (DEBUG_BACKUP) {
14338                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14339            }
14340        }
14341    }
14342
14343    /**
14344     * Non-Binder method, support for the backup/restore mechanism: write the
14345     * default browser (etc) settings in its canonical XML format.  Returns the default
14346     * browser XML representation as a byte array, or null if there is none.
14347     */
14348    @Override
14349    public byte[] getDefaultAppsBackup(int userId) {
14350        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14351            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14352        }
14353
14354        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14355        try {
14356            final XmlSerializer serializer = new FastXmlSerializer();
14357            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14358            serializer.startDocument(null, true);
14359            serializer.startTag(null, TAG_DEFAULT_APPS);
14360
14361            synchronized (mPackages) {
14362                mSettings.writeDefaultAppsLPr(serializer, userId);
14363            }
14364
14365            serializer.endTag(null, TAG_DEFAULT_APPS);
14366            serializer.endDocument();
14367            serializer.flush();
14368        } catch (Exception e) {
14369            if (DEBUG_BACKUP) {
14370                Slog.e(TAG, "Unable to write default apps for backup", e);
14371            }
14372            return null;
14373        }
14374
14375        return dataStream.toByteArray();
14376    }
14377
14378    @Override
14379    public void restoreDefaultApps(byte[] backup, int userId) {
14380        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14381            throw new SecurityException("Only the system may call restoreDefaultApps()");
14382        }
14383
14384        try {
14385            final XmlPullParser parser = Xml.newPullParser();
14386            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14387            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14388                    new BlobXmlRestorer() {
14389                        @Override
14390                        public void apply(XmlPullParser parser, int userId)
14391                                throws XmlPullParserException, IOException {
14392                            synchronized (mPackages) {
14393                                mSettings.readDefaultAppsLPw(parser, userId);
14394                            }
14395                        }
14396                    } );
14397        } catch (Exception e) {
14398            if (DEBUG_BACKUP) {
14399                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14400            }
14401        }
14402    }
14403
14404    @Override
14405    public byte[] getIntentFilterVerificationBackup(int userId) {
14406        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14407            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14408        }
14409
14410        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14411        try {
14412            final XmlSerializer serializer = new FastXmlSerializer();
14413            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14414            serializer.startDocument(null, true);
14415            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14416
14417            synchronized (mPackages) {
14418                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14419            }
14420
14421            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14422            serializer.endDocument();
14423            serializer.flush();
14424        } catch (Exception e) {
14425            if (DEBUG_BACKUP) {
14426                Slog.e(TAG, "Unable to write default apps for backup", e);
14427            }
14428            return null;
14429        }
14430
14431        return dataStream.toByteArray();
14432    }
14433
14434    @Override
14435    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14436        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14437            throw new SecurityException("Only the system may call restorePreferredActivities()");
14438        }
14439
14440        try {
14441            final XmlPullParser parser = Xml.newPullParser();
14442            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14443            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14444                    new BlobXmlRestorer() {
14445                        @Override
14446                        public void apply(XmlPullParser parser, int userId)
14447                                throws XmlPullParserException, IOException {
14448                            synchronized (mPackages) {
14449                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14450                                mSettings.writeLPr();
14451                            }
14452                        }
14453                    } );
14454        } catch (Exception e) {
14455            if (DEBUG_BACKUP) {
14456                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14457            }
14458        }
14459    }
14460
14461    @Override
14462    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14463            int sourceUserId, int targetUserId, int flags) {
14464        mContext.enforceCallingOrSelfPermission(
14465                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14466        int callingUid = Binder.getCallingUid();
14467        enforceOwnerRights(ownerPackage, callingUid);
14468        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14469        if (intentFilter.countActions() == 0) {
14470            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14471            return;
14472        }
14473        synchronized (mPackages) {
14474            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14475                    ownerPackage, targetUserId, flags);
14476            CrossProfileIntentResolver resolver =
14477                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14478            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14479            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14480            if (existing != null) {
14481                int size = existing.size();
14482                for (int i = 0; i < size; i++) {
14483                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14484                        return;
14485                    }
14486                }
14487            }
14488            resolver.addFilter(newFilter);
14489            scheduleWritePackageRestrictionsLocked(sourceUserId);
14490        }
14491    }
14492
14493    @Override
14494    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14495        mContext.enforceCallingOrSelfPermission(
14496                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14497        int callingUid = Binder.getCallingUid();
14498        enforceOwnerRights(ownerPackage, callingUid);
14499        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14500        synchronized (mPackages) {
14501            CrossProfileIntentResolver resolver =
14502                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14503            ArraySet<CrossProfileIntentFilter> set =
14504                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14505            for (CrossProfileIntentFilter filter : set) {
14506                if (filter.getOwnerPackage().equals(ownerPackage)) {
14507                    resolver.removeFilter(filter);
14508                }
14509            }
14510            scheduleWritePackageRestrictionsLocked(sourceUserId);
14511        }
14512    }
14513
14514    // Enforcing that callingUid is owning pkg on userId
14515    private void enforceOwnerRights(String pkg, int callingUid) {
14516        // The system owns everything.
14517        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14518            return;
14519        }
14520        int callingUserId = UserHandle.getUserId(callingUid);
14521        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14522        if (pi == null) {
14523            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14524                    + callingUserId);
14525        }
14526        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14527            throw new SecurityException("Calling uid " + callingUid
14528                    + " does not own package " + pkg);
14529        }
14530    }
14531
14532    @Override
14533    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14534        Intent intent = new Intent(Intent.ACTION_MAIN);
14535        intent.addCategory(Intent.CATEGORY_HOME);
14536
14537        final int callingUserId = UserHandle.getCallingUserId();
14538        List<ResolveInfo> list = queryIntentActivities(intent, null,
14539                PackageManager.GET_META_DATA, callingUserId);
14540        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14541                true, false, false, callingUserId);
14542
14543        allHomeCandidates.clear();
14544        if (list != null) {
14545            for (ResolveInfo ri : list) {
14546                allHomeCandidates.add(ri);
14547            }
14548        }
14549        return (preferred == null || preferred.activityInfo == null)
14550                ? null
14551                : new ComponentName(preferred.activityInfo.packageName,
14552                        preferred.activityInfo.name);
14553    }
14554
14555    @Override
14556    public void setApplicationEnabledSetting(String appPackageName,
14557            int newState, int flags, int userId, String callingPackage) {
14558        if (!sUserManager.exists(userId)) return;
14559        if (callingPackage == null) {
14560            callingPackage = Integer.toString(Binder.getCallingUid());
14561        }
14562        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14563    }
14564
14565    @Override
14566    public void setComponentEnabledSetting(ComponentName componentName,
14567            int newState, int flags, int userId) {
14568        if (!sUserManager.exists(userId)) return;
14569        setEnabledSetting(componentName.getPackageName(),
14570                componentName.getClassName(), newState, flags, userId, null);
14571    }
14572
14573    private void setEnabledSetting(final String packageName, String className, int newState,
14574            final int flags, int userId, String callingPackage) {
14575        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14576              || newState == COMPONENT_ENABLED_STATE_ENABLED
14577              || newState == COMPONENT_ENABLED_STATE_DISABLED
14578              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14579              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14580            throw new IllegalArgumentException("Invalid new component state: "
14581                    + newState);
14582        }
14583        PackageSetting pkgSetting;
14584        final int uid = Binder.getCallingUid();
14585        final int permission = mContext.checkCallingOrSelfPermission(
14586                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14587        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14588        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14589        boolean sendNow = false;
14590        boolean isApp = (className == null);
14591        String componentName = isApp ? packageName : className;
14592        int packageUid = -1;
14593        ArrayList<String> components;
14594
14595        // writer
14596        synchronized (mPackages) {
14597            pkgSetting = mSettings.mPackages.get(packageName);
14598            if (pkgSetting == null) {
14599                if (className == null) {
14600                    throw new IllegalArgumentException(
14601                            "Unknown package: " + packageName);
14602                }
14603                throw new IllegalArgumentException(
14604                        "Unknown component: " + packageName
14605                        + "/" + className);
14606            }
14607            // Allow root and verify that userId is not being specified by a different user
14608            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14609                throw new SecurityException(
14610                        "Permission Denial: attempt to change component state from pid="
14611                        + Binder.getCallingPid()
14612                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14613            }
14614            if (className == null) {
14615                // We're dealing with an application/package level state change
14616                if (pkgSetting.getEnabled(userId) == newState) {
14617                    // Nothing to do
14618                    return;
14619                }
14620                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14621                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14622                    // Don't care about who enables an app.
14623                    callingPackage = null;
14624                }
14625                pkgSetting.setEnabled(newState, userId, callingPackage);
14626                // pkgSetting.pkg.mSetEnabled = newState;
14627            } else {
14628                // We're dealing with a component level state change
14629                // First, verify that this is a valid class name.
14630                PackageParser.Package pkg = pkgSetting.pkg;
14631                if (pkg == null || !pkg.hasComponentClassName(className)) {
14632                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14633                        throw new IllegalArgumentException("Component class " + className
14634                                + " does not exist in " + packageName);
14635                    } else {
14636                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14637                                + className + " does not exist in " + packageName);
14638                    }
14639                }
14640                switch (newState) {
14641                case COMPONENT_ENABLED_STATE_ENABLED:
14642                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14643                        return;
14644                    }
14645                    break;
14646                case COMPONENT_ENABLED_STATE_DISABLED:
14647                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14648                        return;
14649                    }
14650                    break;
14651                case COMPONENT_ENABLED_STATE_DEFAULT:
14652                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14653                        return;
14654                    }
14655                    break;
14656                default:
14657                    Slog.e(TAG, "Invalid new component state: " + newState);
14658                    return;
14659                }
14660            }
14661            scheduleWritePackageRestrictionsLocked(userId);
14662            components = mPendingBroadcasts.get(userId, packageName);
14663            final boolean newPackage = components == null;
14664            if (newPackage) {
14665                components = new ArrayList<String>();
14666            }
14667            if (!components.contains(componentName)) {
14668                components.add(componentName);
14669            }
14670            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14671                sendNow = true;
14672                // Purge entry from pending broadcast list if another one exists already
14673                // since we are sending one right away.
14674                mPendingBroadcasts.remove(userId, packageName);
14675            } else {
14676                if (newPackage) {
14677                    mPendingBroadcasts.put(userId, packageName, components);
14678                }
14679                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14680                    // Schedule a message
14681                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14682                }
14683            }
14684        }
14685
14686        long callingId = Binder.clearCallingIdentity();
14687        try {
14688            if (sendNow) {
14689                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14690                sendPackageChangedBroadcast(packageName,
14691                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14692            }
14693        } finally {
14694            Binder.restoreCallingIdentity(callingId);
14695        }
14696    }
14697
14698    private void sendPackageChangedBroadcast(String packageName,
14699            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14700        if (DEBUG_INSTALL)
14701            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14702                    + componentNames);
14703        Bundle extras = new Bundle(4);
14704        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14705        String nameList[] = new String[componentNames.size()];
14706        componentNames.toArray(nameList);
14707        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14708        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14709        extras.putInt(Intent.EXTRA_UID, packageUid);
14710        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14711                new int[] {UserHandle.getUserId(packageUid)});
14712    }
14713
14714    @Override
14715    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14716        if (!sUserManager.exists(userId)) return;
14717        final int uid = Binder.getCallingUid();
14718        final int permission = mContext.checkCallingOrSelfPermission(
14719                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14720        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14721        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14722        // writer
14723        synchronized (mPackages) {
14724            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14725                    allowedByPermission, uid, userId)) {
14726                scheduleWritePackageRestrictionsLocked(userId);
14727            }
14728        }
14729    }
14730
14731    @Override
14732    public String getInstallerPackageName(String packageName) {
14733        // reader
14734        synchronized (mPackages) {
14735            return mSettings.getInstallerPackageNameLPr(packageName);
14736        }
14737    }
14738
14739    @Override
14740    public int getApplicationEnabledSetting(String packageName, int userId) {
14741        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14742        int uid = Binder.getCallingUid();
14743        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14744        // reader
14745        synchronized (mPackages) {
14746            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14747        }
14748    }
14749
14750    @Override
14751    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14752        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14753        int uid = Binder.getCallingUid();
14754        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14755        // reader
14756        synchronized (mPackages) {
14757            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14758        }
14759    }
14760
14761    @Override
14762    public void enterSafeMode() {
14763        enforceSystemOrRoot("Only the system can request entering safe mode");
14764
14765        if (!mSystemReady) {
14766            mSafeMode = true;
14767        }
14768    }
14769
14770    @Override
14771    public void systemReady() {
14772        mSystemReady = true;
14773
14774        // Read the compatibilty setting when the system is ready.
14775        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14776                mContext.getContentResolver(),
14777                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14778        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14779        if (DEBUG_SETTINGS) {
14780            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14781        }
14782
14783        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14784
14785        synchronized (mPackages) {
14786            // Verify that all of the preferred activity components actually
14787            // exist.  It is possible for applications to be updated and at
14788            // that point remove a previously declared activity component that
14789            // had been set as a preferred activity.  We try to clean this up
14790            // the next time we encounter that preferred activity, but it is
14791            // possible for the user flow to never be able to return to that
14792            // situation so here we do a sanity check to make sure we haven't
14793            // left any junk around.
14794            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14795            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14796                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14797                removed.clear();
14798                for (PreferredActivity pa : pir.filterSet()) {
14799                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14800                        removed.add(pa);
14801                    }
14802                }
14803                if (removed.size() > 0) {
14804                    for (int r=0; r<removed.size(); r++) {
14805                        PreferredActivity pa = removed.get(r);
14806                        Slog.w(TAG, "Removing dangling preferred activity: "
14807                                + pa.mPref.mComponent);
14808                        pir.removeFilter(pa);
14809                    }
14810                    mSettings.writePackageRestrictionsLPr(
14811                            mSettings.mPreferredActivities.keyAt(i));
14812                }
14813            }
14814
14815            for (int userId : UserManagerService.getInstance().getUserIds()) {
14816                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14817                    grantPermissionsUserIds = ArrayUtils.appendInt(
14818                            grantPermissionsUserIds, userId);
14819                }
14820            }
14821        }
14822        sUserManager.systemReady();
14823
14824        // If we upgraded grant all default permissions before kicking off.
14825        for (int userId : grantPermissionsUserIds) {
14826            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14827        }
14828
14829        // Kick off any messages waiting for system ready
14830        if (mPostSystemReadyMessages != null) {
14831            for (Message msg : mPostSystemReadyMessages) {
14832                msg.sendToTarget();
14833            }
14834            mPostSystemReadyMessages = null;
14835        }
14836
14837        // Watch for external volumes that come and go over time
14838        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14839        storage.registerListener(mStorageListener);
14840
14841        mInstallerService.systemReady();
14842        mPackageDexOptimizer.systemReady();
14843
14844        MountServiceInternal mountServiceInternal = LocalServices.getService(
14845                MountServiceInternal.class);
14846        mountServiceInternal.addExternalStoragePolicy(
14847                new MountServiceInternal.ExternalStorageMountPolicy() {
14848            @Override
14849            public int getMountMode(int uid, String packageName) {
14850                if (Process.isIsolated(uid)) {
14851                    return Zygote.MOUNT_EXTERNAL_NONE;
14852                }
14853                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14854                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14855                }
14856                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14857                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14858                }
14859                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14860                    return Zygote.MOUNT_EXTERNAL_READ;
14861                }
14862                return Zygote.MOUNT_EXTERNAL_WRITE;
14863            }
14864
14865            @Override
14866            public boolean hasExternalStorage(int uid, String packageName) {
14867                return true;
14868            }
14869        });
14870    }
14871
14872    @Override
14873    public boolean isSafeMode() {
14874        return mSafeMode;
14875    }
14876
14877    @Override
14878    public boolean hasSystemUidErrors() {
14879        return mHasSystemUidErrors;
14880    }
14881
14882    static String arrayToString(int[] array) {
14883        StringBuffer buf = new StringBuffer(128);
14884        buf.append('[');
14885        if (array != null) {
14886            for (int i=0; i<array.length; i++) {
14887                if (i > 0) buf.append(", ");
14888                buf.append(array[i]);
14889            }
14890        }
14891        buf.append(']');
14892        return buf.toString();
14893    }
14894
14895    static class DumpState {
14896        public static final int DUMP_LIBS = 1 << 0;
14897        public static final int DUMP_FEATURES = 1 << 1;
14898        public static final int DUMP_RESOLVERS = 1 << 2;
14899        public static final int DUMP_PERMISSIONS = 1 << 3;
14900        public static final int DUMP_PACKAGES = 1 << 4;
14901        public static final int DUMP_SHARED_USERS = 1 << 5;
14902        public static final int DUMP_MESSAGES = 1 << 6;
14903        public static final int DUMP_PROVIDERS = 1 << 7;
14904        public static final int DUMP_VERIFIERS = 1 << 8;
14905        public static final int DUMP_PREFERRED = 1 << 9;
14906        public static final int DUMP_PREFERRED_XML = 1 << 10;
14907        public static final int DUMP_KEYSETS = 1 << 11;
14908        public static final int DUMP_VERSION = 1 << 12;
14909        public static final int DUMP_INSTALLS = 1 << 13;
14910        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14911        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14912
14913        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14914
14915        private int mTypes;
14916
14917        private int mOptions;
14918
14919        private boolean mTitlePrinted;
14920
14921        private SharedUserSetting mSharedUser;
14922
14923        public boolean isDumping(int type) {
14924            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14925                return true;
14926            }
14927
14928            return (mTypes & type) != 0;
14929        }
14930
14931        public void setDump(int type) {
14932            mTypes |= type;
14933        }
14934
14935        public boolean isOptionEnabled(int option) {
14936            return (mOptions & option) != 0;
14937        }
14938
14939        public void setOptionEnabled(int option) {
14940            mOptions |= option;
14941        }
14942
14943        public boolean onTitlePrinted() {
14944            final boolean printed = mTitlePrinted;
14945            mTitlePrinted = true;
14946            return printed;
14947        }
14948
14949        public boolean getTitlePrinted() {
14950            return mTitlePrinted;
14951        }
14952
14953        public void setTitlePrinted(boolean enabled) {
14954            mTitlePrinted = enabled;
14955        }
14956
14957        public SharedUserSetting getSharedUser() {
14958            return mSharedUser;
14959        }
14960
14961        public void setSharedUser(SharedUserSetting user) {
14962            mSharedUser = user;
14963        }
14964    }
14965
14966    @Override
14967    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14968        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14969                != PackageManager.PERMISSION_GRANTED) {
14970            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14971                    + Binder.getCallingPid()
14972                    + ", uid=" + Binder.getCallingUid()
14973                    + " without permission "
14974                    + android.Manifest.permission.DUMP);
14975            return;
14976        }
14977
14978        DumpState dumpState = new DumpState();
14979        boolean fullPreferred = false;
14980        boolean checkin = false;
14981
14982        String packageName = null;
14983        ArraySet<String> permissionNames = null;
14984
14985        int opti = 0;
14986        while (opti < args.length) {
14987            String opt = args[opti];
14988            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14989                break;
14990            }
14991            opti++;
14992
14993            if ("-a".equals(opt)) {
14994                // Right now we only know how to print all.
14995            } else if ("-h".equals(opt)) {
14996                pw.println("Package manager dump options:");
14997                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14998                pw.println("    --checkin: dump for a checkin");
14999                pw.println("    -f: print details of intent filters");
15000                pw.println("    -h: print this help");
15001                pw.println("  cmd may be one of:");
15002                pw.println("    l[ibraries]: list known shared libraries");
15003                pw.println("    f[ibraries]: list device features");
15004                pw.println("    k[eysets]: print known keysets");
15005                pw.println("    r[esolvers]: dump intent resolvers");
15006                pw.println("    perm[issions]: dump permissions");
15007                pw.println("    permission [name ...]: dump declaration and use of given permission");
15008                pw.println("    pref[erred]: print preferred package settings");
15009                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15010                pw.println("    prov[iders]: dump content providers");
15011                pw.println("    p[ackages]: dump installed packages");
15012                pw.println("    s[hared-users]: dump shared user IDs");
15013                pw.println("    m[essages]: print collected runtime messages");
15014                pw.println("    v[erifiers]: print package verifier info");
15015                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15016                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15017                pw.println("    version: print database version info");
15018                pw.println("    write: write current settings now");
15019                pw.println("    installs: details about install sessions");
15020                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15021                pw.println("    <package.name>: info about given package");
15022                return;
15023            } else if ("--checkin".equals(opt)) {
15024                checkin = true;
15025            } else if ("-f".equals(opt)) {
15026                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15027            } else {
15028                pw.println("Unknown argument: " + opt + "; use -h for help");
15029            }
15030        }
15031
15032        // Is the caller requesting to dump a particular piece of data?
15033        if (opti < args.length) {
15034            String cmd = args[opti];
15035            opti++;
15036            // Is this a package name?
15037            if ("android".equals(cmd) || cmd.contains(".")) {
15038                packageName = cmd;
15039                // When dumping a single package, we always dump all of its
15040                // filter information since the amount of data will be reasonable.
15041                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15042            } else if ("check-permission".equals(cmd)) {
15043                if (opti >= args.length) {
15044                    pw.println("Error: check-permission missing permission argument");
15045                    return;
15046                }
15047                String perm = args[opti];
15048                opti++;
15049                if (opti >= args.length) {
15050                    pw.println("Error: check-permission missing package argument");
15051                    return;
15052                }
15053                String pkg = args[opti];
15054                opti++;
15055                int user = UserHandle.getUserId(Binder.getCallingUid());
15056                if (opti < args.length) {
15057                    try {
15058                        user = Integer.parseInt(args[opti]);
15059                    } catch (NumberFormatException e) {
15060                        pw.println("Error: check-permission user argument is not a number: "
15061                                + args[opti]);
15062                        return;
15063                    }
15064                }
15065                pw.println(checkPermission(perm, pkg, user));
15066                return;
15067            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15068                dumpState.setDump(DumpState.DUMP_LIBS);
15069            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15070                dumpState.setDump(DumpState.DUMP_FEATURES);
15071            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15072                dumpState.setDump(DumpState.DUMP_RESOLVERS);
15073            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15074                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15075            } else if ("permission".equals(cmd)) {
15076                if (opti >= args.length) {
15077                    pw.println("Error: permission requires permission name");
15078                    return;
15079                }
15080                permissionNames = new ArraySet<>();
15081                while (opti < args.length) {
15082                    permissionNames.add(args[opti]);
15083                    opti++;
15084                }
15085                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15086                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15087            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15088                dumpState.setDump(DumpState.DUMP_PREFERRED);
15089            } else if ("preferred-xml".equals(cmd)) {
15090                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15091                if (opti < args.length && "--full".equals(args[opti])) {
15092                    fullPreferred = true;
15093                    opti++;
15094                }
15095            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15096                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15097            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15098                dumpState.setDump(DumpState.DUMP_PACKAGES);
15099            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15100                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15101            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15102                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15103            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15104                dumpState.setDump(DumpState.DUMP_MESSAGES);
15105            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15106                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15107            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15108                    || "intent-filter-verifiers".equals(cmd)) {
15109                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15110            } else if ("version".equals(cmd)) {
15111                dumpState.setDump(DumpState.DUMP_VERSION);
15112            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15113                dumpState.setDump(DumpState.DUMP_KEYSETS);
15114            } else if ("installs".equals(cmd)) {
15115                dumpState.setDump(DumpState.DUMP_INSTALLS);
15116            } else if ("write".equals(cmd)) {
15117                synchronized (mPackages) {
15118                    mSettings.writeLPr();
15119                    pw.println("Settings written.");
15120                    return;
15121                }
15122            }
15123        }
15124
15125        if (checkin) {
15126            pw.println("vers,1");
15127        }
15128
15129        // reader
15130        synchronized (mPackages) {
15131            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15132                if (!checkin) {
15133                    if (dumpState.onTitlePrinted())
15134                        pw.println();
15135                    pw.println("Database versions:");
15136                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15137                }
15138            }
15139
15140            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15141                if (!checkin) {
15142                    if (dumpState.onTitlePrinted())
15143                        pw.println();
15144                    pw.println("Verifiers:");
15145                    pw.print("  Required: ");
15146                    pw.print(mRequiredVerifierPackage);
15147                    pw.print(" (uid=");
15148                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15149                    pw.println(")");
15150                } else if (mRequiredVerifierPackage != null) {
15151                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15152                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15153                }
15154            }
15155
15156            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15157                    packageName == null) {
15158                if (mIntentFilterVerifierComponent != null) {
15159                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15160                    if (!checkin) {
15161                        if (dumpState.onTitlePrinted())
15162                            pw.println();
15163                        pw.println("Intent Filter Verifier:");
15164                        pw.print("  Using: ");
15165                        pw.print(verifierPackageName);
15166                        pw.print(" (uid=");
15167                        pw.print(getPackageUid(verifierPackageName, 0));
15168                        pw.println(")");
15169                    } else if (verifierPackageName != null) {
15170                        pw.print("ifv,"); pw.print(verifierPackageName);
15171                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15172                    }
15173                } else {
15174                    pw.println();
15175                    pw.println("No Intent Filter Verifier available!");
15176                }
15177            }
15178
15179            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15180                boolean printedHeader = false;
15181                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15182                while (it.hasNext()) {
15183                    String name = it.next();
15184                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15185                    if (!checkin) {
15186                        if (!printedHeader) {
15187                            if (dumpState.onTitlePrinted())
15188                                pw.println();
15189                            pw.println("Libraries:");
15190                            printedHeader = true;
15191                        }
15192                        pw.print("  ");
15193                    } else {
15194                        pw.print("lib,");
15195                    }
15196                    pw.print(name);
15197                    if (!checkin) {
15198                        pw.print(" -> ");
15199                    }
15200                    if (ent.path != null) {
15201                        if (!checkin) {
15202                            pw.print("(jar) ");
15203                            pw.print(ent.path);
15204                        } else {
15205                            pw.print(",jar,");
15206                            pw.print(ent.path);
15207                        }
15208                    } else {
15209                        if (!checkin) {
15210                            pw.print("(apk) ");
15211                            pw.print(ent.apk);
15212                        } else {
15213                            pw.print(",apk,");
15214                            pw.print(ent.apk);
15215                        }
15216                    }
15217                    pw.println();
15218                }
15219            }
15220
15221            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15222                if (dumpState.onTitlePrinted())
15223                    pw.println();
15224                if (!checkin) {
15225                    pw.println("Features:");
15226                }
15227                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15228                while (it.hasNext()) {
15229                    String name = it.next();
15230                    if (!checkin) {
15231                        pw.print("  ");
15232                    } else {
15233                        pw.print("feat,");
15234                    }
15235                    pw.println(name);
15236                }
15237            }
15238
15239            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
15240                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15241                        : "Activity Resolver Table:", "  ", packageName,
15242                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15243                    dumpState.setTitlePrinted(true);
15244                }
15245                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15246                        : "Receiver Resolver Table:", "  ", packageName,
15247                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15248                    dumpState.setTitlePrinted(true);
15249                }
15250                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15251                        : "Service Resolver Table:", "  ", packageName,
15252                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15253                    dumpState.setTitlePrinted(true);
15254                }
15255                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15256                        : "Provider Resolver Table:", "  ", packageName,
15257                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15258                    dumpState.setTitlePrinted(true);
15259                }
15260            }
15261
15262            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15263                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15264                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15265                    int user = mSettings.mPreferredActivities.keyAt(i);
15266                    if (pir.dump(pw,
15267                            dumpState.getTitlePrinted()
15268                                ? "\nPreferred Activities User " + user + ":"
15269                                : "Preferred Activities User " + user + ":", "  ",
15270                            packageName, true, false)) {
15271                        dumpState.setTitlePrinted(true);
15272                    }
15273                }
15274            }
15275
15276            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15277                pw.flush();
15278                FileOutputStream fout = new FileOutputStream(fd);
15279                BufferedOutputStream str = new BufferedOutputStream(fout);
15280                XmlSerializer serializer = new FastXmlSerializer();
15281                try {
15282                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15283                    serializer.startDocument(null, true);
15284                    serializer.setFeature(
15285                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15286                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15287                    serializer.endDocument();
15288                    serializer.flush();
15289                } catch (IllegalArgumentException e) {
15290                    pw.println("Failed writing: " + e);
15291                } catch (IllegalStateException e) {
15292                    pw.println("Failed writing: " + e);
15293                } catch (IOException e) {
15294                    pw.println("Failed writing: " + e);
15295                }
15296            }
15297
15298            if (!checkin
15299                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15300                    && packageName == null) {
15301                pw.println();
15302                int count = mSettings.mPackages.size();
15303                if (count == 0) {
15304                    pw.println("No applications!");
15305                    pw.println();
15306                } else {
15307                    final String prefix = "  ";
15308                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15309                    if (allPackageSettings.size() == 0) {
15310                        pw.println("No domain preferred apps!");
15311                        pw.println();
15312                    } else {
15313                        pw.println("App verification status:");
15314                        pw.println();
15315                        count = 0;
15316                        for (PackageSetting ps : allPackageSettings) {
15317                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15318                            if (ivi == null || ivi.getPackageName() == null) continue;
15319                            pw.println(prefix + "Package: " + ivi.getPackageName());
15320                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15321                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15322                            pw.println();
15323                            count++;
15324                        }
15325                        if (count == 0) {
15326                            pw.println(prefix + "No app verification established.");
15327                            pw.println();
15328                        }
15329                        for (int userId : sUserManager.getUserIds()) {
15330                            pw.println("App linkages for user " + userId + ":");
15331                            pw.println();
15332                            count = 0;
15333                            for (PackageSetting ps : allPackageSettings) {
15334                                final long status = ps.getDomainVerificationStatusForUser(userId);
15335                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15336                                    continue;
15337                                }
15338                                pw.println(prefix + "Package: " + ps.name);
15339                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15340                                String statusStr = IntentFilterVerificationInfo.
15341                                        getStatusStringFromValue(status);
15342                                pw.println(prefix + "Status:  " + statusStr);
15343                                pw.println();
15344                                count++;
15345                            }
15346                            if (count == 0) {
15347                                pw.println(prefix + "No configured app linkages.");
15348                                pw.println();
15349                            }
15350                        }
15351                    }
15352                }
15353            }
15354
15355            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15356                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15357                if (packageName == null && permissionNames == null) {
15358                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15359                        if (iperm == 0) {
15360                            if (dumpState.onTitlePrinted())
15361                                pw.println();
15362                            pw.println("AppOp Permissions:");
15363                        }
15364                        pw.print("  AppOp Permission ");
15365                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15366                        pw.println(":");
15367                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15368                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15369                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15370                        }
15371                    }
15372                }
15373            }
15374
15375            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15376                boolean printedSomething = false;
15377                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15378                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15379                        continue;
15380                    }
15381                    if (!printedSomething) {
15382                        if (dumpState.onTitlePrinted())
15383                            pw.println();
15384                        pw.println("Registered ContentProviders:");
15385                        printedSomething = true;
15386                    }
15387                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15388                    pw.print("    "); pw.println(p.toString());
15389                }
15390                printedSomething = false;
15391                for (Map.Entry<String, PackageParser.Provider> entry :
15392                        mProvidersByAuthority.entrySet()) {
15393                    PackageParser.Provider p = entry.getValue();
15394                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15395                        continue;
15396                    }
15397                    if (!printedSomething) {
15398                        if (dumpState.onTitlePrinted())
15399                            pw.println();
15400                        pw.println("ContentProvider Authorities:");
15401                        printedSomething = true;
15402                    }
15403                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15404                    pw.print("    "); pw.println(p.toString());
15405                    if (p.info != null && p.info.applicationInfo != null) {
15406                        final String appInfo = p.info.applicationInfo.toString();
15407                        pw.print("      applicationInfo="); pw.println(appInfo);
15408                    }
15409                }
15410            }
15411
15412            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15413                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15414            }
15415
15416            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15417                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15418            }
15419
15420            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15421                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15422            }
15423
15424            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15425                // XXX should handle packageName != null by dumping only install data that
15426                // the given package is involved with.
15427                if (dumpState.onTitlePrinted()) pw.println();
15428                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15429            }
15430
15431            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15432                if (dumpState.onTitlePrinted()) pw.println();
15433                mSettings.dumpReadMessagesLPr(pw, dumpState);
15434
15435                pw.println();
15436                pw.println("Package warning messages:");
15437                BufferedReader in = null;
15438                String line = null;
15439                try {
15440                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15441                    while ((line = in.readLine()) != null) {
15442                        if (line.contains("ignored: updated version")) continue;
15443                        pw.println(line);
15444                    }
15445                } catch (IOException ignored) {
15446                } finally {
15447                    IoUtils.closeQuietly(in);
15448                }
15449            }
15450
15451            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15452                BufferedReader in = null;
15453                String line = null;
15454                try {
15455                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15456                    while ((line = in.readLine()) != null) {
15457                        if (line.contains("ignored: updated version")) continue;
15458                        pw.print("msg,");
15459                        pw.println(line);
15460                    }
15461                } catch (IOException ignored) {
15462                } finally {
15463                    IoUtils.closeQuietly(in);
15464                }
15465            }
15466        }
15467    }
15468
15469    private String dumpDomainString(String packageName) {
15470        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15471        List<IntentFilter> filters = getAllIntentFilters(packageName);
15472
15473        ArraySet<String> result = new ArraySet<>();
15474        if (iviList.size() > 0) {
15475            for (IntentFilterVerificationInfo ivi : iviList) {
15476                for (String host : ivi.getDomains()) {
15477                    result.add(host);
15478                }
15479            }
15480        }
15481        if (filters != null && filters.size() > 0) {
15482            for (IntentFilter filter : filters) {
15483                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15484                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15485                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15486                    result.addAll(filter.getHostsList());
15487                }
15488            }
15489        }
15490
15491        StringBuilder sb = new StringBuilder(result.size() * 16);
15492        for (String domain : result) {
15493            if (sb.length() > 0) sb.append(" ");
15494            sb.append(domain);
15495        }
15496        return sb.toString();
15497    }
15498
15499    // ------- apps on sdcard specific code -------
15500    static final boolean DEBUG_SD_INSTALL = false;
15501
15502    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15503
15504    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15505
15506    private boolean mMediaMounted = false;
15507
15508    static String getEncryptKey() {
15509        try {
15510            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15511                    SD_ENCRYPTION_KEYSTORE_NAME);
15512            if (sdEncKey == null) {
15513                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15514                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15515                if (sdEncKey == null) {
15516                    Slog.e(TAG, "Failed to create encryption keys");
15517                    return null;
15518                }
15519            }
15520            return sdEncKey;
15521        } catch (NoSuchAlgorithmException nsae) {
15522            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15523            return null;
15524        } catch (IOException ioe) {
15525            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15526            return null;
15527        }
15528    }
15529
15530    /*
15531     * Update media status on PackageManager.
15532     */
15533    @Override
15534    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15535        int callingUid = Binder.getCallingUid();
15536        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15537            throw new SecurityException("Media status can only be updated by the system");
15538        }
15539        // reader; this apparently protects mMediaMounted, but should probably
15540        // be a different lock in that case.
15541        synchronized (mPackages) {
15542            Log.i(TAG, "Updating external media status from "
15543                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15544                    + (mediaStatus ? "mounted" : "unmounted"));
15545            if (DEBUG_SD_INSTALL)
15546                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15547                        + ", mMediaMounted=" + mMediaMounted);
15548            if (mediaStatus == mMediaMounted) {
15549                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15550                        : 0, -1);
15551                mHandler.sendMessage(msg);
15552                return;
15553            }
15554            mMediaMounted = mediaStatus;
15555        }
15556        // Queue up an async operation since the package installation may take a
15557        // little while.
15558        mHandler.post(new Runnable() {
15559            public void run() {
15560                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15561            }
15562        });
15563    }
15564
15565    /**
15566     * Called by MountService when the initial ASECs to scan are available.
15567     * Should block until all the ASEC containers are finished being scanned.
15568     */
15569    public void scanAvailableAsecs() {
15570        updateExternalMediaStatusInner(true, false, false);
15571        if (mShouldRestoreconData) {
15572            SELinuxMMAC.setRestoreconDone();
15573            mShouldRestoreconData = false;
15574        }
15575    }
15576
15577    /*
15578     * Collect information of applications on external media, map them against
15579     * existing containers and update information based on current mount status.
15580     * Please note that we always have to report status if reportStatus has been
15581     * set to true especially when unloading packages.
15582     */
15583    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15584            boolean externalStorage) {
15585        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15586        int[] uidArr = EmptyArray.INT;
15587
15588        final String[] list = PackageHelper.getSecureContainerList();
15589        if (ArrayUtils.isEmpty(list)) {
15590            Log.i(TAG, "No secure containers found");
15591        } else {
15592            // Process list of secure containers and categorize them
15593            // as active or stale based on their package internal state.
15594
15595            // reader
15596            synchronized (mPackages) {
15597                for (String cid : list) {
15598                    // Leave stages untouched for now; installer service owns them
15599                    if (PackageInstallerService.isStageName(cid)) continue;
15600
15601                    if (DEBUG_SD_INSTALL)
15602                        Log.i(TAG, "Processing container " + cid);
15603                    String pkgName = getAsecPackageName(cid);
15604                    if (pkgName == null) {
15605                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15606                        continue;
15607                    }
15608                    if (DEBUG_SD_INSTALL)
15609                        Log.i(TAG, "Looking for pkg : " + pkgName);
15610
15611                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15612                    if (ps == null) {
15613                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15614                        continue;
15615                    }
15616
15617                    /*
15618                     * Skip packages that are not external if we're unmounting
15619                     * external storage.
15620                     */
15621                    if (externalStorage && !isMounted && !isExternal(ps)) {
15622                        continue;
15623                    }
15624
15625                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15626                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15627                    // The package status is changed only if the code path
15628                    // matches between settings and the container id.
15629                    if (ps.codePathString != null
15630                            && ps.codePathString.startsWith(args.getCodePath())) {
15631                        if (DEBUG_SD_INSTALL) {
15632                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15633                                    + " at code path: " + ps.codePathString);
15634                        }
15635
15636                        // We do have a valid package installed on sdcard
15637                        processCids.put(args, ps.codePathString);
15638                        final int uid = ps.appId;
15639                        if (uid != -1) {
15640                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15641                        }
15642                    } else {
15643                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15644                                + ps.codePathString);
15645                    }
15646                }
15647            }
15648
15649            Arrays.sort(uidArr);
15650        }
15651
15652        // Process packages with valid entries.
15653        if (isMounted) {
15654            if (DEBUG_SD_INSTALL)
15655                Log.i(TAG, "Loading packages");
15656            loadMediaPackages(processCids, uidArr);
15657            startCleaningPackages();
15658            mInstallerService.onSecureContainersAvailable();
15659        } else {
15660            if (DEBUG_SD_INSTALL)
15661                Log.i(TAG, "Unloading packages");
15662            unloadMediaPackages(processCids, uidArr, reportStatus);
15663        }
15664    }
15665
15666    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15667            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15668        final int size = infos.size();
15669        final String[] packageNames = new String[size];
15670        final int[] packageUids = new int[size];
15671        for (int i = 0; i < size; i++) {
15672            final ApplicationInfo info = infos.get(i);
15673            packageNames[i] = info.packageName;
15674            packageUids[i] = info.uid;
15675        }
15676        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15677                finishedReceiver);
15678    }
15679
15680    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15681            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15682        sendResourcesChangedBroadcast(mediaStatus, replacing,
15683                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15684    }
15685
15686    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15687            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15688        int size = pkgList.length;
15689        if (size > 0) {
15690            // Send broadcasts here
15691            Bundle extras = new Bundle();
15692            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15693            if (uidArr != null) {
15694                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15695            }
15696            if (replacing) {
15697                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15698            }
15699            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15700                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15701            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15702        }
15703    }
15704
15705   /*
15706     * Look at potentially valid container ids from processCids If package
15707     * information doesn't match the one on record or package scanning fails,
15708     * the cid is added to list of removeCids. We currently don't delete stale
15709     * containers.
15710     */
15711    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15712        ArrayList<String> pkgList = new ArrayList<String>();
15713        Set<AsecInstallArgs> keys = processCids.keySet();
15714
15715        for (AsecInstallArgs args : keys) {
15716            String codePath = processCids.get(args);
15717            if (DEBUG_SD_INSTALL)
15718                Log.i(TAG, "Loading container : " + args.cid);
15719            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15720            try {
15721                // Make sure there are no container errors first.
15722                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15723                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15724                            + " when installing from sdcard");
15725                    continue;
15726                }
15727                // Check code path here.
15728                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15729                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15730                            + " does not match one in settings " + codePath);
15731                    continue;
15732                }
15733                // Parse package
15734                int parseFlags = mDefParseFlags;
15735                if (args.isExternalAsec()) {
15736                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15737                }
15738                if (args.isFwdLocked()) {
15739                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15740                }
15741
15742                synchronized (mInstallLock) {
15743                    PackageParser.Package pkg = null;
15744                    try {
15745                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
15746                    } catch (PackageManagerException e) {
15747                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15748                    }
15749                    // Scan the package
15750                    if (pkg != null) {
15751                        /*
15752                         * TODO why is the lock being held? doPostInstall is
15753                         * called in other places without the lock. This needs
15754                         * to be straightened out.
15755                         */
15756                        // writer
15757                        synchronized (mPackages) {
15758                            retCode = PackageManager.INSTALL_SUCCEEDED;
15759                            pkgList.add(pkg.packageName);
15760                            // Post process args
15761                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15762                                    pkg.applicationInfo.uid);
15763                        }
15764                    } else {
15765                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15766                    }
15767                }
15768
15769            } finally {
15770                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15771                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15772                }
15773            }
15774        }
15775        // writer
15776        synchronized (mPackages) {
15777            // If the platform SDK has changed since the last time we booted,
15778            // we need to re-grant app permission to catch any new ones that
15779            // appear. This is really a hack, and means that apps can in some
15780            // cases get permissions that the user didn't initially explicitly
15781            // allow... it would be nice to have some better way to handle
15782            // this situation.
15783            final VersionInfo ver = mSettings.getExternalVersion();
15784
15785            int updateFlags = UPDATE_PERMISSIONS_ALL;
15786            if (ver.sdkVersion != mSdkVersion) {
15787                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15788                        + mSdkVersion + "; regranting permissions for external");
15789                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15790            }
15791            updatePermissionsLPw(null, null, updateFlags);
15792
15793            // Yay, everything is now upgraded
15794            ver.forceCurrent();
15795
15796            // can downgrade to reader
15797            // Persist settings
15798            mSettings.writeLPr();
15799        }
15800        // Send a broadcast to let everyone know we are done processing
15801        if (pkgList.size() > 0) {
15802            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15803        }
15804    }
15805
15806   /*
15807     * Utility method to unload a list of specified containers
15808     */
15809    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15810        // Just unmount all valid containers.
15811        for (AsecInstallArgs arg : cidArgs) {
15812            synchronized (mInstallLock) {
15813                arg.doPostDeleteLI(false);
15814           }
15815       }
15816   }
15817
15818    /*
15819     * Unload packages mounted on external media. This involves deleting package
15820     * data from internal structures, sending broadcasts about diabled packages,
15821     * gc'ing to free up references, unmounting all secure containers
15822     * corresponding to packages on external media, and posting a
15823     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15824     * that we always have to post this message if status has been requested no
15825     * matter what.
15826     */
15827    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15828            final boolean reportStatus) {
15829        if (DEBUG_SD_INSTALL)
15830            Log.i(TAG, "unloading media packages");
15831        ArrayList<String> pkgList = new ArrayList<String>();
15832        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15833        final Set<AsecInstallArgs> keys = processCids.keySet();
15834        for (AsecInstallArgs args : keys) {
15835            String pkgName = args.getPackageName();
15836            if (DEBUG_SD_INSTALL)
15837                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15838            // Delete package internally
15839            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15840            synchronized (mInstallLock) {
15841                boolean res = deletePackageLI(pkgName, null, false, null, null,
15842                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15843                if (res) {
15844                    pkgList.add(pkgName);
15845                } else {
15846                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15847                    failedList.add(args);
15848                }
15849            }
15850        }
15851
15852        // reader
15853        synchronized (mPackages) {
15854            // We didn't update the settings after removing each package;
15855            // write them now for all packages.
15856            mSettings.writeLPr();
15857        }
15858
15859        // We have to absolutely send UPDATED_MEDIA_STATUS only
15860        // after confirming that all the receivers processed the ordered
15861        // broadcast when packages get disabled, force a gc to clean things up.
15862        // and unload all the containers.
15863        if (pkgList.size() > 0) {
15864            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15865                    new IIntentReceiver.Stub() {
15866                public void performReceive(Intent intent, int resultCode, String data,
15867                        Bundle extras, boolean ordered, boolean sticky,
15868                        int sendingUser) throws RemoteException {
15869                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15870                            reportStatus ? 1 : 0, 1, keys);
15871                    mHandler.sendMessage(msg);
15872                }
15873            });
15874        } else {
15875            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15876                    keys);
15877            mHandler.sendMessage(msg);
15878        }
15879    }
15880
15881    private void loadPrivatePackages(final VolumeInfo vol) {
15882        mHandler.post(new Runnable() {
15883            @Override
15884            public void run() {
15885                loadPrivatePackagesInner(vol);
15886            }
15887        });
15888    }
15889
15890    private void loadPrivatePackagesInner(VolumeInfo vol) {
15891        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15892        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15893
15894        final VersionInfo ver;
15895        final List<PackageSetting> packages;
15896        synchronized (mPackages) {
15897            ver = mSettings.findOrCreateVersion(vol.fsUuid);
15898            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15899        }
15900
15901        for (PackageSetting ps : packages) {
15902            synchronized (mInstallLock) {
15903                final PackageParser.Package pkg;
15904                try {
15905                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15906                    loaded.add(pkg.applicationInfo);
15907                } catch (PackageManagerException e) {
15908                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15909                }
15910
15911                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15912                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15913                }
15914            }
15915        }
15916
15917        synchronized (mPackages) {
15918            int updateFlags = UPDATE_PERMISSIONS_ALL;
15919            if (ver.sdkVersion != mSdkVersion) {
15920                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15921                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15922                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15923            }
15924            updatePermissionsLPw(null, null, updateFlags);
15925
15926            // Yay, everything is now upgraded
15927            ver.forceCurrent();
15928
15929            mSettings.writeLPr();
15930        }
15931
15932        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15933        sendResourcesChangedBroadcast(true, false, loaded, null);
15934    }
15935
15936    private void unloadPrivatePackages(final VolumeInfo vol) {
15937        mHandler.post(new Runnable() {
15938            @Override
15939            public void run() {
15940                unloadPrivatePackagesInner(vol);
15941            }
15942        });
15943    }
15944
15945    private void unloadPrivatePackagesInner(VolumeInfo vol) {
15946        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15947        synchronized (mInstallLock) {
15948        synchronized (mPackages) {
15949            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15950            for (PackageSetting ps : packages) {
15951                if (ps.pkg == null) continue;
15952
15953                final ApplicationInfo info = ps.pkg.applicationInfo;
15954                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15955                if (deletePackageLI(ps.name, null, false, null, null,
15956                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15957                    unloaded.add(info);
15958                } else {
15959                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15960                }
15961            }
15962
15963            mSettings.writeLPr();
15964        }
15965        }
15966
15967        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15968        sendResourcesChangedBroadcast(false, false, unloaded, null);
15969    }
15970
15971    /**
15972     * Examine all users present on given mounted volume, and destroy data
15973     * belonging to users that are no longer valid, or whose user ID has been
15974     * recycled.
15975     */
15976    private void reconcileUsers(String volumeUuid) {
15977        final File[] files = FileUtils
15978                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15979        for (File file : files) {
15980            if (!file.isDirectory()) continue;
15981
15982            final int userId;
15983            final UserInfo info;
15984            try {
15985                userId = Integer.parseInt(file.getName());
15986                info = sUserManager.getUserInfo(userId);
15987            } catch (NumberFormatException e) {
15988                Slog.w(TAG, "Invalid user directory " + file);
15989                continue;
15990            }
15991
15992            boolean destroyUser = false;
15993            if (info == null) {
15994                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15995                        + " because no matching user was found");
15996                destroyUser = true;
15997            } else {
15998                try {
15999                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16000                } catch (IOException e) {
16001                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16002                            + " because we failed to enforce serial number: " + e);
16003                    destroyUser = true;
16004                }
16005            }
16006
16007            if (destroyUser) {
16008                synchronized (mInstallLock) {
16009                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16010                }
16011            }
16012        }
16013
16014        final UserManager um = mContext.getSystemService(UserManager.class);
16015        for (UserInfo user : um.getUsers()) {
16016            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16017            if (userDir.exists()) continue;
16018
16019            try {
16020                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
16021                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16022            } catch (IOException e) {
16023                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16024            }
16025        }
16026    }
16027
16028    /**
16029     * Examine all apps present on given mounted volume, and destroy apps that
16030     * aren't expected, either due to uninstallation or reinstallation on
16031     * another volume.
16032     */
16033    private void reconcileApps(String volumeUuid) {
16034        final File[] files = FileUtils
16035                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16036        for (File file : files) {
16037            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16038                    && !PackageInstallerService.isStageName(file.getName());
16039            if (!isPackage) {
16040                // Ignore entries which are not packages
16041                continue;
16042            }
16043
16044            boolean destroyApp = false;
16045            String packageName = null;
16046            try {
16047                final PackageLite pkg = PackageParser.parsePackageLite(file,
16048                        PackageParser.PARSE_MUST_BE_APK);
16049                packageName = pkg.packageName;
16050
16051                synchronized (mPackages) {
16052                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16053                    if (ps == null) {
16054                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16055                                + volumeUuid + " because we found no install record");
16056                        destroyApp = true;
16057                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16058                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16059                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16060                        destroyApp = true;
16061                    }
16062                }
16063
16064            } catch (PackageParserException e) {
16065                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16066                destroyApp = true;
16067            }
16068
16069            if (destroyApp) {
16070                synchronized (mInstallLock) {
16071                    if (packageName != null) {
16072                        removeDataDirsLI(volumeUuid, packageName);
16073                    }
16074                    if (file.isDirectory()) {
16075                        mInstaller.rmPackageDir(file.getAbsolutePath());
16076                    } else {
16077                        file.delete();
16078                    }
16079                }
16080            }
16081        }
16082    }
16083
16084    private void unfreezePackage(String packageName) {
16085        synchronized (mPackages) {
16086            final PackageSetting ps = mSettings.mPackages.get(packageName);
16087            if (ps != null) {
16088                ps.frozen = false;
16089            }
16090        }
16091    }
16092
16093    @Override
16094    public int movePackage(final String packageName, final String volumeUuid) {
16095        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16096
16097        final int moveId = mNextMoveId.getAndIncrement();
16098        try {
16099            movePackageInternal(packageName, volumeUuid, moveId);
16100        } catch (PackageManagerException e) {
16101            Slog.w(TAG, "Failed to move " + packageName, e);
16102            mMoveCallbacks.notifyStatusChanged(moveId,
16103                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16104        }
16105        return moveId;
16106    }
16107
16108    private void movePackageInternal(final String packageName, final String volumeUuid,
16109            final int moveId) throws PackageManagerException {
16110        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16111        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16112        final PackageManager pm = mContext.getPackageManager();
16113
16114        final boolean currentAsec;
16115        final String currentVolumeUuid;
16116        final File codeFile;
16117        final String installerPackageName;
16118        final String packageAbiOverride;
16119        final int appId;
16120        final String seinfo;
16121        final String label;
16122
16123        // reader
16124        synchronized (mPackages) {
16125            final PackageParser.Package pkg = mPackages.get(packageName);
16126            final PackageSetting ps = mSettings.mPackages.get(packageName);
16127            if (pkg == null || ps == null) {
16128                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16129            }
16130
16131            if (pkg.applicationInfo.isSystemApp()) {
16132                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16133                        "Cannot move system application");
16134            }
16135
16136            if (pkg.applicationInfo.isExternalAsec()) {
16137                currentAsec = true;
16138                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16139            } else if (pkg.applicationInfo.isForwardLocked()) {
16140                currentAsec = true;
16141                currentVolumeUuid = "forward_locked";
16142            } else {
16143                currentAsec = false;
16144                currentVolumeUuid = ps.volumeUuid;
16145
16146                final File probe = new File(pkg.codePath);
16147                final File probeOat = new File(probe, "oat");
16148                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16149                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16150                            "Move only supported for modern cluster style installs");
16151                }
16152            }
16153
16154            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16155                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16156                        "Package already moved to " + volumeUuid);
16157            }
16158
16159            if (ps.frozen) {
16160                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16161                        "Failed to move already frozen package");
16162            }
16163            ps.frozen = true;
16164
16165            codeFile = new File(pkg.codePath);
16166            installerPackageName = ps.installerPackageName;
16167            packageAbiOverride = ps.cpuAbiOverrideString;
16168            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16169            seinfo = pkg.applicationInfo.seinfo;
16170            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16171        }
16172
16173        // Now that we're guarded by frozen state, kill app during move
16174        final long token = Binder.clearCallingIdentity();
16175        try {
16176            killApplication(packageName, appId, "move pkg");
16177        } finally {
16178            Binder.restoreCallingIdentity(token);
16179        }
16180
16181        final Bundle extras = new Bundle();
16182        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16183        extras.putString(Intent.EXTRA_TITLE, label);
16184        mMoveCallbacks.notifyCreated(moveId, extras);
16185
16186        int installFlags;
16187        final boolean moveCompleteApp;
16188        final File measurePath;
16189
16190        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16191            installFlags = INSTALL_INTERNAL;
16192            moveCompleteApp = !currentAsec;
16193            measurePath = Environment.getDataAppDirectory(volumeUuid);
16194        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16195            installFlags = INSTALL_EXTERNAL;
16196            moveCompleteApp = false;
16197            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16198        } else {
16199            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16200            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16201                    || !volume.isMountedWritable()) {
16202                unfreezePackage(packageName);
16203                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16204                        "Move location not mounted private volume");
16205            }
16206
16207            Preconditions.checkState(!currentAsec);
16208
16209            installFlags = INSTALL_INTERNAL;
16210            moveCompleteApp = true;
16211            measurePath = Environment.getDataAppDirectory(volumeUuid);
16212        }
16213
16214        final PackageStats stats = new PackageStats(null, -1);
16215        synchronized (mInstaller) {
16216            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16217                unfreezePackage(packageName);
16218                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16219                        "Failed to measure package size");
16220            }
16221        }
16222
16223        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16224                + stats.dataSize);
16225
16226        final long startFreeBytes = measurePath.getFreeSpace();
16227        final long sizeBytes;
16228        if (moveCompleteApp) {
16229            sizeBytes = stats.codeSize + stats.dataSize;
16230        } else {
16231            sizeBytes = stats.codeSize;
16232        }
16233
16234        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16235            unfreezePackage(packageName);
16236            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16237                    "Not enough free space to move");
16238        }
16239
16240        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16241
16242        final CountDownLatch installedLatch = new CountDownLatch(1);
16243        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16244            @Override
16245            public void onUserActionRequired(Intent intent) throws RemoteException {
16246                throw new IllegalStateException();
16247            }
16248
16249            @Override
16250            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16251                    Bundle extras) throws RemoteException {
16252                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16253                        + PackageManager.installStatusToString(returnCode, msg));
16254
16255                installedLatch.countDown();
16256
16257                // Regardless of success or failure of the move operation,
16258                // always unfreeze the package
16259                unfreezePackage(packageName);
16260
16261                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16262                switch (status) {
16263                    case PackageInstaller.STATUS_SUCCESS:
16264                        mMoveCallbacks.notifyStatusChanged(moveId,
16265                                PackageManager.MOVE_SUCCEEDED);
16266                        break;
16267                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16268                        mMoveCallbacks.notifyStatusChanged(moveId,
16269                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16270                        break;
16271                    default:
16272                        mMoveCallbacks.notifyStatusChanged(moveId,
16273                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16274                        break;
16275                }
16276            }
16277        };
16278
16279        final MoveInfo move;
16280        if (moveCompleteApp) {
16281            // Kick off a thread to report progress estimates
16282            new Thread() {
16283                @Override
16284                public void run() {
16285                    while (true) {
16286                        try {
16287                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16288                                break;
16289                            }
16290                        } catch (InterruptedException ignored) {
16291                        }
16292
16293                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16294                        final int progress = 10 + (int) MathUtils.constrain(
16295                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16296                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16297                    }
16298                }
16299            }.start();
16300
16301            final String dataAppName = codeFile.getName();
16302            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16303                    dataAppName, appId, seinfo);
16304        } else {
16305            move = null;
16306        }
16307
16308        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16309
16310        final Message msg = mHandler.obtainMessage(INIT_COPY);
16311        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16312        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16313                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16314        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16315        msg.obj = params;
16316
16317        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16318                System.identityHashCode(msg.obj));
16319        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16320                System.identityHashCode(msg.obj));
16321
16322        mHandler.sendMessage(msg);
16323    }
16324
16325    @Override
16326    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16327        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16328
16329        final int realMoveId = mNextMoveId.getAndIncrement();
16330        final Bundle extras = new Bundle();
16331        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16332        mMoveCallbacks.notifyCreated(realMoveId, extras);
16333
16334        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16335            @Override
16336            public void onCreated(int moveId, Bundle extras) {
16337                // Ignored
16338            }
16339
16340            @Override
16341            public void onStatusChanged(int moveId, int status, long estMillis) {
16342                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16343            }
16344        };
16345
16346        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16347        storage.setPrimaryStorageUuid(volumeUuid, callback);
16348        return realMoveId;
16349    }
16350
16351    @Override
16352    public int getMoveStatus(int moveId) {
16353        mContext.enforceCallingOrSelfPermission(
16354                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16355        return mMoveCallbacks.mLastStatus.get(moveId);
16356    }
16357
16358    @Override
16359    public void registerMoveCallback(IPackageMoveObserver callback) {
16360        mContext.enforceCallingOrSelfPermission(
16361                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16362        mMoveCallbacks.register(callback);
16363    }
16364
16365    @Override
16366    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16367        mContext.enforceCallingOrSelfPermission(
16368                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16369        mMoveCallbacks.unregister(callback);
16370    }
16371
16372    @Override
16373    public boolean setInstallLocation(int loc) {
16374        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16375                null);
16376        if (getInstallLocation() == loc) {
16377            return true;
16378        }
16379        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16380                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16381            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16382                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16383            return true;
16384        }
16385        return false;
16386   }
16387
16388    @Override
16389    public int getInstallLocation() {
16390        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16391                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16392                PackageHelper.APP_INSTALL_AUTO);
16393    }
16394
16395    /** Called by UserManagerService */
16396    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16397        mDirtyUsers.remove(userHandle);
16398        mSettings.removeUserLPw(userHandle);
16399        mPendingBroadcasts.remove(userHandle);
16400        if (mInstaller != null) {
16401            // Technically, we shouldn't be doing this with the package lock
16402            // held.  However, this is very rare, and there is already so much
16403            // other disk I/O going on, that we'll let it slide for now.
16404            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16405            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16406                final String volumeUuid = vol.getFsUuid();
16407                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16408                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16409            }
16410        }
16411        mUserNeedsBadging.delete(userHandle);
16412        removeUnusedPackagesLILPw(userManager, userHandle);
16413    }
16414
16415    /**
16416     * We're removing userHandle and would like to remove any downloaded packages
16417     * that are no longer in use by any other user.
16418     * @param userHandle the user being removed
16419     */
16420    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16421        final boolean DEBUG_CLEAN_APKS = false;
16422        int [] users = userManager.getUserIdsLPr();
16423        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16424        while (psit.hasNext()) {
16425            PackageSetting ps = psit.next();
16426            if (ps.pkg == null) {
16427                continue;
16428            }
16429            final String packageName = ps.pkg.packageName;
16430            // Skip over if system app
16431            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16432                continue;
16433            }
16434            if (DEBUG_CLEAN_APKS) {
16435                Slog.i(TAG, "Checking package " + packageName);
16436            }
16437            boolean keep = false;
16438            for (int i = 0; i < users.length; i++) {
16439                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16440                    keep = true;
16441                    if (DEBUG_CLEAN_APKS) {
16442                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16443                                + users[i]);
16444                    }
16445                    break;
16446                }
16447            }
16448            if (!keep) {
16449                if (DEBUG_CLEAN_APKS) {
16450                    Slog.i(TAG, "  Removing package " + packageName);
16451                }
16452                mHandler.post(new Runnable() {
16453                    public void run() {
16454                        deletePackageX(packageName, userHandle, 0);
16455                    } //end run
16456                });
16457            }
16458        }
16459    }
16460
16461    /** Called by UserManagerService */
16462    void createNewUserLILPw(int userHandle) {
16463        if (mInstaller != null) {
16464            mInstaller.createUserConfig(userHandle);
16465            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16466            applyFactoryDefaultBrowserLPw(userHandle);
16467            primeDomainVerificationsLPw(userHandle);
16468        }
16469    }
16470
16471    void newUserCreated(final int userHandle) {
16472        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16473    }
16474
16475    @Override
16476    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16477        mContext.enforceCallingOrSelfPermission(
16478                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16479                "Only package verification agents can read the verifier device identity");
16480
16481        synchronized (mPackages) {
16482            return mSettings.getVerifierDeviceIdentityLPw();
16483        }
16484    }
16485
16486    @Override
16487    public void setPermissionEnforced(String permission, boolean enforced) {
16488        // TODO: Now that we no longer change GID for storage, this should to away.
16489        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16490                "setPermissionEnforced");
16491        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16492            synchronized (mPackages) {
16493                if (mSettings.mReadExternalStorageEnforced == null
16494                        || mSettings.mReadExternalStorageEnforced != enforced) {
16495                    mSettings.mReadExternalStorageEnforced = enforced;
16496                    mSettings.writeLPr();
16497                }
16498            }
16499            // kill any non-foreground processes so we restart them and
16500            // grant/revoke the GID.
16501            final IActivityManager am = ActivityManagerNative.getDefault();
16502            if (am != null) {
16503                final long token = Binder.clearCallingIdentity();
16504                try {
16505                    am.killProcessesBelowForeground("setPermissionEnforcement");
16506                } catch (RemoteException e) {
16507                } finally {
16508                    Binder.restoreCallingIdentity(token);
16509                }
16510            }
16511        } else {
16512            throw new IllegalArgumentException("No selective enforcement for " + permission);
16513        }
16514    }
16515
16516    @Override
16517    @Deprecated
16518    public boolean isPermissionEnforced(String permission) {
16519        return true;
16520    }
16521
16522    @Override
16523    public boolean isStorageLow() {
16524        final long token = Binder.clearCallingIdentity();
16525        try {
16526            final DeviceStorageMonitorInternal
16527                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16528            if (dsm != null) {
16529                return dsm.isMemoryLow();
16530            } else {
16531                return false;
16532            }
16533        } finally {
16534            Binder.restoreCallingIdentity(token);
16535        }
16536    }
16537
16538    @Override
16539    public IPackageInstaller getPackageInstaller() {
16540        return mInstallerService;
16541    }
16542
16543    private boolean userNeedsBadging(int userId) {
16544        int index = mUserNeedsBadging.indexOfKey(userId);
16545        if (index < 0) {
16546            final UserInfo userInfo;
16547            final long token = Binder.clearCallingIdentity();
16548            try {
16549                userInfo = sUserManager.getUserInfo(userId);
16550            } finally {
16551                Binder.restoreCallingIdentity(token);
16552            }
16553            final boolean b;
16554            if (userInfo != null && userInfo.isManagedProfile()) {
16555                b = true;
16556            } else {
16557                b = false;
16558            }
16559            mUserNeedsBadging.put(userId, b);
16560            return b;
16561        }
16562        return mUserNeedsBadging.valueAt(index);
16563    }
16564
16565    @Override
16566    public KeySet getKeySetByAlias(String packageName, String alias) {
16567        if (packageName == null || alias == null) {
16568            return null;
16569        }
16570        synchronized(mPackages) {
16571            final PackageParser.Package pkg = mPackages.get(packageName);
16572            if (pkg == null) {
16573                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16574                throw new IllegalArgumentException("Unknown package: " + packageName);
16575            }
16576            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16577            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16578        }
16579    }
16580
16581    @Override
16582    public KeySet getSigningKeySet(String packageName) {
16583        if (packageName == null) {
16584            return null;
16585        }
16586        synchronized(mPackages) {
16587            final PackageParser.Package pkg = mPackages.get(packageName);
16588            if (pkg == null) {
16589                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16590                throw new IllegalArgumentException("Unknown package: " + packageName);
16591            }
16592            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16593                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16594                throw new SecurityException("May not access signing KeySet of other apps.");
16595            }
16596            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16597            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16598        }
16599    }
16600
16601    @Override
16602    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16603        if (packageName == null || ks == null) {
16604            return false;
16605        }
16606        synchronized(mPackages) {
16607            final PackageParser.Package pkg = mPackages.get(packageName);
16608            if (pkg == null) {
16609                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16610                throw new IllegalArgumentException("Unknown package: " + packageName);
16611            }
16612            IBinder ksh = ks.getToken();
16613            if (ksh instanceof KeySetHandle) {
16614                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16615                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16616            }
16617            return false;
16618        }
16619    }
16620
16621    @Override
16622    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16623        if (packageName == null || ks == null) {
16624            return false;
16625        }
16626        synchronized(mPackages) {
16627            final PackageParser.Package pkg = mPackages.get(packageName);
16628            if (pkg == null) {
16629                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16630                throw new IllegalArgumentException("Unknown package: " + packageName);
16631            }
16632            IBinder ksh = ks.getToken();
16633            if (ksh instanceof KeySetHandle) {
16634                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16635                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16636            }
16637            return false;
16638        }
16639    }
16640
16641    public void getUsageStatsIfNoPackageUsageInfo() {
16642        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16643            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16644            if (usm == null) {
16645                throw new IllegalStateException("UsageStatsManager must be initialized");
16646            }
16647            long now = System.currentTimeMillis();
16648            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16649            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16650                String packageName = entry.getKey();
16651                PackageParser.Package pkg = mPackages.get(packageName);
16652                if (pkg == null) {
16653                    continue;
16654                }
16655                UsageStats usage = entry.getValue();
16656                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16657                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16658            }
16659        }
16660    }
16661
16662    /**
16663     * Check and throw if the given before/after packages would be considered a
16664     * downgrade.
16665     */
16666    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16667            throws PackageManagerException {
16668        if (after.versionCode < before.mVersionCode) {
16669            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16670                    "Update version code " + after.versionCode + " is older than current "
16671                    + before.mVersionCode);
16672        } else if (after.versionCode == before.mVersionCode) {
16673            if (after.baseRevisionCode < before.baseRevisionCode) {
16674                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16675                        "Update base revision code " + after.baseRevisionCode
16676                        + " is older than current " + before.baseRevisionCode);
16677            }
16678
16679            if (!ArrayUtils.isEmpty(after.splitNames)) {
16680                for (int i = 0; i < after.splitNames.length; i++) {
16681                    final String splitName = after.splitNames[i];
16682                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16683                    if (j != -1) {
16684                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16685                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16686                                    "Update split " + splitName + " revision code "
16687                                    + after.splitRevisionCodes[i] + " is older than current "
16688                                    + before.splitRevisionCodes[j]);
16689                        }
16690                    }
16691                }
16692            }
16693        }
16694    }
16695
16696    private static class MoveCallbacks extends Handler {
16697        private static final int MSG_CREATED = 1;
16698        private static final int MSG_STATUS_CHANGED = 2;
16699
16700        private final RemoteCallbackList<IPackageMoveObserver>
16701                mCallbacks = new RemoteCallbackList<>();
16702
16703        private final SparseIntArray mLastStatus = new SparseIntArray();
16704
16705        public MoveCallbacks(Looper looper) {
16706            super(looper);
16707        }
16708
16709        public void register(IPackageMoveObserver callback) {
16710            mCallbacks.register(callback);
16711        }
16712
16713        public void unregister(IPackageMoveObserver callback) {
16714            mCallbacks.unregister(callback);
16715        }
16716
16717        @Override
16718        public void handleMessage(Message msg) {
16719            final SomeArgs args = (SomeArgs) msg.obj;
16720            final int n = mCallbacks.beginBroadcast();
16721            for (int i = 0; i < n; i++) {
16722                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16723                try {
16724                    invokeCallback(callback, msg.what, args);
16725                } catch (RemoteException ignored) {
16726                }
16727            }
16728            mCallbacks.finishBroadcast();
16729            args.recycle();
16730        }
16731
16732        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16733                throws RemoteException {
16734            switch (what) {
16735                case MSG_CREATED: {
16736                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16737                    break;
16738                }
16739                case MSG_STATUS_CHANGED: {
16740                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16741                    break;
16742                }
16743            }
16744        }
16745
16746        private void notifyCreated(int moveId, Bundle extras) {
16747            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16748
16749            final SomeArgs args = SomeArgs.obtain();
16750            args.argi1 = moveId;
16751            args.arg2 = extras;
16752            obtainMessage(MSG_CREATED, args).sendToTarget();
16753        }
16754
16755        private void notifyStatusChanged(int moveId, int status) {
16756            notifyStatusChanged(moveId, status, -1);
16757        }
16758
16759        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16760            Slog.v(TAG, "Move " + moveId + " status " + status);
16761
16762            final SomeArgs args = SomeArgs.obtain();
16763            args.argi1 = moveId;
16764            args.argi2 = status;
16765            args.arg3 = estMillis;
16766            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16767
16768            synchronized (mLastStatus) {
16769                mLastStatus.put(moveId, status);
16770            }
16771        }
16772    }
16773
16774    private final class OnPermissionChangeListeners extends Handler {
16775        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16776
16777        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16778                new RemoteCallbackList<>();
16779
16780        public OnPermissionChangeListeners(Looper looper) {
16781            super(looper);
16782        }
16783
16784        @Override
16785        public void handleMessage(Message msg) {
16786            switch (msg.what) {
16787                case MSG_ON_PERMISSIONS_CHANGED: {
16788                    final int uid = msg.arg1;
16789                    handleOnPermissionsChanged(uid);
16790                } break;
16791            }
16792        }
16793
16794        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16795            mPermissionListeners.register(listener);
16796
16797        }
16798
16799        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16800            mPermissionListeners.unregister(listener);
16801        }
16802
16803        public void onPermissionsChanged(int uid) {
16804            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16805                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16806            }
16807        }
16808
16809        private void handleOnPermissionsChanged(int uid) {
16810            final int count = mPermissionListeners.beginBroadcast();
16811            try {
16812                for (int i = 0; i < count; i++) {
16813                    IOnPermissionsChangeListener callback = mPermissionListeners
16814                            .getBroadcastItem(i);
16815                    try {
16816                        callback.onPermissionsChanged(uid);
16817                    } catch (RemoteException e) {
16818                        Log.e(TAG, "Permission listener is dead", e);
16819                    }
16820                }
16821            } finally {
16822                mPermissionListeners.finishBroadcast();
16823            }
16824        }
16825    }
16826
16827    private class PackageManagerInternalImpl extends PackageManagerInternal {
16828        @Override
16829        public void setLocationPackagesProvider(PackagesProvider provider) {
16830            synchronized (mPackages) {
16831                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16832            }
16833        }
16834
16835        @Override
16836        public void setImePackagesProvider(PackagesProvider provider) {
16837            synchronized (mPackages) {
16838                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16839            }
16840        }
16841
16842        @Override
16843        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16844            synchronized (mPackages) {
16845                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16846            }
16847        }
16848
16849        @Override
16850        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16851            synchronized (mPackages) {
16852                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16853            }
16854        }
16855
16856        @Override
16857        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16858            synchronized (mPackages) {
16859                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16860            }
16861        }
16862
16863        @Override
16864        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16865            synchronized (mPackages) {
16866                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16867            }
16868        }
16869
16870        @Override
16871        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16872            synchronized (mPackages) {
16873                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16874            }
16875        }
16876
16877        @Override
16878        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16879            synchronized (mPackages) {
16880                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16881                        packageName, userId);
16882            }
16883        }
16884
16885        @Override
16886        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16887            synchronized (mPackages) {
16888                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16889                        packageName, userId);
16890            }
16891        }
16892        @Override
16893        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16894            synchronized (mPackages) {
16895                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16896                        packageName, userId);
16897            }
16898        }
16899    }
16900
16901    @Override
16902    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16903        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16904        synchronized (mPackages) {
16905            final long identity = Binder.clearCallingIdentity();
16906            try {
16907                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16908                        packageNames, userId);
16909            } finally {
16910                Binder.restoreCallingIdentity(identity);
16911            }
16912        }
16913    }
16914
16915    private static void enforceSystemOrPhoneCaller(String tag) {
16916        int callingUid = Binder.getCallingUid();
16917        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16918            throw new SecurityException(
16919                    "Cannot call " + tag + " from UID " + callingUid);
16920        }
16921    }
16922}
16923