PackageManagerService.java revision 1a350157198bd8700f1e81b8ce3f7c656f91dba9
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.InstructionSets.getAppDexInstructionSets;
79import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
80import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
81import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
82import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
86
87import android.Manifest;
88import android.app.ActivityManager;
89import android.app.ActivityManagerNative;
90import android.app.AppGlobals;
91import android.app.IActivityManager;
92import android.app.admin.IDevicePolicyManager;
93import android.app.backup.IBackupManager;
94import android.app.usage.UsageStats;
95import android.app.usage.UsageStatsManager;
96import android.content.BroadcastReceiver;
97import android.content.ComponentName;
98import android.content.Context;
99import android.content.IIntentReceiver;
100import android.content.Intent;
101import android.content.IntentFilter;
102import android.content.IntentSender;
103import android.content.IntentSender.SendIntentException;
104import android.content.ServiceConnection;
105import android.content.pm.ActivityInfo;
106import android.content.pm.ApplicationInfo;
107import android.content.pm.FeatureInfo;
108import android.content.pm.IOnPermissionsChangeListener;
109import android.content.pm.IPackageDataObserver;
110import android.content.pm.IPackageDeleteObserver;
111import android.content.pm.IPackageDeleteObserver2;
112import android.content.pm.IPackageInstallObserver2;
113import android.content.pm.IPackageInstaller;
114import android.content.pm.IPackageManager;
115import android.content.pm.IPackageMoveObserver;
116import android.content.pm.IPackageStatsObserver;
117import android.content.pm.InstrumentationInfo;
118import android.content.pm.IntentFilterVerificationInfo;
119import android.content.pm.KeySet;
120import android.content.pm.ManifestDigest;
121import android.content.pm.PackageCleanItem;
122import android.content.pm.PackageInfo;
123import android.content.pm.PackageInfoLite;
124import android.content.pm.PackageInstaller;
125import android.content.pm.PackageManager;
126import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
127import android.content.pm.PackageManagerInternal;
128import android.content.pm.PackageParser;
129import android.content.pm.PackageParser.ActivityIntentInfo;
130import android.content.pm.PackageParser.PackageLite;
131import android.content.pm.PackageParser.PackageParserException;
132import android.content.pm.PackageStats;
133import android.content.pm.PackageUserState;
134import android.content.pm.ParceledListSlice;
135import android.content.pm.PermissionGroupInfo;
136import android.content.pm.PermissionInfo;
137import android.content.pm.ProviderInfo;
138import android.content.pm.ResolveInfo;
139import android.content.pm.ServiceInfo;
140import android.content.pm.Signature;
141import android.content.pm.UserInfo;
142import android.content.pm.VerificationParams;
143import android.content.pm.VerifierDeviceIdentity;
144import android.content.pm.VerifierInfo;
145import android.content.res.Resources;
146import android.hardware.display.DisplayManager;
147import android.net.Uri;
148import android.os.Debug;
149import android.os.Binder;
150import android.os.Build;
151import android.os.Bundle;
152import android.os.Environment;
153import android.os.Environment.UserEnvironment;
154import android.os.FileUtils;
155import android.os.Handler;
156import android.os.IBinder;
157import android.os.Looper;
158import android.os.Message;
159import android.os.Parcel;
160import android.os.ParcelFileDescriptor;
161import android.os.Process;
162import android.os.RemoteCallbackList;
163import android.os.RemoteException;
164import android.os.SELinux;
165import android.os.ServiceManager;
166import android.os.SystemClock;
167import android.os.SystemProperties;
168import android.os.Trace;
169import android.os.UserHandle;
170import android.os.UserManager;
171import android.os.storage.IMountService;
172import android.os.storage.MountServiceInternal;
173import android.os.storage.StorageEventListener;
174import android.os.storage.StorageManager;
175import android.os.storage.VolumeInfo;
176import android.os.storage.VolumeRecord;
177import android.security.KeyStore;
178import android.security.SystemKeyStore;
179import android.system.ErrnoException;
180import android.system.Os;
181import android.system.StructStat;
182import android.text.TextUtils;
183import android.text.format.DateUtils;
184import android.util.ArrayMap;
185import android.util.ArraySet;
186import android.util.AtomicFile;
187import android.util.DisplayMetrics;
188import android.util.EventLog;
189import android.util.ExceptionUtils;
190import android.util.Log;
191import android.util.LogPrinter;
192import android.util.MathUtils;
193import android.util.PrintStreamPrinter;
194import android.util.Slog;
195import android.util.SparseArray;
196import android.util.SparseBooleanArray;
197import android.util.SparseIntArray;
198import android.util.Xml;
199import android.view.Display;
200
201import dalvik.system.DexFile;
202import dalvik.system.VMRuntime;
203
204import libcore.io.IoUtils;
205import libcore.util.EmptyArray;
206
207import com.android.internal.R;
208import com.android.internal.annotations.GuardedBy;
209import com.android.internal.app.IMediaContainerService;
210import com.android.internal.app.ResolverActivity;
211import com.android.internal.content.NativeLibraryHelper;
212import com.android.internal.content.PackageHelper;
213import com.android.internal.os.IParcelFileDescriptorFactory;
214import com.android.internal.os.SomeArgs;
215import com.android.internal.os.Zygote;
216import com.android.internal.util.ArrayUtils;
217import com.android.internal.util.FastPrintWriter;
218import com.android.internal.util.FastXmlSerializer;
219import com.android.internal.util.IndentingPrintWriter;
220import com.android.internal.util.Preconditions;
221import com.android.server.EventLogTags;
222import com.android.server.FgThread;
223import com.android.server.IntentResolver;
224import com.android.server.LocalServices;
225import com.android.server.ServiceThread;
226import com.android.server.SystemConfig;
227import com.android.server.Watchdog;
228import com.android.server.pm.PermissionsState.PermissionState;
229import com.android.server.pm.Settings.DatabaseVersion;
230import com.android.server.pm.Settings.VersionInfo;
231import com.android.server.storage.DeviceStorageMonitorInternal;
232
233import org.xmlpull.v1.XmlPullParser;
234import org.xmlpull.v1.XmlPullParserException;
235import org.xmlpull.v1.XmlSerializer;
236
237import java.io.BufferedInputStream;
238import java.io.BufferedOutputStream;
239import java.io.BufferedReader;
240import java.io.ByteArrayInputStream;
241import java.io.ByteArrayOutputStream;
242import java.io.File;
243import java.io.FileDescriptor;
244import java.io.FileNotFoundException;
245import java.io.FileOutputStream;
246import java.io.FileReader;
247import java.io.FilenameFilter;
248import java.io.IOException;
249import java.io.InputStream;
250import java.io.PrintWriter;
251import java.nio.charset.StandardCharsets;
252import java.security.NoSuchAlgorithmException;
253import java.security.PublicKey;
254import java.security.cert.CertificateEncodingException;
255import java.security.cert.CertificateException;
256import java.text.SimpleDateFormat;
257import java.util.ArrayList;
258import java.util.Arrays;
259import java.util.Collection;
260import java.util.Collections;
261import java.util.Comparator;
262import java.util.Date;
263import java.util.Iterator;
264import java.util.List;
265import java.util.Map;
266import java.util.Objects;
267import java.util.Set;
268import java.util.concurrent.CountDownLatch;
269import java.util.concurrent.TimeUnit;
270import java.util.concurrent.atomic.AtomicBoolean;
271import java.util.concurrent.atomic.AtomicInteger;
272import java.util.concurrent.atomic.AtomicLong;
273
274/**
275 * Keep track of all those .apks everywhere.
276 *
277 * This is very central to the platform's security; please run the unit
278 * tests whenever making modifications here:
279 *
280runtest -c android.content.pm.PackageManagerTests frameworks-core
281 *
282 * {@hide}
283 */
284public class PackageManagerService extends IPackageManager.Stub {
285    static final String TAG = "PackageManager";
286    static final boolean DEBUG_SETTINGS = false;
287    static final boolean DEBUG_PREFERRED = false;
288    static final boolean DEBUG_UPGRADE = false;
289    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
290    private static final boolean DEBUG_BACKUP = false;
291    private static final boolean DEBUG_INSTALL = false;
292    private static final boolean DEBUG_REMOVE = false;
293    private static final boolean DEBUG_BROADCASTS = false;
294    private static final boolean DEBUG_SHOW_INFO = false;
295    private static final boolean DEBUG_PACKAGE_INFO = false;
296    private static final boolean DEBUG_INTENT_MATCHING = false;
297    private static final boolean DEBUG_PACKAGE_SCANNING = false;
298    private static final boolean DEBUG_VERIFY = false;
299    private static final boolean DEBUG_DEXOPT = false;
300    private static final boolean DEBUG_ABI_SELECTION = false;
301
302    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
303
304    private static final int RADIO_UID = Process.PHONE_UID;
305    private static final int LOG_UID = Process.LOG_UID;
306    private static final int NFC_UID = Process.NFC_UID;
307    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
308    private static final int SHELL_UID = Process.SHELL_UID;
309
310    // Cap the size of permission trees that 3rd party apps can define
311    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
312
313    // Suffix used during package installation when copying/moving
314    // package apks to install directory.
315    private static final String INSTALL_PACKAGE_SUFFIX = "-";
316
317    static final int SCAN_NO_DEX = 1<<1;
318    static final int SCAN_FORCE_DEX = 1<<2;
319    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
320    static final int SCAN_NEW_INSTALL = 1<<4;
321    static final int SCAN_NO_PATHS = 1<<5;
322    static final int SCAN_UPDATE_TIME = 1<<6;
323    static final int SCAN_DEFER_DEX = 1<<7;
324    static final int SCAN_BOOTING = 1<<8;
325    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
326    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
327    static final int SCAN_REPLACING = 1<<11;
328    static final int SCAN_REQUIRE_KNOWN = 1<<12;
329    static final int SCAN_MOVE = 1<<13;
330    static final int SCAN_INITIAL = 1<<14;
331
332    static final int REMOVE_CHATTY = 1<<16;
333
334    private static final int[] EMPTY_INT_ARRAY = new int[0];
335
336    /**
337     * Timeout (in milliseconds) after which the watchdog should declare that
338     * our handler thread is wedged.  The usual default for such things is one
339     * minute but we sometimes do very lengthy I/O operations on this thread,
340     * such as installing multi-gigabyte applications, so ours needs to be longer.
341     */
342    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
343
344    /**
345     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
346     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
347     * settings entry if available, otherwise we use the hardcoded default.  If it's been
348     * more than this long since the last fstrim, we force one during the boot sequence.
349     *
350     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
351     * one gets run at the next available charging+idle time.  This final mandatory
352     * no-fstrim check kicks in only of the other scheduling criteria is never met.
353     */
354    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
355
356    /**
357     * Whether verification is enabled by default.
358     */
359    private static final boolean DEFAULT_VERIFY_ENABLE = true;
360
361    /**
362     * The default maximum time to wait for the verification agent to return in
363     * milliseconds.
364     */
365    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
366
367    /**
368     * The default response for package verification timeout.
369     *
370     * This can be either PackageManager.VERIFICATION_ALLOW or
371     * PackageManager.VERIFICATION_REJECT.
372     */
373    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
374
375    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
376
377    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
378            DEFAULT_CONTAINER_PACKAGE,
379            "com.android.defcontainer.DefaultContainerService");
380
381    private static final String KILL_APP_REASON_GIDS_CHANGED =
382            "permission grant or revoke changed gids";
383
384    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
385            "permissions revoked";
386
387    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
388
389    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
390
391    /** Permission grant: not grant the permission. */
392    private static final int GRANT_DENIED = 1;
393
394    /** Permission grant: grant the permission as an install permission. */
395    private static final int GRANT_INSTALL = 2;
396
397    /** Permission grant: grant the permission as an install permission for a legacy app. */
398    private static final int GRANT_INSTALL_LEGACY = 3;
399
400    /** Permission grant: grant the permission as a runtime one. */
401    private static final int GRANT_RUNTIME = 4;
402
403    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
404    private static final int GRANT_UPGRADE = 5;
405
406    /** Canonical intent used to identify what counts as a "web browser" app */
407    private static final Intent sBrowserIntent;
408    static {
409        sBrowserIntent = new Intent();
410        sBrowserIntent.setAction(Intent.ACTION_VIEW);
411        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
412        sBrowserIntent.setData(Uri.parse("http:"));
413    }
414
415    final ServiceThread mHandlerThread;
416
417    final PackageHandler mHandler;
418
419    /**
420     * Messages for {@link #mHandler} that need to wait for system ready before
421     * being dispatched.
422     */
423    private ArrayList<Message> mPostSystemReadyMessages;
424
425    final int mSdkVersion = Build.VERSION.SDK_INT;
426
427    final Context mContext;
428    final boolean mFactoryTest;
429    final boolean mOnlyCore;
430    final boolean mLazyDexOpt;
431    final long mDexOptLRUThresholdInMills;
432    final DisplayMetrics mMetrics;
433    final int mDefParseFlags;
434    final String[] mSeparateProcesses;
435    final boolean mIsUpgrade;
436
437    // This is where all application persistent data goes.
438    final File mAppDataDir;
439
440    // This is where all application persistent data goes for secondary users.
441    final File mUserAppDataDir;
442
443    /** The location for ASEC container files on internal storage. */
444    final String mAsecInternalPath;
445
446    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
447    // LOCK HELD.  Can be called with mInstallLock held.
448    @GuardedBy("mInstallLock")
449    final Installer mInstaller;
450
451    /** Directory where installed third-party apps stored */
452    final File mAppInstallDir;
453
454    /**
455     * Directory to which applications installed internally have their
456     * 32 bit native libraries copied.
457     */
458    private File mAppLib32InstallDir;
459
460    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
461    // apps.
462    final File mDrmAppPrivateInstallDir;
463
464    // ----------------------------------------------------------------
465
466    // Lock for state used when installing and doing other long running
467    // operations.  Methods that must be called with this lock held have
468    // the suffix "LI".
469    final Object mInstallLock = new Object();
470
471    // ----------------------------------------------------------------
472
473    // Keys are String (package name), values are Package.  This also serves
474    // as the lock for the global state.  Methods that must be called with
475    // this lock held have the prefix "LP".
476    @GuardedBy("mPackages")
477    final ArrayMap<String, PackageParser.Package> mPackages =
478            new ArrayMap<String, PackageParser.Package>();
479
480    // Tracks available target package names -> overlay package paths.
481    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
482        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
483
484    /**
485     * Tracks new system packages [received in an OTA] that we expect to
486     * find updated user-installed versions. Keys are package name, values
487     * are package location.
488     */
489    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
490
491    /**
492     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
493     */
494    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
495    /**
496     * Whether or not system app permissions should be promoted from install to runtime.
497     */
498    boolean mPromoteSystemApps;
499
500    final Settings mSettings;
501    boolean mRestoredSettings;
502
503    // System configuration read by SystemConfig.
504    final int[] mGlobalGids;
505    final SparseArray<ArraySet<String>> mSystemPermissions;
506    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
507
508    // If mac_permissions.xml was found for seinfo labeling.
509    boolean mFoundPolicyFile;
510
511    // If a recursive restorecon of /data/data/<pkg> is needed.
512    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
513
514    public static final class SharedLibraryEntry {
515        public final String path;
516        public final String apk;
517
518        SharedLibraryEntry(String _path, String _apk) {
519            path = _path;
520            apk = _apk;
521        }
522    }
523
524    // Currently known shared libraries.
525    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
526            new ArrayMap<String, SharedLibraryEntry>();
527
528    // All available activities, for your resolving pleasure.
529    final ActivityIntentResolver mActivities =
530            new ActivityIntentResolver();
531
532    // All available receivers, for your resolving pleasure.
533    final ActivityIntentResolver mReceivers =
534            new ActivityIntentResolver();
535
536    // All available services, for your resolving pleasure.
537    final ServiceIntentResolver mServices = new ServiceIntentResolver();
538
539    // All available providers, for your resolving pleasure.
540    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
541
542    // Mapping from provider base names (first directory in content URI codePath)
543    // to the provider information.
544    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
545            new ArrayMap<String, PackageParser.Provider>();
546
547    // Mapping from instrumentation class names to info about them.
548    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
549            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
550
551    // Mapping from permission names to info about them.
552    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
553            new ArrayMap<String, PackageParser.PermissionGroup>();
554
555    // Packages whose data we have transfered into another package, thus
556    // should no longer exist.
557    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
558
559    // Broadcast actions that are only available to the system.
560    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
561
562    /** List of packages waiting for verification. */
563    final SparseArray<PackageVerificationState> mPendingVerification
564            = new SparseArray<PackageVerificationState>();
565
566    /** Set of packages associated with each app op permission. */
567    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
568
569    final PackageInstallerService mInstallerService;
570
571    private final PackageDexOptimizer mPackageDexOptimizer;
572
573    private AtomicInteger mNextMoveId = new AtomicInteger();
574    private final MoveCallbacks mMoveCallbacks;
575
576    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
577
578    // Cache of users who need badging.
579    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
580
581    /** Token for keys in mPendingVerification. */
582    private int mPendingVerificationToken = 0;
583
584    volatile boolean mSystemReady;
585    volatile boolean mSafeMode;
586    volatile boolean mHasSystemUidErrors;
587
588    ApplicationInfo mAndroidApplication;
589    final ActivityInfo mResolveActivity = new ActivityInfo();
590    final ResolveInfo mResolveInfo = new ResolveInfo();
591    ComponentName mResolveComponentName;
592    PackageParser.Package mPlatformPackage;
593    ComponentName mCustomResolverComponentName;
594
595    boolean mResolverReplaced = false;
596
597    private final ComponentName mIntentFilterVerifierComponent;
598    private int mIntentFilterVerificationToken = 0;
599
600    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
601            = new SparseArray<IntentFilterVerificationState>();
602
603    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
604            new DefaultPermissionGrantPolicy(this);
605
606    private static class IFVerificationParams {
607        PackageParser.Package pkg;
608        boolean replacing;
609        int userId;
610        int verifierUid;
611
612        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
613                int _userId, int _verifierUid) {
614            pkg = _pkg;
615            replacing = _replacing;
616            userId = _userId;
617            replacing = _replacing;
618            verifierUid = _verifierUid;
619        }
620    }
621
622    private interface IntentFilterVerifier<T extends IntentFilter> {
623        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
624                                               T filter, String packageName);
625        void startVerifications(int userId);
626        void receiveVerificationResponse(int verificationId);
627    }
628
629    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
630        private Context mContext;
631        private ComponentName mIntentFilterVerifierComponent;
632        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
633
634        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
635            mContext = context;
636            mIntentFilterVerifierComponent = verifierComponent;
637        }
638
639        private String getDefaultScheme() {
640            return IntentFilter.SCHEME_HTTPS;
641        }
642
643        @Override
644        public void startVerifications(int userId) {
645            // Launch verifications requests
646            int count = mCurrentIntentFilterVerifications.size();
647            for (int n=0; n<count; n++) {
648                int verificationId = mCurrentIntentFilterVerifications.get(n);
649                final IntentFilterVerificationState ivs =
650                        mIntentFilterVerificationStates.get(verificationId);
651
652                String packageName = ivs.getPackageName();
653
654                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
655                final int filterCount = filters.size();
656                ArraySet<String> domainsSet = new ArraySet<>();
657                for (int m=0; m<filterCount; m++) {
658                    PackageParser.ActivityIntentInfo filter = filters.get(m);
659                    domainsSet.addAll(filter.getHostsList());
660                }
661                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
662                synchronized (mPackages) {
663                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
664                            packageName, domainsList) != null) {
665                        scheduleWriteSettingsLocked();
666                    }
667                }
668                sendVerificationRequest(userId, verificationId, ivs);
669            }
670            mCurrentIntentFilterVerifications.clear();
671        }
672
673        private void sendVerificationRequest(int userId, int verificationId,
674                IntentFilterVerificationState ivs) {
675
676            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
677            verificationIntent.putExtra(
678                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
679                    verificationId);
680            verificationIntent.putExtra(
681                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
682                    getDefaultScheme());
683            verificationIntent.putExtra(
684                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
685                    ivs.getHostsString());
686            verificationIntent.putExtra(
687                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
688                    ivs.getPackageName());
689            verificationIntent.setComponent(mIntentFilterVerifierComponent);
690            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
691
692            UserHandle user = new UserHandle(userId);
693            mContext.sendBroadcastAsUser(verificationIntent, user);
694            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
695                    "Sending IntentFilter verification broadcast");
696        }
697
698        public void receiveVerificationResponse(int verificationId) {
699            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
700
701            final boolean verified = ivs.isVerified();
702
703            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
704            final int count = filters.size();
705            if (DEBUG_DOMAIN_VERIFICATION) {
706                Slog.i(TAG, "Received verification response " + verificationId
707                        + " for " + count + " filters, verified=" + verified);
708            }
709            for (int n=0; n<count; n++) {
710                PackageParser.ActivityIntentInfo filter = filters.get(n);
711                filter.setVerified(verified);
712
713                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
714                        + " verified with result:" + verified + " and hosts:"
715                        + ivs.getHostsString());
716            }
717
718            mIntentFilterVerificationStates.remove(verificationId);
719
720            final String packageName = ivs.getPackageName();
721            IntentFilterVerificationInfo ivi = null;
722
723            synchronized (mPackages) {
724                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
725            }
726            if (ivi == null) {
727                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
728                        + verificationId + " packageName:" + packageName);
729                return;
730            }
731            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
732                    "Updating IntentFilterVerificationInfo for package " + packageName
733                            +" verificationId:" + verificationId);
734
735            synchronized (mPackages) {
736                if (verified) {
737                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
738                } else {
739                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
740                }
741                scheduleWriteSettingsLocked();
742
743                final int userId = ivs.getUserId();
744                if (userId != UserHandle.USER_ALL) {
745                    final int userStatus =
746                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
747
748                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
749                    boolean needUpdate = false;
750
751                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
752                    // already been set by the User thru the Disambiguation dialog
753                    switch (userStatus) {
754                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
755                            if (verified) {
756                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
757                            } else {
758                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
759                            }
760                            needUpdate = true;
761                            break;
762
763                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
764                            if (verified) {
765                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
766                                needUpdate = true;
767                            }
768                            break;
769
770                        default:
771                            // Nothing to do
772                    }
773
774                    if (needUpdate) {
775                        mSettings.updateIntentFilterVerificationStatusLPw(
776                                packageName, updatedStatus, userId);
777                        scheduleWritePackageRestrictionsLocked(userId);
778                    }
779                }
780            }
781        }
782
783        @Override
784        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
785                    ActivityIntentInfo filter, String packageName) {
786            if (!hasValidDomains(filter)) {
787                return false;
788            }
789            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
790            if (ivs == null) {
791                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
792                        packageName);
793            }
794            if (DEBUG_DOMAIN_VERIFICATION) {
795                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
796            }
797            ivs.addFilter(filter);
798            return true;
799        }
800
801        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
802                int userId, int verificationId, String packageName) {
803            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
804                    verifierUid, userId, packageName);
805            ivs.setPendingState();
806            synchronized (mPackages) {
807                mIntentFilterVerificationStates.append(verificationId, ivs);
808                mCurrentIntentFilterVerifications.add(verificationId);
809            }
810            return ivs;
811        }
812    }
813
814    private static boolean hasValidDomains(ActivityIntentInfo filter) {
815        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
816                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
817                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
818    }
819
820    private IntentFilterVerifier mIntentFilterVerifier;
821
822    // Set of pending broadcasts for aggregating enable/disable of components.
823    static class PendingPackageBroadcasts {
824        // for each user id, a map of <package name -> components within that package>
825        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
826
827        public PendingPackageBroadcasts() {
828            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
829        }
830
831        public ArrayList<String> get(int userId, String packageName) {
832            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
833            return packages.get(packageName);
834        }
835
836        public void put(int userId, String packageName, ArrayList<String> components) {
837            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
838            packages.put(packageName, components);
839        }
840
841        public void remove(int userId, String packageName) {
842            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
843            if (packages != null) {
844                packages.remove(packageName);
845            }
846        }
847
848        public void remove(int userId) {
849            mUidMap.remove(userId);
850        }
851
852        public int userIdCount() {
853            return mUidMap.size();
854        }
855
856        public int userIdAt(int n) {
857            return mUidMap.keyAt(n);
858        }
859
860        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
861            return mUidMap.get(userId);
862        }
863
864        public int size() {
865            // total number of pending broadcast entries across all userIds
866            int num = 0;
867            for (int i = 0; i< mUidMap.size(); i++) {
868                num += mUidMap.valueAt(i).size();
869            }
870            return num;
871        }
872
873        public void clear() {
874            mUidMap.clear();
875        }
876
877        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
878            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
879            if (map == null) {
880                map = new ArrayMap<String, ArrayList<String>>();
881                mUidMap.put(userId, map);
882            }
883            return map;
884        }
885    }
886    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
887
888    // Service Connection to remote media container service to copy
889    // package uri's from external media onto secure containers
890    // or internal storage.
891    private IMediaContainerService mContainerService = null;
892
893    static final int SEND_PENDING_BROADCAST = 1;
894    static final int MCS_BOUND = 3;
895    static final int END_COPY = 4;
896    static final int INIT_COPY = 5;
897    static final int MCS_UNBIND = 6;
898    static final int START_CLEANING_PACKAGE = 7;
899    static final int FIND_INSTALL_LOC = 8;
900    static final int POST_INSTALL = 9;
901    static final int MCS_RECONNECT = 10;
902    static final int MCS_GIVE_UP = 11;
903    static final int UPDATED_MEDIA_STATUS = 12;
904    static final int WRITE_SETTINGS = 13;
905    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
906    static final int PACKAGE_VERIFIED = 15;
907    static final int CHECK_PENDING_VERIFICATION = 16;
908    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
909    static final int INTENT_FILTER_VERIFIED = 18;
910
911    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
912
913    // Delay time in millisecs
914    static final int BROADCAST_DELAY = 10 * 1000;
915
916    static UserManagerService sUserManager;
917
918    // Stores a list of users whose package restrictions file needs to be updated
919    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
920
921    final private DefaultContainerConnection mDefContainerConn =
922            new DefaultContainerConnection();
923    class DefaultContainerConnection implements ServiceConnection {
924        public void onServiceConnected(ComponentName name, IBinder service) {
925            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
926            IMediaContainerService imcs =
927                IMediaContainerService.Stub.asInterface(service);
928            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
929        }
930
931        public void onServiceDisconnected(ComponentName name) {
932            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
933        }
934    }
935
936    // Recordkeeping of restore-after-install operations that are currently in flight
937    // between the Package Manager and the Backup Manager
938    class PostInstallData {
939        public InstallArgs args;
940        public PackageInstalledInfo res;
941
942        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
943            args = _a;
944            res = _r;
945        }
946    }
947
948    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
949    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
950
951    // XML tags for backup/restore of various bits of state
952    private static final String TAG_PREFERRED_BACKUP = "pa";
953    private static final String TAG_DEFAULT_APPS = "da";
954    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
955
956    final String mRequiredVerifierPackage;
957    final String mRequiredInstallerPackage;
958
959    private final PackageUsage mPackageUsage = new PackageUsage();
960
961    private class PackageUsage {
962        private static final int WRITE_INTERVAL
963            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
964
965        private final Object mFileLock = new Object();
966        private final AtomicLong mLastWritten = new AtomicLong(0);
967        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
968
969        private boolean mIsHistoricalPackageUsageAvailable = true;
970
971        boolean isHistoricalPackageUsageAvailable() {
972            return mIsHistoricalPackageUsageAvailable;
973        }
974
975        void write(boolean force) {
976            if (force) {
977                writeInternal();
978                return;
979            }
980            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
981                && !DEBUG_DEXOPT) {
982                return;
983            }
984            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
985                new Thread("PackageUsage_DiskWriter") {
986                    @Override
987                    public void run() {
988                        try {
989                            writeInternal();
990                        } finally {
991                            mBackgroundWriteRunning.set(false);
992                        }
993                    }
994                }.start();
995            }
996        }
997
998        private void writeInternal() {
999            synchronized (mPackages) {
1000                synchronized (mFileLock) {
1001                    AtomicFile file = getFile();
1002                    FileOutputStream f = null;
1003                    try {
1004                        f = file.startWrite();
1005                        BufferedOutputStream out = new BufferedOutputStream(f);
1006                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1007                        StringBuilder sb = new StringBuilder();
1008                        for (PackageParser.Package pkg : mPackages.values()) {
1009                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1010                                continue;
1011                            }
1012                            sb.setLength(0);
1013                            sb.append(pkg.packageName);
1014                            sb.append(' ');
1015                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1016                            sb.append('\n');
1017                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1018                        }
1019                        out.flush();
1020                        file.finishWrite(f);
1021                    } catch (IOException e) {
1022                        if (f != null) {
1023                            file.failWrite(f);
1024                        }
1025                        Log.e(TAG, "Failed to write package usage times", e);
1026                    }
1027                }
1028            }
1029            mLastWritten.set(SystemClock.elapsedRealtime());
1030        }
1031
1032        void readLP() {
1033            synchronized (mFileLock) {
1034                AtomicFile file = getFile();
1035                BufferedInputStream in = null;
1036                try {
1037                    in = new BufferedInputStream(file.openRead());
1038                    StringBuffer sb = new StringBuffer();
1039                    while (true) {
1040                        String packageName = readToken(in, sb, ' ');
1041                        if (packageName == null) {
1042                            break;
1043                        }
1044                        String timeInMillisString = readToken(in, sb, '\n');
1045                        if (timeInMillisString == null) {
1046                            throw new IOException("Failed to find last usage time for package "
1047                                                  + packageName);
1048                        }
1049                        PackageParser.Package pkg = mPackages.get(packageName);
1050                        if (pkg == null) {
1051                            continue;
1052                        }
1053                        long timeInMillis;
1054                        try {
1055                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1056                        } catch (NumberFormatException e) {
1057                            throw new IOException("Failed to parse " + timeInMillisString
1058                                                  + " as a long.", e);
1059                        }
1060                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1061                    }
1062                } catch (FileNotFoundException expected) {
1063                    mIsHistoricalPackageUsageAvailable = false;
1064                } catch (IOException e) {
1065                    Log.w(TAG, "Failed to read package usage times", e);
1066                } finally {
1067                    IoUtils.closeQuietly(in);
1068                }
1069            }
1070            mLastWritten.set(SystemClock.elapsedRealtime());
1071        }
1072
1073        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1074                throws IOException {
1075            sb.setLength(0);
1076            while (true) {
1077                int ch = in.read();
1078                if (ch == -1) {
1079                    if (sb.length() == 0) {
1080                        return null;
1081                    }
1082                    throw new IOException("Unexpected EOF");
1083                }
1084                if (ch == endOfToken) {
1085                    return sb.toString();
1086                }
1087                sb.append((char)ch);
1088            }
1089        }
1090
1091        private AtomicFile getFile() {
1092            File dataDir = Environment.getDataDirectory();
1093            File systemDir = new File(dataDir, "system");
1094            File fname = new File(systemDir, "package-usage.list");
1095            return new AtomicFile(fname);
1096        }
1097    }
1098
1099    class PackageHandler extends Handler {
1100        private boolean mBound = false;
1101        final ArrayList<HandlerParams> mPendingInstalls =
1102            new ArrayList<HandlerParams>();
1103
1104        private boolean connectToService() {
1105            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1106                    " DefaultContainerService");
1107            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1108            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1109            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1110                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1111                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1112                mBound = true;
1113                return true;
1114            }
1115            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1116            return false;
1117        }
1118
1119        private void disconnectService() {
1120            mContainerService = null;
1121            mBound = false;
1122            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1123            mContext.unbindService(mDefContainerConn);
1124            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1125        }
1126
1127        PackageHandler(Looper looper) {
1128            super(looper);
1129        }
1130
1131        public void handleMessage(Message msg) {
1132            try {
1133                doHandleMessage(msg);
1134            } finally {
1135                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1136            }
1137        }
1138
1139        void doHandleMessage(Message msg) {
1140            switch (msg.what) {
1141                case INIT_COPY: {
1142                    HandlerParams params = (HandlerParams) msg.obj;
1143                    int idx = mPendingInstalls.size();
1144                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1145                    // If a bind was already initiated we dont really
1146                    // need to do anything. The pending install
1147                    // will be processed later on.
1148                    if (!mBound) {
1149                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1150                                System.identityHashCode(mHandler));
1151                        // If this is the only one pending we might
1152                        // have to bind to the service again.
1153                        if (!connectToService()) {
1154                            Slog.e(TAG, "Failed to bind to media container service");
1155                            params.serviceError();
1156                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1157                                    System.identityHashCode(mHandler));
1158                            if (params.traceMethod != null) {
1159                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1160                                        params.traceCookie);
1161                            }
1162                            return;
1163                        } else {
1164                            // Once we bind to the service, the first
1165                            // pending request will be processed.
1166                            mPendingInstalls.add(idx, params);
1167                        }
1168                    } else {
1169                        mPendingInstalls.add(idx, params);
1170                        // Already bound to the service. Just make
1171                        // sure we trigger off processing the first request.
1172                        if (idx == 0) {
1173                            mHandler.sendEmptyMessage(MCS_BOUND);
1174                        }
1175                    }
1176                    break;
1177                }
1178                case MCS_BOUND: {
1179                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1180                    if (msg.obj != null) {
1181                        mContainerService = (IMediaContainerService) msg.obj;
1182                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1183                                System.identityHashCode(mHandler));
1184                    }
1185                    if (mContainerService == null) {
1186                        if (!mBound) {
1187                            // Something seriously wrong since we are not bound and we are not
1188                            // waiting for connection. Bail out.
1189                            Slog.e(TAG, "Cannot bind to media container service");
1190                            for (HandlerParams params : mPendingInstalls) {
1191                                // Indicate service bind error
1192                                params.serviceError();
1193                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1194                                        System.identityHashCode(params));
1195                                if (params.traceMethod != null) {
1196                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1197                                            params.traceMethod, params.traceCookie);
1198                                }
1199                                return;
1200                            }
1201                            mPendingInstalls.clear();
1202                        } else {
1203                            Slog.w(TAG, "Waiting to connect to media container service");
1204                        }
1205                    } else if (mPendingInstalls.size() > 0) {
1206                        HandlerParams params = mPendingInstalls.get(0);
1207                        if (params != null) {
1208                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1209                                    System.identityHashCode(params));
1210                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1211                            if (params.startCopy()) {
1212                                // We are done...  look for more work or to
1213                                // go idle.
1214                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1215                                        "Checking for more work or unbind...");
1216                                // Delete pending install
1217                                if (mPendingInstalls.size() > 0) {
1218                                    mPendingInstalls.remove(0);
1219                                }
1220                                if (mPendingInstalls.size() == 0) {
1221                                    if (mBound) {
1222                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1223                                                "Posting delayed MCS_UNBIND");
1224                                        removeMessages(MCS_UNBIND);
1225                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1226                                        // Unbind after a little delay, to avoid
1227                                        // continual thrashing.
1228                                        sendMessageDelayed(ubmsg, 10000);
1229                                    }
1230                                } else {
1231                                    // There are more pending requests in queue.
1232                                    // Just post MCS_BOUND message to trigger processing
1233                                    // of next pending install.
1234                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1235                                            "Posting MCS_BOUND for next work");
1236                                    mHandler.sendEmptyMessage(MCS_BOUND);
1237                                }
1238                            }
1239                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1240                        }
1241                    } else {
1242                        // Should never happen ideally.
1243                        Slog.w(TAG, "Empty queue");
1244                    }
1245                    break;
1246                }
1247                case MCS_RECONNECT: {
1248                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1249                    if (mPendingInstalls.size() > 0) {
1250                        if (mBound) {
1251                            disconnectService();
1252                        }
1253                        if (!connectToService()) {
1254                            Slog.e(TAG, "Failed to bind to media container service");
1255                            for (HandlerParams params : mPendingInstalls) {
1256                                // Indicate service bind error
1257                                params.serviceError();
1258                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1259                                        System.identityHashCode(params));
1260                            }
1261                            mPendingInstalls.clear();
1262                        }
1263                    }
1264                    break;
1265                }
1266                case MCS_UNBIND: {
1267                    // If there is no actual work left, then time to unbind.
1268                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1269
1270                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1271                        if (mBound) {
1272                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1273
1274                            disconnectService();
1275                        }
1276                    } else if (mPendingInstalls.size() > 0) {
1277                        // There are more pending requests in queue.
1278                        // Just post MCS_BOUND message to trigger processing
1279                        // of next pending install.
1280                        mHandler.sendEmptyMessage(MCS_BOUND);
1281                    }
1282
1283                    break;
1284                }
1285                case MCS_GIVE_UP: {
1286                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1287                    HandlerParams params = mPendingInstalls.remove(0);
1288                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1289                            System.identityHashCode(params));
1290                    break;
1291                }
1292                case SEND_PENDING_BROADCAST: {
1293                    String packages[];
1294                    ArrayList<String> components[];
1295                    int size = 0;
1296                    int uids[];
1297                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1298                    synchronized (mPackages) {
1299                        if (mPendingBroadcasts == null) {
1300                            return;
1301                        }
1302                        size = mPendingBroadcasts.size();
1303                        if (size <= 0) {
1304                            // Nothing to be done. Just return
1305                            return;
1306                        }
1307                        packages = new String[size];
1308                        components = new ArrayList[size];
1309                        uids = new int[size];
1310                        int i = 0;  // filling out the above arrays
1311
1312                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1313                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1314                            Iterator<Map.Entry<String, ArrayList<String>>> it
1315                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1316                                            .entrySet().iterator();
1317                            while (it.hasNext() && i < size) {
1318                                Map.Entry<String, ArrayList<String>> ent = it.next();
1319                                packages[i] = ent.getKey();
1320                                components[i] = ent.getValue();
1321                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1322                                uids[i] = (ps != null)
1323                                        ? UserHandle.getUid(packageUserId, ps.appId)
1324                                        : -1;
1325                                i++;
1326                            }
1327                        }
1328                        size = i;
1329                        mPendingBroadcasts.clear();
1330                    }
1331                    // Send broadcasts
1332                    for (int i = 0; i < size; i++) {
1333                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1334                    }
1335                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1336                    break;
1337                }
1338                case START_CLEANING_PACKAGE: {
1339                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1340                    final String packageName = (String)msg.obj;
1341                    final int userId = msg.arg1;
1342                    final boolean andCode = msg.arg2 != 0;
1343                    synchronized (mPackages) {
1344                        if (userId == UserHandle.USER_ALL) {
1345                            int[] users = sUserManager.getUserIds();
1346                            for (int user : users) {
1347                                mSettings.addPackageToCleanLPw(
1348                                        new PackageCleanItem(user, packageName, andCode));
1349                            }
1350                        } else {
1351                            mSettings.addPackageToCleanLPw(
1352                                    new PackageCleanItem(userId, packageName, andCode));
1353                        }
1354                    }
1355                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1356                    startCleaningPackages();
1357                } break;
1358                case POST_INSTALL: {
1359                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1360                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1361                    mRunningInstalls.delete(msg.arg1);
1362                    boolean deleteOld = false;
1363
1364                    if (data != null) {
1365                        InstallArgs args = data.args;
1366                        PackageInstalledInfo res = data.res;
1367
1368                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1369                            final String packageName = res.pkg.applicationInfo.packageName;
1370                            res.removedInfo.sendBroadcast(false, true, false);
1371                            Bundle extras = new Bundle(1);
1372                            extras.putInt(Intent.EXTRA_UID, res.uid);
1373
1374                            // Now that we successfully installed the package, grant runtime
1375                            // permissions if requested before broadcasting the install.
1376                            if ((args.installFlags
1377                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1378                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1379                                        args.installGrantPermissions);
1380                            }
1381
1382                            // Determine the set of users who are adding this
1383                            // package for the first time vs. those who are seeing
1384                            // an update.
1385                            int[] firstUsers;
1386                            int[] updateUsers = new int[0];
1387                            if (res.origUsers == null || res.origUsers.length == 0) {
1388                                firstUsers = res.newUsers;
1389                            } else {
1390                                firstUsers = new int[0];
1391                                for (int i=0; i<res.newUsers.length; i++) {
1392                                    int user = res.newUsers[i];
1393                                    boolean isNew = true;
1394                                    for (int j=0; j<res.origUsers.length; j++) {
1395                                        if (res.origUsers[j] == user) {
1396                                            isNew = false;
1397                                            break;
1398                                        }
1399                                    }
1400                                    if (isNew) {
1401                                        int[] newFirst = new int[firstUsers.length+1];
1402                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1403                                                firstUsers.length);
1404                                        newFirst[firstUsers.length] = user;
1405                                        firstUsers = newFirst;
1406                                    } else {
1407                                        int[] newUpdate = new int[updateUsers.length+1];
1408                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1409                                                updateUsers.length);
1410                                        newUpdate[updateUsers.length] = user;
1411                                        updateUsers = newUpdate;
1412                                    }
1413                                }
1414                            }
1415                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1416                                    packageName, extras, null, null, firstUsers);
1417                            final boolean update = res.removedInfo.removedPackage != null;
1418                            if (update) {
1419                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1420                            }
1421                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1422                                    packageName, extras, null, null, updateUsers);
1423                            if (update) {
1424                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1425                                        packageName, extras, null, null, updateUsers);
1426                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1427                                        null, null, packageName, null, updateUsers);
1428
1429                                // treat asec-hosted packages like removable media on upgrade
1430                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1431                                    if (DEBUG_INSTALL) {
1432                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1433                                                + " is ASEC-hosted -> AVAILABLE");
1434                                    }
1435                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1436                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1437                                    pkgList.add(packageName);
1438                                    sendResourcesChangedBroadcast(true, true,
1439                                            pkgList,uidArray, null);
1440                                }
1441                            }
1442                            if (res.removedInfo.args != null) {
1443                                // Remove the replaced package's older resources safely now
1444                                deleteOld = true;
1445                            }
1446
1447                            // If this app is a browser and it's newly-installed for some
1448                            // users, clear any default-browser state in those users
1449                            if (firstUsers.length > 0) {
1450                                // the app's nature doesn't depend on the user, so we can just
1451                                // check its browser nature in any user and generalize.
1452                                if (packageIsBrowser(packageName, firstUsers[0])) {
1453                                    synchronized (mPackages) {
1454                                        for (int userId : firstUsers) {
1455                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1456                                        }
1457                                    }
1458                                }
1459                            }
1460                            // Log current value of "unknown sources" setting
1461                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1462                                getUnknownSourcesSettings());
1463                        }
1464                        // Force a gc to clear up things
1465                        Runtime.getRuntime().gc();
1466                        // We delete after a gc for applications  on sdcard.
1467                        if (deleteOld) {
1468                            synchronized (mInstallLock) {
1469                                res.removedInfo.args.doPostDeleteLI(true);
1470                            }
1471                        }
1472                        if (args.observer != null) {
1473                            try {
1474                                Bundle extras = extrasForInstallResult(res);
1475                                args.observer.onPackageInstalled(res.name, res.returnCode,
1476                                        res.returnMsg, extras);
1477                            } catch (RemoteException e) {
1478                                Slog.i(TAG, "Observer no longer exists.");
1479                            }
1480                        }
1481                        if (args.traceMethod != null) {
1482                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1483                                    args.traceCookie);
1484                        }
1485                        return;
1486                    } else {
1487                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1488                    }
1489
1490                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1491                } break;
1492                case UPDATED_MEDIA_STATUS: {
1493                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1494                    boolean reportStatus = msg.arg1 == 1;
1495                    boolean doGc = msg.arg2 == 1;
1496                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1497                    if (doGc) {
1498                        // Force a gc to clear up stale containers.
1499                        Runtime.getRuntime().gc();
1500                    }
1501                    if (msg.obj != null) {
1502                        @SuppressWarnings("unchecked")
1503                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1504                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1505                        // Unload containers
1506                        unloadAllContainers(args);
1507                    }
1508                    if (reportStatus) {
1509                        try {
1510                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1511                            PackageHelper.getMountService().finishMediaUpdate();
1512                        } catch (RemoteException e) {
1513                            Log.e(TAG, "MountService not running?");
1514                        }
1515                    }
1516                } break;
1517                case WRITE_SETTINGS: {
1518                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1519                    synchronized (mPackages) {
1520                        removeMessages(WRITE_SETTINGS);
1521                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1522                        mSettings.writeLPr();
1523                        mDirtyUsers.clear();
1524                    }
1525                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1526                } break;
1527                case WRITE_PACKAGE_RESTRICTIONS: {
1528                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1529                    synchronized (mPackages) {
1530                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1531                        for (int userId : mDirtyUsers) {
1532                            mSettings.writePackageRestrictionsLPr(userId);
1533                        }
1534                        mDirtyUsers.clear();
1535                    }
1536                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1537                } break;
1538                case CHECK_PENDING_VERIFICATION: {
1539                    final int verificationId = msg.arg1;
1540                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1541
1542                    if ((state != null) && !state.timeoutExtended()) {
1543                        final InstallArgs args = state.getInstallArgs();
1544                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1545
1546                        Slog.i(TAG, "Verification timed out for " + originUri);
1547                        mPendingVerification.remove(verificationId);
1548
1549                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1550
1551                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1552                            Slog.i(TAG, "Continuing with installation of " + originUri);
1553                            state.setVerifierResponse(Binder.getCallingUid(),
1554                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1555                            broadcastPackageVerified(verificationId, originUri,
1556                                    PackageManager.VERIFICATION_ALLOW,
1557                                    state.getInstallArgs().getUser());
1558                            try {
1559                                ret = args.copyApk(mContainerService, true);
1560                            } catch (RemoteException e) {
1561                                Slog.e(TAG, "Could not contact the ContainerService");
1562                            }
1563                        } else {
1564                            broadcastPackageVerified(verificationId, originUri,
1565                                    PackageManager.VERIFICATION_REJECT,
1566                                    state.getInstallArgs().getUser());
1567                        }
1568
1569                        Trace.asyncTraceEnd(
1570                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1571
1572                        processPendingInstall(args, ret);
1573                        mHandler.sendEmptyMessage(MCS_UNBIND);
1574                    }
1575                    break;
1576                }
1577                case PACKAGE_VERIFIED: {
1578                    final int verificationId = msg.arg1;
1579
1580                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1581                    if (state == null) {
1582                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1583                        break;
1584                    }
1585
1586                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1587
1588                    state.setVerifierResponse(response.callerUid, response.code);
1589
1590                    if (state.isVerificationComplete()) {
1591                        mPendingVerification.remove(verificationId);
1592
1593                        final InstallArgs args = state.getInstallArgs();
1594                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1595
1596                        int ret;
1597                        if (state.isInstallAllowed()) {
1598                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1599                            broadcastPackageVerified(verificationId, originUri,
1600                                    response.code, state.getInstallArgs().getUser());
1601                            try {
1602                                ret = args.copyApk(mContainerService, true);
1603                            } catch (RemoteException e) {
1604                                Slog.e(TAG, "Could not contact the ContainerService");
1605                            }
1606                        } else {
1607                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1608                        }
1609
1610                        Trace.asyncTraceEnd(
1611                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1612
1613                        processPendingInstall(args, ret);
1614                        mHandler.sendEmptyMessage(MCS_UNBIND);
1615                    }
1616
1617                    break;
1618                }
1619                case START_INTENT_FILTER_VERIFICATIONS: {
1620                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1621                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1622                            params.replacing, params.pkg);
1623                    break;
1624                }
1625                case INTENT_FILTER_VERIFIED: {
1626                    final int verificationId = msg.arg1;
1627
1628                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1629                            verificationId);
1630                    if (state == null) {
1631                        Slog.w(TAG, "Invalid IntentFilter verification token "
1632                                + verificationId + " received");
1633                        break;
1634                    }
1635
1636                    final int userId = state.getUserId();
1637
1638                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1639                            "Processing IntentFilter verification with token:"
1640                            + verificationId + " and userId:" + userId);
1641
1642                    final IntentFilterVerificationResponse response =
1643                            (IntentFilterVerificationResponse) msg.obj;
1644
1645                    state.setVerifierResponse(response.callerUid, response.code);
1646
1647                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1648                            "IntentFilter verification with token:" + verificationId
1649                            + " and userId:" + userId
1650                            + " is settings verifier response with response code:"
1651                            + response.code);
1652
1653                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1654                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1655                                + response.getFailedDomainsString());
1656                    }
1657
1658                    if (state.isVerificationComplete()) {
1659                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1660                    } else {
1661                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1662                                "IntentFilter verification with token:" + verificationId
1663                                + " was not said to be complete");
1664                    }
1665
1666                    break;
1667                }
1668            }
1669        }
1670    }
1671
1672    private StorageEventListener mStorageListener = new StorageEventListener() {
1673        @Override
1674        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1675            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1676                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1677                    final String volumeUuid = vol.getFsUuid();
1678
1679                    // Clean up any users or apps that were removed or recreated
1680                    // while this volume was missing
1681                    reconcileUsers(volumeUuid);
1682                    reconcileApps(volumeUuid);
1683
1684                    // Clean up any install sessions that expired or were
1685                    // cancelled while this volume was missing
1686                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1687
1688                    loadPrivatePackages(vol);
1689
1690                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1691                    unloadPrivatePackages(vol);
1692                }
1693            }
1694
1695            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1696                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1697                    updateExternalMediaStatus(true, false);
1698                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1699                    updateExternalMediaStatus(false, false);
1700                }
1701            }
1702        }
1703
1704        @Override
1705        public void onVolumeForgotten(String fsUuid) {
1706            if (TextUtils.isEmpty(fsUuid)) {
1707                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1708                return;
1709            }
1710
1711            // Remove any apps installed on the forgotten volume
1712            synchronized (mPackages) {
1713                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1714                for (PackageSetting ps : packages) {
1715                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1716                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1717                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1718                }
1719
1720                mSettings.onVolumeForgotten(fsUuid);
1721                mSettings.writeLPr();
1722            }
1723        }
1724    };
1725
1726    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1727            String[] grantedPermissions) {
1728        if (userId >= UserHandle.USER_OWNER) {
1729            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1730        } else if (userId == UserHandle.USER_ALL) {
1731            final int[] userIds;
1732            synchronized (mPackages) {
1733                userIds = UserManagerService.getInstance().getUserIds();
1734            }
1735            for (int someUserId : userIds) {
1736                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1737            }
1738        }
1739
1740        // We could have touched GID membership, so flush out packages.list
1741        synchronized (mPackages) {
1742            mSettings.writePackageListLPr();
1743        }
1744    }
1745
1746    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1747            String[] grantedPermissions) {
1748        SettingBase sb = (SettingBase) pkg.mExtras;
1749        if (sb == null) {
1750            return;
1751        }
1752
1753        PermissionsState permissionsState = sb.getPermissionsState();
1754
1755        for (String permission : pkg.requestedPermissions) {
1756            BasePermission bp = mSettings.mPermissions.get(permission);
1757            if (bp != null && bp.isRuntime() && (grantedPermissions == null
1758                    || ArrayUtils.contains(grantedPermissions, permission))) {
1759                permissionsState.grantRuntimePermission(bp, userId);
1760            }
1761        }
1762    }
1763
1764    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1765        Bundle extras = null;
1766        switch (res.returnCode) {
1767            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1768                extras = new Bundle();
1769                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1770                        res.origPermission);
1771                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1772                        res.origPackage);
1773                break;
1774            }
1775            case PackageManager.INSTALL_SUCCEEDED: {
1776                extras = new Bundle();
1777                extras.putBoolean(Intent.EXTRA_REPLACING,
1778                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1779                break;
1780            }
1781        }
1782        return extras;
1783    }
1784
1785    void scheduleWriteSettingsLocked() {
1786        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1787            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1788        }
1789    }
1790
1791    void scheduleWritePackageRestrictionsLocked(int userId) {
1792        if (!sUserManager.exists(userId)) return;
1793        mDirtyUsers.add(userId);
1794        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1795            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1796        }
1797    }
1798
1799    public static PackageManagerService main(Context context, Installer installer,
1800            boolean factoryTest, boolean onlyCore) {
1801        PackageManagerService m = new PackageManagerService(context, installer,
1802                factoryTest, onlyCore);
1803        ServiceManager.addService("package", m);
1804        return m;
1805    }
1806
1807    static String[] splitString(String str, char sep) {
1808        int count = 1;
1809        int i = 0;
1810        while ((i=str.indexOf(sep, i)) >= 0) {
1811            count++;
1812            i++;
1813        }
1814
1815        String[] res = new String[count];
1816        i=0;
1817        count = 0;
1818        int lastI=0;
1819        while ((i=str.indexOf(sep, i)) >= 0) {
1820            res[count] = str.substring(lastI, i);
1821            count++;
1822            i++;
1823            lastI = i;
1824        }
1825        res[count] = str.substring(lastI, str.length());
1826        return res;
1827    }
1828
1829    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1830        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1831                Context.DISPLAY_SERVICE);
1832        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1833    }
1834
1835    public PackageManagerService(Context context, Installer installer,
1836            boolean factoryTest, boolean onlyCore) {
1837        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1838                SystemClock.uptimeMillis());
1839
1840        if (mSdkVersion <= 0) {
1841            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1842        }
1843
1844        mContext = context;
1845        mFactoryTest = factoryTest;
1846        mOnlyCore = onlyCore;
1847        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1848        mMetrics = new DisplayMetrics();
1849        mSettings = new Settings(mPackages);
1850        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1851                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1852        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1853                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1854        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1855                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1856        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1857                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1858        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1859                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1860        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1861                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1862
1863        // TODO: add a property to control this?
1864        long dexOptLRUThresholdInMinutes;
1865        if (mLazyDexOpt) {
1866            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1867        } else {
1868            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1869        }
1870        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1871
1872        String separateProcesses = SystemProperties.get("debug.separate_processes");
1873        if (separateProcesses != null && separateProcesses.length() > 0) {
1874            if ("*".equals(separateProcesses)) {
1875                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1876                mSeparateProcesses = null;
1877                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1878            } else {
1879                mDefParseFlags = 0;
1880                mSeparateProcesses = separateProcesses.split(",");
1881                Slog.w(TAG, "Running with debug.separate_processes: "
1882                        + separateProcesses);
1883            }
1884        } else {
1885            mDefParseFlags = 0;
1886            mSeparateProcesses = null;
1887        }
1888
1889        mInstaller = installer;
1890        mPackageDexOptimizer = new PackageDexOptimizer(this);
1891        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1892
1893        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1894                FgThread.get().getLooper());
1895
1896        getDefaultDisplayMetrics(context, mMetrics);
1897
1898        SystemConfig systemConfig = SystemConfig.getInstance();
1899        mGlobalGids = systemConfig.getGlobalGids();
1900        mSystemPermissions = systemConfig.getSystemPermissions();
1901        mAvailableFeatures = systemConfig.getAvailableFeatures();
1902
1903        synchronized (mInstallLock) {
1904        // writer
1905        synchronized (mPackages) {
1906            mHandlerThread = new ServiceThread(TAG,
1907                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1908            mHandlerThread.start();
1909            mHandler = new PackageHandler(mHandlerThread.getLooper());
1910            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1911
1912            File dataDir = Environment.getDataDirectory();
1913            mAppDataDir = new File(dataDir, "data");
1914            mAppInstallDir = new File(dataDir, "app");
1915            mAppLib32InstallDir = new File(dataDir, "app-lib");
1916            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1917            mUserAppDataDir = new File(dataDir, "user");
1918            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1919
1920            sUserManager = new UserManagerService(context, this,
1921                    mInstallLock, mPackages);
1922
1923            // Propagate permission configuration in to package manager.
1924            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1925                    = systemConfig.getPermissions();
1926            for (int i=0; i<permConfig.size(); i++) {
1927                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1928                BasePermission bp = mSettings.mPermissions.get(perm.name);
1929                if (bp == null) {
1930                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1931                    mSettings.mPermissions.put(perm.name, bp);
1932                }
1933                if (perm.gids != null) {
1934                    bp.setGids(perm.gids, perm.perUser);
1935                }
1936            }
1937
1938            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1939            for (int i=0; i<libConfig.size(); i++) {
1940                mSharedLibraries.put(libConfig.keyAt(i),
1941                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1942            }
1943
1944            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1945
1946            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
1947
1948            String customResolverActivity = Resources.getSystem().getString(
1949                    R.string.config_customResolverActivity);
1950            if (TextUtils.isEmpty(customResolverActivity)) {
1951                customResolverActivity = null;
1952            } else {
1953                mCustomResolverComponentName = ComponentName.unflattenFromString(
1954                        customResolverActivity);
1955            }
1956
1957            long startTime = SystemClock.uptimeMillis();
1958
1959            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1960                    startTime);
1961
1962            // Set flag to monitor and not change apk file paths when
1963            // scanning install directories.
1964            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1965
1966            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1967
1968            /**
1969             * Add everything in the in the boot class path to the
1970             * list of process files because dexopt will have been run
1971             * if necessary during zygote startup.
1972             */
1973            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1974            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1975
1976            if (bootClassPath != null) {
1977                String[] bootClassPathElements = splitString(bootClassPath, ':');
1978                for (String element : bootClassPathElements) {
1979                    alreadyDexOpted.add(element);
1980                }
1981            } else {
1982                Slog.w(TAG, "No BOOTCLASSPATH found!");
1983            }
1984
1985            if (systemServerClassPath != null) {
1986                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1987                for (String element : systemServerClassPathElements) {
1988                    alreadyDexOpted.add(element);
1989                }
1990            } else {
1991                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1992            }
1993
1994            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1995            final String[] dexCodeInstructionSets =
1996                    getDexCodeInstructionSets(
1997                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1998
1999            /**
2000             * Ensure all external libraries have had dexopt run on them.
2001             */
2002            if (mSharedLibraries.size() > 0) {
2003                // NOTE: For now, we're compiling these system "shared libraries"
2004                // (and framework jars) into all available architectures. It's possible
2005                // to compile them only when we come across an app that uses them (there's
2006                // already logic for that in scanPackageLI) but that adds some complexity.
2007                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2008                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2009                        final String lib = libEntry.path;
2010                        if (lib == null) {
2011                            continue;
2012                        }
2013
2014                        try {
2015                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2016                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2017                                alreadyDexOpted.add(lib);
2018                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2019                            }
2020                        } catch (FileNotFoundException e) {
2021                            Slog.w(TAG, "Library not found: " + lib);
2022                        } catch (IOException e) {
2023                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2024                                    + e.getMessage());
2025                        }
2026                    }
2027                }
2028            }
2029
2030            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2031
2032            // Gross hack for now: we know this file doesn't contain any
2033            // code, so don't dexopt it to avoid the resulting log spew.
2034            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
2035
2036            // Gross hack for now: we know this file is only part of
2037            // the boot class path for art, so don't dexopt it to
2038            // avoid the resulting log spew.
2039            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
2040
2041            /**
2042             * There are a number of commands implemented in Java, which
2043             * we currently need to do the dexopt on so that they can be
2044             * run from a non-root shell.
2045             */
2046            String[] frameworkFiles = frameworkDir.list();
2047            if (frameworkFiles != null) {
2048                // TODO: We could compile these only for the most preferred ABI. We should
2049                // first double check that the dex files for these commands are not referenced
2050                // by other system apps.
2051                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2052                    for (int i=0; i<frameworkFiles.length; i++) {
2053                        File libPath = new File(frameworkDir, frameworkFiles[i]);
2054                        String path = libPath.getPath();
2055                        // Skip the file if we already did it.
2056                        if (alreadyDexOpted.contains(path)) {
2057                            continue;
2058                        }
2059                        // Skip the file if it is not a type we want to dexopt.
2060                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2061                            continue;
2062                        }
2063                        try {
2064                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2065                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2066                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2067                            }
2068                        } catch (FileNotFoundException e) {
2069                            Slog.w(TAG, "Jar not found: " + path);
2070                        } catch (IOException e) {
2071                            Slog.w(TAG, "Exception reading jar: " + path, e);
2072                        }
2073                    }
2074                }
2075            }
2076
2077            final VersionInfo ver = mSettings.getInternalVersion();
2078            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2079            // when upgrading from pre-M, promote system app permissions from install to runtime
2080            mPromoteSystemApps =
2081                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2082
2083            // save off the names of pre-existing system packages prior to scanning; we don't
2084            // want to automatically grant runtime permissions for new system apps
2085            if (mPromoteSystemApps) {
2086                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2087                while (pkgSettingIter.hasNext()) {
2088                    PackageSetting ps = pkgSettingIter.next();
2089                    if (isSystemApp(ps)) {
2090                        mExistingSystemPackages.add(ps.name);
2091                    }
2092                }
2093            }
2094
2095            // Collect vendor overlay packages.
2096            // (Do this before scanning any apps.)
2097            // For security and version matching reason, only consider
2098            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2099            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2100            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2101                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2102
2103            // Find base frameworks (resource packages without code).
2104            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2105                    | PackageParser.PARSE_IS_SYSTEM_DIR
2106                    | PackageParser.PARSE_IS_PRIVILEGED,
2107                    scanFlags | SCAN_NO_DEX, 0);
2108
2109            // Collected privileged system packages.
2110            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2111            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2112                    | PackageParser.PARSE_IS_SYSTEM_DIR
2113                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2114
2115            // Collect ordinary system packages.
2116            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2117            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2118                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2119
2120            // Collect all vendor packages.
2121            File vendorAppDir = new File("/vendor/app");
2122            try {
2123                vendorAppDir = vendorAppDir.getCanonicalFile();
2124            } catch (IOException e) {
2125                // failed to look up canonical path, continue with original one
2126            }
2127            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2128                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2129
2130            // Collect all OEM packages.
2131            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2132            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2133                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2134
2135            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2136            mInstaller.moveFiles();
2137
2138            // Prune any system packages that no longer exist.
2139            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2140            if (!mOnlyCore) {
2141                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2142                while (psit.hasNext()) {
2143                    PackageSetting ps = psit.next();
2144
2145                    /*
2146                     * If this is not a system app, it can't be a
2147                     * disable system app.
2148                     */
2149                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2150                        continue;
2151                    }
2152
2153                    /*
2154                     * If the package is scanned, it's not erased.
2155                     */
2156                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2157                    if (scannedPkg != null) {
2158                        /*
2159                         * If the system app is both scanned and in the
2160                         * disabled packages list, then it must have been
2161                         * added via OTA. Remove it from the currently
2162                         * scanned package so the previously user-installed
2163                         * application can be scanned.
2164                         */
2165                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2166                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2167                                    + ps.name + "; removing system app.  Last known codePath="
2168                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2169                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2170                                    + scannedPkg.mVersionCode);
2171                            removePackageLI(ps, true);
2172                            mExpectingBetter.put(ps.name, ps.codePath);
2173                        }
2174
2175                        continue;
2176                    }
2177
2178                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2179                        psit.remove();
2180                        logCriticalInfo(Log.WARN, "System package " + ps.name
2181                                + " no longer exists; wiping its data");
2182                        removeDataDirsLI(null, ps.name);
2183                    } else {
2184                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2185                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2186                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2187                        }
2188                    }
2189                }
2190            }
2191
2192            //look for any incomplete package installations
2193            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2194            //clean up list
2195            for(int i = 0; i < deletePkgsList.size(); i++) {
2196                //clean up here
2197                cleanupInstallFailedPackage(deletePkgsList.get(i));
2198            }
2199            //delete tmp files
2200            deleteTempPackageFiles();
2201
2202            // Remove any shared userIDs that have no associated packages
2203            mSettings.pruneSharedUsersLPw();
2204
2205            if (!mOnlyCore) {
2206                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2207                        SystemClock.uptimeMillis());
2208                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2209
2210                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2211                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2212
2213                /**
2214                 * Remove disable package settings for any updated system
2215                 * apps that were removed via an OTA. If they're not a
2216                 * previously-updated app, remove them completely.
2217                 * Otherwise, just revoke their system-level permissions.
2218                 */
2219                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2220                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2221                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2222
2223                    String msg;
2224                    if (deletedPkg == null) {
2225                        msg = "Updated system package " + deletedAppName
2226                                + " no longer exists; wiping its data";
2227                        removeDataDirsLI(null, deletedAppName);
2228                    } else {
2229                        msg = "Updated system app + " + deletedAppName
2230                                + " no longer present; removing system privileges for "
2231                                + deletedAppName;
2232
2233                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2234
2235                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2236                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2237                    }
2238                    logCriticalInfo(Log.WARN, msg);
2239                }
2240
2241                /**
2242                 * Make sure all system apps that we expected to appear on
2243                 * the userdata partition actually showed up. If they never
2244                 * appeared, crawl back and revive the system version.
2245                 */
2246                for (int i = 0; i < mExpectingBetter.size(); i++) {
2247                    final String packageName = mExpectingBetter.keyAt(i);
2248                    if (!mPackages.containsKey(packageName)) {
2249                        final File scanFile = mExpectingBetter.valueAt(i);
2250
2251                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2252                                + " but never showed up; reverting to system");
2253
2254                        final int reparseFlags;
2255                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2256                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2257                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2258                                    | PackageParser.PARSE_IS_PRIVILEGED;
2259                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2260                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2261                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2262                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2263                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2264                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2265                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2266                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2267                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2268                        } else {
2269                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2270                            continue;
2271                        }
2272
2273                        mSettings.enableSystemPackageLPw(packageName);
2274
2275                        try {
2276                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2277                        } catch (PackageManagerException e) {
2278                            Slog.e(TAG, "Failed to parse original system package: "
2279                                    + e.getMessage());
2280                        }
2281                    }
2282                }
2283            }
2284            mExpectingBetter.clear();
2285
2286            // Now that we know all of the shared libraries, update all clients to have
2287            // the correct library paths.
2288            updateAllSharedLibrariesLPw();
2289
2290            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2291                // NOTE: We ignore potential failures here during a system scan (like
2292                // the rest of the commands above) because there's precious little we
2293                // can do about it. A settings error is reported, though.
2294                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2295                        false /* force dexopt */, false /* defer dexopt */);
2296            }
2297
2298            // Now that we know all the packages we are keeping,
2299            // read and update their last usage times.
2300            mPackageUsage.readLP();
2301
2302            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2303                    SystemClock.uptimeMillis());
2304            Slog.i(TAG, "Time to scan packages: "
2305                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2306                    + " seconds");
2307
2308            // If the platform SDK has changed since the last time we booted,
2309            // we need to re-grant app permission to catch any new ones that
2310            // appear.  This is really a hack, and means that apps can in some
2311            // cases get permissions that the user didn't initially explicitly
2312            // allow...  it would be nice to have some better way to handle
2313            // this situation.
2314            int updateFlags = UPDATE_PERMISSIONS_ALL;
2315            if (ver.sdkVersion != mSdkVersion) {
2316                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2317                        + mSdkVersion + "; regranting permissions for internal storage");
2318                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2319            }
2320            updatePermissionsLPw(null, null, updateFlags);
2321            ver.sdkVersion = mSdkVersion;
2322            // clear only after permissions have been updated
2323            mExistingSystemPackages.clear();
2324            mPromoteSystemApps = false;
2325
2326            // If this is the first boot, and it is a normal boot, then
2327            // we need to initialize the default preferred apps.
2328            if (!mRestoredSettings && !onlyCore) {
2329                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2330                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2331                primeDomainVerificationsLPw(UserHandle.USER_OWNER);
2332            }
2333
2334            // If this is first boot after an OTA, and a normal boot, then
2335            // we need to clear code cache directories.
2336            if (mIsUpgrade && !onlyCore) {
2337                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2338                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2339                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2340                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2341                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2342                    }
2343                }
2344                ver.fingerprint = Build.FINGERPRINT;
2345            }
2346
2347            checkDefaultBrowser();
2348
2349            // All the changes are done during package scanning.
2350            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2351
2352            // can downgrade to reader
2353            mSettings.writeLPr();
2354
2355            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2356                    SystemClock.uptimeMillis());
2357
2358            mRequiredVerifierPackage = getRequiredVerifierLPr();
2359            mRequiredInstallerPackage = getRequiredInstallerLPr();
2360
2361            mInstallerService = new PackageInstallerService(context, this);
2362
2363            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2364            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2365                    mIntentFilterVerifierComponent);
2366
2367        } // synchronized (mPackages)
2368        } // synchronized (mInstallLock)
2369
2370        // Now after opening every single application zip, make sure they
2371        // are all flushed.  Not really needed, but keeps things nice and
2372        // tidy.
2373        Runtime.getRuntime().gc();
2374
2375        // Expose private service for system components to use.
2376        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2377    }
2378
2379    @Override
2380    public boolean isFirstBoot() {
2381        return !mRestoredSettings;
2382    }
2383
2384    @Override
2385    public boolean isOnlyCoreApps() {
2386        return mOnlyCore;
2387    }
2388
2389    @Override
2390    public boolean isUpgrade() {
2391        return mIsUpgrade;
2392    }
2393
2394    private String getRequiredVerifierLPr() {
2395        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2396        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2397                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2398
2399        String requiredVerifier = null;
2400
2401        final int N = receivers.size();
2402        for (int i = 0; i < N; i++) {
2403            final ResolveInfo info = receivers.get(i);
2404
2405            if (info.activityInfo == null) {
2406                continue;
2407            }
2408
2409            final String packageName = info.activityInfo.packageName;
2410
2411            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2412                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2413                continue;
2414            }
2415
2416            if (requiredVerifier != null) {
2417                throw new RuntimeException("There can be only one required verifier");
2418            }
2419
2420            requiredVerifier = packageName;
2421        }
2422
2423        return requiredVerifier;
2424    }
2425
2426    private String getRequiredInstallerLPr() {
2427        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2428        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2429        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2430
2431        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2432                PACKAGE_MIME_TYPE, 0, 0);
2433
2434        String requiredInstaller = null;
2435
2436        final int N = installers.size();
2437        for (int i = 0; i < N; i++) {
2438            final ResolveInfo info = installers.get(i);
2439            final String packageName = info.activityInfo.packageName;
2440
2441            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2442                continue;
2443            }
2444
2445            if (requiredInstaller != null) {
2446                throw new RuntimeException("There must be one required installer");
2447            }
2448
2449            requiredInstaller = packageName;
2450        }
2451
2452        if (requiredInstaller == null) {
2453            throw new RuntimeException("There must be one required installer");
2454        }
2455
2456        return requiredInstaller;
2457    }
2458
2459    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2460        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2461        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2462                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2463
2464        ComponentName verifierComponentName = null;
2465
2466        int priority = -1000;
2467        final int N = receivers.size();
2468        for (int i = 0; i < N; i++) {
2469            final ResolveInfo info = receivers.get(i);
2470
2471            if (info.activityInfo == null) {
2472                continue;
2473            }
2474
2475            final String packageName = info.activityInfo.packageName;
2476
2477            final PackageSetting ps = mSettings.mPackages.get(packageName);
2478            if (ps == null) {
2479                continue;
2480            }
2481
2482            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2483                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2484                continue;
2485            }
2486
2487            // Select the IntentFilterVerifier with the highest priority
2488            if (priority < info.priority) {
2489                priority = info.priority;
2490                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2491                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2492                        + verifierComponentName + " with priority: " + info.priority);
2493            }
2494        }
2495
2496        return verifierComponentName;
2497    }
2498
2499    private void primeDomainVerificationsLPw(int userId) {
2500        if (DEBUG_DOMAIN_VERIFICATION) {
2501            Slog.d(TAG, "Priming domain verifications in user " + userId);
2502        }
2503
2504        SystemConfig systemConfig = SystemConfig.getInstance();
2505        ArraySet<String> packages = systemConfig.getLinkedApps();
2506        ArraySet<String> domains = new ArraySet<String>();
2507
2508        for (String packageName : packages) {
2509            PackageParser.Package pkg = mPackages.get(packageName);
2510            if (pkg != null) {
2511                if (!pkg.isSystemApp()) {
2512                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2513                    continue;
2514                }
2515
2516                domains.clear();
2517                for (PackageParser.Activity a : pkg.activities) {
2518                    for (ActivityIntentInfo filter : a.intents) {
2519                        if (hasValidDomains(filter)) {
2520                            domains.addAll(filter.getHostsList());
2521                        }
2522                    }
2523                }
2524
2525                if (domains.size() > 0) {
2526                    if (DEBUG_DOMAIN_VERIFICATION) {
2527                        Slog.v(TAG, "      + " + packageName);
2528                    }
2529                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2530                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2531                    // and then 'always' in the per-user state actually used for intent resolution.
2532                    final IntentFilterVerificationInfo ivi;
2533                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2534                            new ArrayList<String>(domains));
2535                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2536                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2537                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2538                } else {
2539                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2540                            + "' does not handle web links");
2541                }
2542            } else {
2543                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2544            }
2545        }
2546
2547        scheduleWritePackageRestrictionsLocked(userId);
2548        scheduleWriteSettingsLocked();
2549    }
2550
2551    private void applyFactoryDefaultBrowserLPw(int userId) {
2552        // The default browser app's package name is stored in a string resource,
2553        // with a product-specific overlay used for vendor customization.
2554        String browserPkg = mContext.getResources().getString(
2555                com.android.internal.R.string.default_browser);
2556        if (!TextUtils.isEmpty(browserPkg)) {
2557            // non-empty string => required to be a known package
2558            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2559            if (ps == null) {
2560                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2561                browserPkg = null;
2562            } else {
2563                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2564            }
2565        }
2566
2567        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2568        // default.  If there's more than one, just leave everything alone.
2569        if (browserPkg == null) {
2570            calculateDefaultBrowserLPw(userId);
2571        }
2572    }
2573
2574    private void calculateDefaultBrowserLPw(int userId) {
2575        List<String> allBrowsers = resolveAllBrowserApps(userId);
2576        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2577        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2578    }
2579
2580    private List<String> resolveAllBrowserApps(int userId) {
2581        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2582        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2583                PackageManager.MATCH_ALL, userId);
2584
2585        final int count = list.size();
2586        List<String> result = new ArrayList<String>(count);
2587        for (int i=0; i<count; i++) {
2588            ResolveInfo info = list.get(i);
2589            if (info.activityInfo == null
2590                    || !info.handleAllWebDataURI
2591                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2592                    || result.contains(info.activityInfo.packageName)) {
2593                continue;
2594            }
2595            result.add(info.activityInfo.packageName);
2596        }
2597
2598        return result;
2599    }
2600
2601    private boolean packageIsBrowser(String packageName, int userId) {
2602        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2603                PackageManager.MATCH_ALL, userId);
2604        final int N = list.size();
2605        for (int i = 0; i < N; i++) {
2606            ResolveInfo info = list.get(i);
2607            if (packageName.equals(info.activityInfo.packageName)) {
2608                return true;
2609            }
2610        }
2611        return false;
2612    }
2613
2614    private void checkDefaultBrowser() {
2615        final int myUserId = UserHandle.myUserId();
2616        final String packageName = getDefaultBrowserPackageName(myUserId);
2617        if (packageName != null) {
2618            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2619            if (info == null) {
2620                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2621                synchronized (mPackages) {
2622                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2623                }
2624            }
2625        }
2626    }
2627
2628    @Override
2629    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2630            throws RemoteException {
2631        try {
2632            return super.onTransact(code, data, reply, flags);
2633        } catch (RuntimeException e) {
2634            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2635                Slog.wtf(TAG, "Package Manager Crash", e);
2636            }
2637            throw e;
2638        }
2639    }
2640
2641    void cleanupInstallFailedPackage(PackageSetting ps) {
2642        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2643
2644        removeDataDirsLI(ps.volumeUuid, ps.name);
2645        if (ps.codePath != null) {
2646            if (ps.codePath.isDirectory()) {
2647                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2648            } else {
2649                ps.codePath.delete();
2650            }
2651        }
2652        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2653            if (ps.resourcePath.isDirectory()) {
2654                FileUtils.deleteContents(ps.resourcePath);
2655            }
2656            ps.resourcePath.delete();
2657        }
2658        mSettings.removePackageLPw(ps.name);
2659    }
2660
2661    static int[] appendInts(int[] cur, int[] add) {
2662        if (add == null) return cur;
2663        if (cur == null) return add;
2664        final int N = add.length;
2665        for (int i=0; i<N; i++) {
2666            cur = appendInt(cur, add[i]);
2667        }
2668        return cur;
2669    }
2670
2671    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2672        if (!sUserManager.exists(userId)) return null;
2673        final PackageSetting ps = (PackageSetting) p.mExtras;
2674        if (ps == null) {
2675            return null;
2676        }
2677
2678        final PermissionsState permissionsState = ps.getPermissionsState();
2679
2680        final int[] gids = permissionsState.computeGids(userId);
2681        final Set<String> permissions = permissionsState.getPermissions(userId);
2682        final PackageUserState state = ps.readUserState(userId);
2683
2684        return PackageParser.generatePackageInfo(p, gids, flags,
2685                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2686    }
2687
2688    @Override
2689    public boolean isPackageFrozen(String packageName) {
2690        synchronized (mPackages) {
2691            final PackageSetting ps = mSettings.mPackages.get(packageName);
2692            if (ps != null) {
2693                return ps.frozen;
2694            }
2695        }
2696        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2697        return true;
2698    }
2699
2700    @Override
2701    public boolean isPackageAvailable(String packageName, int userId) {
2702        if (!sUserManager.exists(userId)) return false;
2703        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2704        synchronized (mPackages) {
2705            PackageParser.Package p = mPackages.get(packageName);
2706            if (p != null) {
2707                final PackageSetting ps = (PackageSetting) p.mExtras;
2708                if (ps != null) {
2709                    final PackageUserState state = ps.readUserState(userId);
2710                    if (state != null) {
2711                        return PackageParser.isAvailable(state);
2712                    }
2713                }
2714            }
2715        }
2716        return false;
2717    }
2718
2719    @Override
2720    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2721        if (!sUserManager.exists(userId)) return null;
2722        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2723        // reader
2724        synchronized (mPackages) {
2725            PackageParser.Package p = mPackages.get(packageName);
2726            if (DEBUG_PACKAGE_INFO)
2727                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2728            if (p != null) {
2729                return generatePackageInfo(p, flags, userId);
2730            }
2731            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2732                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2733            }
2734        }
2735        return null;
2736    }
2737
2738    @Override
2739    public String[] currentToCanonicalPackageNames(String[] names) {
2740        String[] out = new String[names.length];
2741        // reader
2742        synchronized (mPackages) {
2743            for (int i=names.length-1; i>=0; i--) {
2744                PackageSetting ps = mSettings.mPackages.get(names[i]);
2745                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2746            }
2747        }
2748        return out;
2749    }
2750
2751    @Override
2752    public String[] canonicalToCurrentPackageNames(String[] names) {
2753        String[] out = new String[names.length];
2754        // reader
2755        synchronized (mPackages) {
2756            for (int i=names.length-1; i>=0; i--) {
2757                String cur = mSettings.mRenamedPackages.get(names[i]);
2758                out[i] = cur != null ? cur : names[i];
2759            }
2760        }
2761        return out;
2762    }
2763
2764    @Override
2765    public int getPackageUid(String packageName, int userId) {
2766        if (!sUserManager.exists(userId)) return -1;
2767        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2768
2769        // reader
2770        synchronized (mPackages) {
2771            PackageParser.Package p = mPackages.get(packageName);
2772            if(p != null) {
2773                return UserHandle.getUid(userId, p.applicationInfo.uid);
2774            }
2775            PackageSetting ps = mSettings.mPackages.get(packageName);
2776            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2777                return -1;
2778            }
2779            p = ps.pkg;
2780            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2781        }
2782    }
2783
2784    @Override
2785    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2786        if (!sUserManager.exists(userId)) {
2787            return null;
2788        }
2789
2790        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2791                "getPackageGids");
2792
2793        // reader
2794        synchronized (mPackages) {
2795            PackageParser.Package p = mPackages.get(packageName);
2796            if (DEBUG_PACKAGE_INFO) {
2797                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2798            }
2799            if (p != null) {
2800                PackageSetting ps = (PackageSetting) p.mExtras;
2801                return ps.getPermissionsState().computeGids(userId);
2802            }
2803        }
2804
2805        return null;
2806    }
2807
2808    static PermissionInfo generatePermissionInfo(
2809            BasePermission bp, int flags) {
2810        if (bp.perm != null) {
2811            return PackageParser.generatePermissionInfo(bp.perm, flags);
2812        }
2813        PermissionInfo pi = new PermissionInfo();
2814        pi.name = bp.name;
2815        pi.packageName = bp.sourcePackage;
2816        pi.nonLocalizedLabel = bp.name;
2817        pi.protectionLevel = bp.protectionLevel;
2818        return pi;
2819    }
2820
2821    @Override
2822    public PermissionInfo getPermissionInfo(String name, int flags) {
2823        // reader
2824        synchronized (mPackages) {
2825            final BasePermission p = mSettings.mPermissions.get(name);
2826            if (p != null) {
2827                return generatePermissionInfo(p, flags);
2828            }
2829            return null;
2830        }
2831    }
2832
2833    @Override
2834    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2835        // reader
2836        synchronized (mPackages) {
2837            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2838            for (BasePermission p : mSettings.mPermissions.values()) {
2839                if (group == null) {
2840                    if (p.perm == null || p.perm.info.group == null) {
2841                        out.add(generatePermissionInfo(p, flags));
2842                    }
2843                } else {
2844                    if (p.perm != null && group.equals(p.perm.info.group)) {
2845                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2846                    }
2847                }
2848            }
2849
2850            if (out.size() > 0) {
2851                return out;
2852            }
2853            return mPermissionGroups.containsKey(group) ? out : null;
2854        }
2855    }
2856
2857    @Override
2858    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2859        // reader
2860        synchronized (mPackages) {
2861            return PackageParser.generatePermissionGroupInfo(
2862                    mPermissionGroups.get(name), flags);
2863        }
2864    }
2865
2866    @Override
2867    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2868        // reader
2869        synchronized (mPackages) {
2870            final int N = mPermissionGroups.size();
2871            ArrayList<PermissionGroupInfo> out
2872                    = new ArrayList<PermissionGroupInfo>(N);
2873            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2874                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2875            }
2876            return out;
2877        }
2878    }
2879
2880    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2881            int userId) {
2882        if (!sUserManager.exists(userId)) return null;
2883        PackageSetting ps = mSettings.mPackages.get(packageName);
2884        if (ps != null) {
2885            if (ps.pkg == null) {
2886                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2887                        flags, userId);
2888                if (pInfo != null) {
2889                    return pInfo.applicationInfo;
2890                }
2891                return null;
2892            }
2893            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2894                    ps.readUserState(userId), userId);
2895        }
2896        return null;
2897    }
2898
2899    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2900            int userId) {
2901        if (!sUserManager.exists(userId)) return null;
2902        PackageSetting ps = mSettings.mPackages.get(packageName);
2903        if (ps != null) {
2904            PackageParser.Package pkg = ps.pkg;
2905            if (pkg == null) {
2906                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2907                    return null;
2908                }
2909                // Only data remains, so we aren't worried about code paths
2910                pkg = new PackageParser.Package(packageName);
2911                pkg.applicationInfo.packageName = packageName;
2912                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2913                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2914                pkg.applicationInfo.dataDir = Environment
2915                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2916                        .getAbsolutePath();
2917                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2918                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2919            }
2920            return generatePackageInfo(pkg, flags, userId);
2921        }
2922        return null;
2923    }
2924
2925    @Override
2926    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2927        if (!sUserManager.exists(userId)) return null;
2928        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2929        // writer
2930        synchronized (mPackages) {
2931            PackageParser.Package p = mPackages.get(packageName);
2932            if (DEBUG_PACKAGE_INFO) Log.v(
2933                    TAG, "getApplicationInfo " + packageName
2934                    + ": " + p);
2935            if (p != null) {
2936                PackageSetting ps = mSettings.mPackages.get(packageName);
2937                if (ps == null) return null;
2938                // Note: isEnabledLP() does not apply here - always return info
2939                return PackageParser.generateApplicationInfo(
2940                        p, flags, ps.readUserState(userId), userId);
2941            }
2942            if ("android".equals(packageName)||"system".equals(packageName)) {
2943                return mAndroidApplication;
2944            }
2945            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2946                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2947            }
2948        }
2949        return null;
2950    }
2951
2952    @Override
2953    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2954            final IPackageDataObserver observer) {
2955        mContext.enforceCallingOrSelfPermission(
2956                android.Manifest.permission.CLEAR_APP_CACHE, null);
2957        // Queue up an async operation since clearing cache may take a little while.
2958        mHandler.post(new Runnable() {
2959            public void run() {
2960                mHandler.removeCallbacks(this);
2961                int retCode = -1;
2962                synchronized (mInstallLock) {
2963                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2964                    if (retCode < 0) {
2965                        Slog.w(TAG, "Couldn't clear application caches");
2966                    }
2967                }
2968                if (observer != null) {
2969                    try {
2970                        observer.onRemoveCompleted(null, (retCode >= 0));
2971                    } catch (RemoteException e) {
2972                        Slog.w(TAG, "RemoveException when invoking call back");
2973                    }
2974                }
2975            }
2976        });
2977    }
2978
2979    @Override
2980    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2981            final IntentSender pi) {
2982        mContext.enforceCallingOrSelfPermission(
2983                android.Manifest.permission.CLEAR_APP_CACHE, null);
2984        // Queue up an async operation since clearing cache may take a little while.
2985        mHandler.post(new Runnable() {
2986            public void run() {
2987                mHandler.removeCallbacks(this);
2988                int retCode = -1;
2989                synchronized (mInstallLock) {
2990                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2991                    if (retCode < 0) {
2992                        Slog.w(TAG, "Couldn't clear application caches");
2993                    }
2994                }
2995                if(pi != null) {
2996                    try {
2997                        // Callback via pending intent
2998                        int code = (retCode >= 0) ? 1 : 0;
2999                        pi.sendIntent(null, code, null,
3000                                null, null);
3001                    } catch (SendIntentException e1) {
3002                        Slog.i(TAG, "Failed to send pending intent");
3003                    }
3004                }
3005            }
3006        });
3007    }
3008
3009    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3010        synchronized (mInstallLock) {
3011            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3012                throw new IOException("Failed to free enough space");
3013            }
3014        }
3015    }
3016
3017    @Override
3018    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3019        if (!sUserManager.exists(userId)) return null;
3020        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3021        synchronized (mPackages) {
3022            PackageParser.Activity a = mActivities.mActivities.get(component);
3023
3024            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3025            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3026                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3027                if (ps == null) return null;
3028                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3029                        userId);
3030            }
3031            if (mResolveComponentName.equals(component)) {
3032                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3033                        new PackageUserState(), userId);
3034            }
3035        }
3036        return null;
3037    }
3038
3039    @Override
3040    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3041            String resolvedType) {
3042        synchronized (mPackages) {
3043            if (component.equals(mResolveComponentName)) {
3044                // The resolver supports EVERYTHING!
3045                return true;
3046            }
3047            PackageParser.Activity a = mActivities.mActivities.get(component);
3048            if (a == null) {
3049                return false;
3050            }
3051            for (int i=0; i<a.intents.size(); i++) {
3052                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3053                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3054                    return true;
3055                }
3056            }
3057            return false;
3058        }
3059    }
3060
3061    @Override
3062    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3063        if (!sUserManager.exists(userId)) return null;
3064        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3065        synchronized (mPackages) {
3066            PackageParser.Activity a = mReceivers.mActivities.get(component);
3067            if (DEBUG_PACKAGE_INFO) Log.v(
3068                TAG, "getReceiverInfo " + component + ": " + a);
3069            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3070                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3071                if (ps == null) return null;
3072                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3073                        userId);
3074            }
3075        }
3076        return null;
3077    }
3078
3079    @Override
3080    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3081        if (!sUserManager.exists(userId)) return null;
3082        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3083        synchronized (mPackages) {
3084            PackageParser.Service s = mServices.mServices.get(component);
3085            if (DEBUG_PACKAGE_INFO) Log.v(
3086                TAG, "getServiceInfo " + component + ": " + s);
3087            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3088                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3089                if (ps == null) return null;
3090                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3091                        userId);
3092            }
3093        }
3094        return null;
3095    }
3096
3097    @Override
3098    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3099        if (!sUserManager.exists(userId)) return null;
3100        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3101        synchronized (mPackages) {
3102            PackageParser.Provider p = mProviders.mProviders.get(component);
3103            if (DEBUG_PACKAGE_INFO) Log.v(
3104                TAG, "getProviderInfo " + component + ": " + p);
3105            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3106                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3107                if (ps == null) return null;
3108                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3109                        userId);
3110            }
3111        }
3112        return null;
3113    }
3114
3115    @Override
3116    public String[] getSystemSharedLibraryNames() {
3117        Set<String> libSet;
3118        synchronized (mPackages) {
3119            libSet = mSharedLibraries.keySet();
3120            int size = libSet.size();
3121            if (size > 0) {
3122                String[] libs = new String[size];
3123                libSet.toArray(libs);
3124                return libs;
3125            }
3126        }
3127        return null;
3128    }
3129
3130    /**
3131     * @hide
3132     */
3133    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3134        synchronized (mPackages) {
3135            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3136            if (lib != null && lib.apk != null) {
3137                return mPackages.get(lib.apk);
3138            }
3139        }
3140        return null;
3141    }
3142
3143    @Override
3144    public FeatureInfo[] getSystemAvailableFeatures() {
3145        Collection<FeatureInfo> featSet;
3146        synchronized (mPackages) {
3147            featSet = mAvailableFeatures.values();
3148            int size = featSet.size();
3149            if (size > 0) {
3150                FeatureInfo[] features = new FeatureInfo[size+1];
3151                featSet.toArray(features);
3152                FeatureInfo fi = new FeatureInfo();
3153                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3154                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3155                features[size] = fi;
3156                return features;
3157            }
3158        }
3159        return null;
3160    }
3161
3162    @Override
3163    public boolean hasSystemFeature(String name) {
3164        synchronized (mPackages) {
3165            return mAvailableFeatures.containsKey(name);
3166        }
3167    }
3168
3169    private void checkValidCaller(int uid, int userId) {
3170        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3171            return;
3172
3173        throw new SecurityException("Caller uid=" + uid
3174                + " is not privileged to communicate with user=" + userId);
3175    }
3176
3177    @Override
3178    public int checkPermission(String permName, String pkgName, int userId) {
3179        if (!sUserManager.exists(userId)) {
3180            return PackageManager.PERMISSION_DENIED;
3181        }
3182
3183        synchronized (mPackages) {
3184            final PackageParser.Package p = mPackages.get(pkgName);
3185            if (p != null && p.mExtras != null) {
3186                final PackageSetting ps = (PackageSetting) p.mExtras;
3187                final PermissionsState permissionsState = ps.getPermissionsState();
3188                if (permissionsState.hasPermission(permName, userId)) {
3189                    return PackageManager.PERMISSION_GRANTED;
3190                }
3191                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3192                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3193                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3194                    return PackageManager.PERMISSION_GRANTED;
3195                }
3196            }
3197        }
3198
3199        return PackageManager.PERMISSION_DENIED;
3200    }
3201
3202    @Override
3203    public int checkUidPermission(String permName, int uid) {
3204        final int userId = UserHandle.getUserId(uid);
3205
3206        if (!sUserManager.exists(userId)) {
3207            return PackageManager.PERMISSION_DENIED;
3208        }
3209
3210        synchronized (mPackages) {
3211            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3212            if (obj != null) {
3213                final SettingBase ps = (SettingBase) obj;
3214                final PermissionsState permissionsState = ps.getPermissionsState();
3215                if (permissionsState.hasPermission(permName, userId)) {
3216                    return PackageManager.PERMISSION_GRANTED;
3217                }
3218                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3219                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3220                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3221                    return PackageManager.PERMISSION_GRANTED;
3222                }
3223            } else {
3224                ArraySet<String> perms = mSystemPermissions.get(uid);
3225                if (perms != null) {
3226                    if (perms.contains(permName)) {
3227                        return PackageManager.PERMISSION_GRANTED;
3228                    }
3229                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3230                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3231                        return PackageManager.PERMISSION_GRANTED;
3232                    }
3233                }
3234            }
3235        }
3236
3237        return PackageManager.PERMISSION_DENIED;
3238    }
3239
3240    @Override
3241    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3242        if (UserHandle.getCallingUserId() != userId) {
3243            mContext.enforceCallingPermission(
3244                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3245                    "isPermissionRevokedByPolicy for user " + userId);
3246        }
3247
3248        if (checkPermission(permission, packageName, userId)
3249                == PackageManager.PERMISSION_GRANTED) {
3250            return false;
3251        }
3252
3253        final long identity = Binder.clearCallingIdentity();
3254        try {
3255            final int flags = getPermissionFlags(permission, packageName, userId);
3256            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3257        } finally {
3258            Binder.restoreCallingIdentity(identity);
3259        }
3260    }
3261
3262    @Override
3263    public String getPermissionControllerPackageName() {
3264        synchronized (mPackages) {
3265            return mRequiredInstallerPackage;
3266        }
3267    }
3268
3269    /**
3270     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3271     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3272     * @param checkShell TODO(yamasani):
3273     * @param message the message to log on security exception
3274     */
3275    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3276            boolean checkShell, String message) {
3277        if (userId < 0) {
3278            throw new IllegalArgumentException("Invalid userId " + userId);
3279        }
3280        if (checkShell) {
3281            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3282        }
3283        if (userId == UserHandle.getUserId(callingUid)) return;
3284        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3285            if (requireFullPermission) {
3286                mContext.enforceCallingOrSelfPermission(
3287                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3288            } else {
3289                try {
3290                    mContext.enforceCallingOrSelfPermission(
3291                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3292                } catch (SecurityException se) {
3293                    mContext.enforceCallingOrSelfPermission(
3294                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3295                }
3296            }
3297        }
3298    }
3299
3300    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3301        if (callingUid == Process.SHELL_UID) {
3302            if (userHandle >= 0
3303                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3304                throw new SecurityException("Shell does not have permission to access user "
3305                        + userHandle);
3306            } else if (userHandle < 0) {
3307                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3308                        + Debug.getCallers(3));
3309            }
3310        }
3311    }
3312
3313    private BasePermission findPermissionTreeLP(String permName) {
3314        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3315            if (permName.startsWith(bp.name) &&
3316                    permName.length() > bp.name.length() &&
3317                    permName.charAt(bp.name.length()) == '.') {
3318                return bp;
3319            }
3320        }
3321        return null;
3322    }
3323
3324    private BasePermission checkPermissionTreeLP(String permName) {
3325        if (permName != null) {
3326            BasePermission bp = findPermissionTreeLP(permName);
3327            if (bp != null) {
3328                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3329                    return bp;
3330                }
3331                throw new SecurityException("Calling uid "
3332                        + Binder.getCallingUid()
3333                        + " is not allowed to add to permission tree "
3334                        + bp.name + " owned by uid " + bp.uid);
3335            }
3336        }
3337        throw new SecurityException("No permission tree found for " + permName);
3338    }
3339
3340    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3341        if (s1 == null) {
3342            return s2 == null;
3343        }
3344        if (s2 == null) {
3345            return false;
3346        }
3347        if (s1.getClass() != s2.getClass()) {
3348            return false;
3349        }
3350        return s1.equals(s2);
3351    }
3352
3353    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3354        if (pi1.icon != pi2.icon) return false;
3355        if (pi1.logo != pi2.logo) return false;
3356        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3357        if (!compareStrings(pi1.name, pi2.name)) return false;
3358        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3359        // We'll take care of setting this one.
3360        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3361        // These are not currently stored in settings.
3362        //if (!compareStrings(pi1.group, pi2.group)) return false;
3363        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3364        //if (pi1.labelRes != pi2.labelRes) return false;
3365        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3366        return true;
3367    }
3368
3369    int permissionInfoFootprint(PermissionInfo info) {
3370        int size = info.name.length();
3371        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3372        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3373        return size;
3374    }
3375
3376    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3377        int size = 0;
3378        for (BasePermission perm : mSettings.mPermissions.values()) {
3379            if (perm.uid == tree.uid) {
3380                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3381            }
3382        }
3383        return size;
3384    }
3385
3386    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3387        // We calculate the max size of permissions defined by this uid and throw
3388        // if that plus the size of 'info' would exceed our stated maximum.
3389        if (tree.uid != Process.SYSTEM_UID) {
3390            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3391            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3392                throw new SecurityException("Permission tree size cap exceeded");
3393            }
3394        }
3395    }
3396
3397    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3398        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3399            throw new SecurityException("Label must be specified in permission");
3400        }
3401        BasePermission tree = checkPermissionTreeLP(info.name);
3402        BasePermission bp = mSettings.mPermissions.get(info.name);
3403        boolean added = bp == null;
3404        boolean changed = true;
3405        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3406        if (added) {
3407            enforcePermissionCapLocked(info, tree);
3408            bp = new BasePermission(info.name, tree.sourcePackage,
3409                    BasePermission.TYPE_DYNAMIC);
3410        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3411            throw new SecurityException(
3412                    "Not allowed to modify non-dynamic permission "
3413                    + info.name);
3414        } else {
3415            if (bp.protectionLevel == fixedLevel
3416                    && bp.perm.owner.equals(tree.perm.owner)
3417                    && bp.uid == tree.uid
3418                    && comparePermissionInfos(bp.perm.info, info)) {
3419                changed = false;
3420            }
3421        }
3422        bp.protectionLevel = fixedLevel;
3423        info = new PermissionInfo(info);
3424        info.protectionLevel = fixedLevel;
3425        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3426        bp.perm.info.packageName = tree.perm.info.packageName;
3427        bp.uid = tree.uid;
3428        if (added) {
3429            mSettings.mPermissions.put(info.name, bp);
3430        }
3431        if (changed) {
3432            if (!async) {
3433                mSettings.writeLPr();
3434            } else {
3435                scheduleWriteSettingsLocked();
3436            }
3437        }
3438        return added;
3439    }
3440
3441    @Override
3442    public boolean addPermission(PermissionInfo info) {
3443        synchronized (mPackages) {
3444            return addPermissionLocked(info, false);
3445        }
3446    }
3447
3448    @Override
3449    public boolean addPermissionAsync(PermissionInfo info) {
3450        synchronized (mPackages) {
3451            return addPermissionLocked(info, true);
3452        }
3453    }
3454
3455    @Override
3456    public void removePermission(String name) {
3457        synchronized (mPackages) {
3458            checkPermissionTreeLP(name);
3459            BasePermission bp = mSettings.mPermissions.get(name);
3460            if (bp != null) {
3461                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3462                    throw new SecurityException(
3463                            "Not allowed to modify non-dynamic permission "
3464                            + name);
3465                }
3466                mSettings.mPermissions.remove(name);
3467                mSettings.writeLPr();
3468            }
3469        }
3470    }
3471
3472    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3473            BasePermission bp) {
3474        int index = pkg.requestedPermissions.indexOf(bp.name);
3475        if (index == -1) {
3476            throw new SecurityException("Package " + pkg.packageName
3477                    + " has not requested permission " + bp.name);
3478        }
3479        if (!bp.isRuntime() && !bp.isDevelopment()) {
3480            throw new SecurityException("Permission " + bp.name
3481                    + " is not a changeable permission type");
3482        }
3483    }
3484
3485    @Override
3486    public void grantRuntimePermission(String packageName, String name, final int userId) {
3487        if (!sUserManager.exists(userId)) {
3488            Log.e(TAG, "No such user:" + userId);
3489            return;
3490        }
3491
3492        mContext.enforceCallingOrSelfPermission(
3493                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3494                "grantRuntimePermission");
3495
3496        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3497                "grantRuntimePermission");
3498
3499        final int uid;
3500        final SettingBase sb;
3501
3502        synchronized (mPackages) {
3503            final PackageParser.Package pkg = mPackages.get(packageName);
3504            if (pkg == null) {
3505                throw new IllegalArgumentException("Unknown package: " + packageName);
3506            }
3507
3508            final BasePermission bp = mSettings.mPermissions.get(name);
3509            if (bp == null) {
3510                throw new IllegalArgumentException("Unknown permission: " + name);
3511            }
3512
3513            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3514
3515            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3516            sb = (SettingBase) pkg.mExtras;
3517            if (sb == null) {
3518                throw new IllegalArgumentException("Unknown package: " + packageName);
3519            }
3520
3521            final PermissionsState permissionsState = sb.getPermissionsState();
3522
3523            final int flags = permissionsState.getPermissionFlags(name, userId);
3524            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3525                throw new SecurityException("Cannot grant system fixed permission: "
3526                        + name + " for package: " + packageName);
3527            }
3528
3529            if (bp.isDevelopment()) {
3530                // Development permissions must be handled specially, since they are not
3531                // normal runtime permissions.  For now they apply to all users.
3532                if (permissionsState.grantInstallPermission(bp) !=
3533                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3534                    scheduleWriteSettingsLocked();
3535                }
3536                return;
3537            }
3538
3539            final int result = permissionsState.grantRuntimePermission(bp, userId);
3540            switch (result) {
3541                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3542                    return;
3543                }
3544
3545                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3546                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3547                    mHandler.post(new Runnable() {
3548                        @Override
3549                        public void run() {
3550                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3551                        }
3552                    });
3553                } break;
3554            }
3555
3556            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3557
3558            // Not critical if that is lost - app has to request again.
3559            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3560        }
3561
3562        // Only need to do this if user is initialized. Otherwise it's a new user
3563        // and there are no processes running as the user yet and there's no need
3564        // to make an expensive call to remount processes for the changed permissions.
3565        if (READ_EXTERNAL_STORAGE.equals(name)
3566                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3567            final long token = Binder.clearCallingIdentity();
3568            try {
3569                if (sUserManager.isInitialized(userId)) {
3570                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3571                            MountServiceInternal.class);
3572                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3573                }
3574            } finally {
3575                Binder.restoreCallingIdentity(token);
3576            }
3577        }
3578    }
3579
3580    @Override
3581    public void revokeRuntimePermission(String packageName, String name, int userId) {
3582        if (!sUserManager.exists(userId)) {
3583            Log.e(TAG, "No such user:" + userId);
3584            return;
3585        }
3586
3587        mContext.enforceCallingOrSelfPermission(
3588                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3589                "revokeRuntimePermission");
3590
3591        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3592                "revokeRuntimePermission");
3593
3594        final int appId;
3595
3596        synchronized (mPackages) {
3597            final PackageParser.Package pkg = mPackages.get(packageName);
3598            if (pkg == null) {
3599                throw new IllegalArgumentException("Unknown package: " + packageName);
3600            }
3601
3602            final BasePermission bp = mSettings.mPermissions.get(name);
3603            if (bp == null) {
3604                throw new IllegalArgumentException("Unknown permission: " + name);
3605            }
3606
3607            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3608
3609            SettingBase sb = (SettingBase) pkg.mExtras;
3610            if (sb == null) {
3611                throw new IllegalArgumentException("Unknown package: " + packageName);
3612            }
3613
3614            final PermissionsState permissionsState = sb.getPermissionsState();
3615
3616            final int flags = permissionsState.getPermissionFlags(name, userId);
3617            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3618                throw new SecurityException("Cannot revoke system fixed permission: "
3619                        + name + " for package: " + packageName);
3620            }
3621
3622            if (bp.isDevelopment()) {
3623                // Development permissions must be handled specially, since they are not
3624                // normal runtime permissions.  For now they apply to all users.
3625                if (permissionsState.revokeInstallPermission(bp) !=
3626                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3627                    scheduleWriteSettingsLocked();
3628                }
3629                return;
3630            }
3631
3632            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3633                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3634                return;
3635            }
3636
3637            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3638
3639            // Critical, after this call app should never have the permission.
3640            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3641
3642            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3643        }
3644
3645        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3646    }
3647
3648    @Override
3649    public void resetRuntimePermissions() {
3650        mContext.enforceCallingOrSelfPermission(
3651                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3652                "revokeRuntimePermission");
3653
3654        int callingUid = Binder.getCallingUid();
3655        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3656            mContext.enforceCallingOrSelfPermission(
3657                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3658                    "resetRuntimePermissions");
3659        }
3660
3661        synchronized (mPackages) {
3662            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3663            for (int userId : UserManagerService.getInstance().getUserIds()) {
3664                final int packageCount = mPackages.size();
3665                for (int i = 0; i < packageCount; i++) {
3666                    PackageParser.Package pkg = mPackages.valueAt(i);
3667                    if (!(pkg.mExtras instanceof PackageSetting)) {
3668                        continue;
3669                    }
3670                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3671                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3672                }
3673            }
3674        }
3675    }
3676
3677    @Override
3678    public int getPermissionFlags(String name, String packageName, int userId) {
3679        if (!sUserManager.exists(userId)) {
3680            return 0;
3681        }
3682
3683        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3684
3685        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3686                "getPermissionFlags");
3687
3688        synchronized (mPackages) {
3689            final PackageParser.Package pkg = mPackages.get(packageName);
3690            if (pkg == null) {
3691                throw new IllegalArgumentException("Unknown package: " + packageName);
3692            }
3693
3694            final BasePermission bp = mSettings.mPermissions.get(name);
3695            if (bp == null) {
3696                throw new IllegalArgumentException("Unknown permission: " + name);
3697            }
3698
3699            SettingBase sb = (SettingBase) pkg.mExtras;
3700            if (sb == null) {
3701                throw new IllegalArgumentException("Unknown package: " + packageName);
3702            }
3703
3704            PermissionsState permissionsState = sb.getPermissionsState();
3705            return permissionsState.getPermissionFlags(name, userId);
3706        }
3707    }
3708
3709    @Override
3710    public void updatePermissionFlags(String name, String packageName, int flagMask,
3711            int flagValues, int userId) {
3712        if (!sUserManager.exists(userId)) {
3713            return;
3714        }
3715
3716        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3717
3718        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3719                "updatePermissionFlags");
3720
3721        // Only the system can change these flags and nothing else.
3722        if (getCallingUid() != Process.SYSTEM_UID) {
3723            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3724            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3725            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3726            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3727        }
3728
3729        synchronized (mPackages) {
3730            final PackageParser.Package pkg = mPackages.get(packageName);
3731            if (pkg == null) {
3732                throw new IllegalArgumentException("Unknown package: " + packageName);
3733            }
3734
3735            final BasePermission bp = mSettings.mPermissions.get(name);
3736            if (bp == null) {
3737                throw new IllegalArgumentException("Unknown permission: " + name);
3738            }
3739
3740            SettingBase sb = (SettingBase) pkg.mExtras;
3741            if (sb == null) {
3742                throw new IllegalArgumentException("Unknown package: " + packageName);
3743            }
3744
3745            PermissionsState permissionsState = sb.getPermissionsState();
3746
3747            // Only the package manager can change flags for system component permissions.
3748            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3749            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3750                return;
3751            }
3752
3753            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3754
3755            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3756                // Install and runtime permissions are stored in different places,
3757                // so figure out what permission changed and persist the change.
3758                if (permissionsState.getInstallPermissionState(name) != null) {
3759                    scheduleWriteSettingsLocked();
3760                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3761                        || hadState) {
3762                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3763                }
3764            }
3765        }
3766    }
3767
3768    /**
3769     * Update the permission flags for all packages and runtime permissions of a user in order
3770     * to allow device or profile owner to remove POLICY_FIXED.
3771     */
3772    @Override
3773    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3774        if (!sUserManager.exists(userId)) {
3775            return;
3776        }
3777
3778        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3779
3780        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3781                "updatePermissionFlagsForAllApps");
3782
3783        // Only the system can change system fixed flags.
3784        if (getCallingUid() != Process.SYSTEM_UID) {
3785            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3786            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3787        }
3788
3789        synchronized (mPackages) {
3790            boolean changed = false;
3791            final int packageCount = mPackages.size();
3792            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3793                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3794                SettingBase sb = (SettingBase) pkg.mExtras;
3795                if (sb == null) {
3796                    continue;
3797                }
3798                PermissionsState permissionsState = sb.getPermissionsState();
3799                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3800                        userId, flagMask, flagValues);
3801            }
3802            if (changed) {
3803                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3804            }
3805        }
3806    }
3807
3808    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3809        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3810                != PackageManager.PERMISSION_GRANTED
3811            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3812                != PackageManager.PERMISSION_GRANTED) {
3813            throw new SecurityException(message + " requires "
3814                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3815                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3816        }
3817    }
3818
3819    @Override
3820    public boolean shouldShowRequestPermissionRationale(String permissionName,
3821            String packageName, int userId) {
3822        if (UserHandle.getCallingUserId() != userId) {
3823            mContext.enforceCallingPermission(
3824                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3825                    "canShowRequestPermissionRationale for user " + userId);
3826        }
3827
3828        final int uid = getPackageUid(packageName, userId);
3829        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3830            return false;
3831        }
3832
3833        if (checkPermission(permissionName, packageName, userId)
3834                == PackageManager.PERMISSION_GRANTED) {
3835            return false;
3836        }
3837
3838        final int flags;
3839
3840        final long identity = Binder.clearCallingIdentity();
3841        try {
3842            flags = getPermissionFlags(permissionName,
3843                    packageName, userId);
3844        } finally {
3845            Binder.restoreCallingIdentity(identity);
3846        }
3847
3848        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3849                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3850                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3851
3852        if ((flags & fixedFlags) != 0) {
3853            return false;
3854        }
3855
3856        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3857    }
3858
3859    @Override
3860    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3861        mContext.enforceCallingOrSelfPermission(
3862                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3863                "addOnPermissionsChangeListener");
3864
3865        synchronized (mPackages) {
3866            mOnPermissionChangeListeners.addListenerLocked(listener);
3867        }
3868    }
3869
3870    @Override
3871    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3872        synchronized (mPackages) {
3873            mOnPermissionChangeListeners.removeListenerLocked(listener);
3874        }
3875    }
3876
3877    @Override
3878    public boolean isProtectedBroadcast(String actionName) {
3879        synchronized (mPackages) {
3880            return mProtectedBroadcasts.contains(actionName);
3881        }
3882    }
3883
3884    @Override
3885    public int checkSignatures(String pkg1, String pkg2) {
3886        synchronized (mPackages) {
3887            final PackageParser.Package p1 = mPackages.get(pkg1);
3888            final PackageParser.Package p2 = mPackages.get(pkg2);
3889            if (p1 == null || p1.mExtras == null
3890                    || p2 == null || p2.mExtras == null) {
3891                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3892            }
3893            return compareSignatures(p1.mSignatures, p2.mSignatures);
3894        }
3895    }
3896
3897    @Override
3898    public int checkUidSignatures(int uid1, int uid2) {
3899        // Map to base uids.
3900        uid1 = UserHandle.getAppId(uid1);
3901        uid2 = UserHandle.getAppId(uid2);
3902        // reader
3903        synchronized (mPackages) {
3904            Signature[] s1;
3905            Signature[] s2;
3906            Object obj = mSettings.getUserIdLPr(uid1);
3907            if (obj != null) {
3908                if (obj instanceof SharedUserSetting) {
3909                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3910                } else if (obj instanceof PackageSetting) {
3911                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3912                } else {
3913                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3914                }
3915            } else {
3916                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3917            }
3918            obj = mSettings.getUserIdLPr(uid2);
3919            if (obj != null) {
3920                if (obj instanceof SharedUserSetting) {
3921                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3922                } else if (obj instanceof PackageSetting) {
3923                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3924                } else {
3925                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3926                }
3927            } else {
3928                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3929            }
3930            return compareSignatures(s1, s2);
3931        }
3932    }
3933
3934    private void killUid(int appId, int userId, String reason) {
3935        final long identity = Binder.clearCallingIdentity();
3936        try {
3937            IActivityManager am = ActivityManagerNative.getDefault();
3938            if (am != null) {
3939                try {
3940                    am.killUid(appId, userId, reason);
3941                } catch (RemoteException e) {
3942                    /* ignore - same process */
3943                }
3944            }
3945        } finally {
3946            Binder.restoreCallingIdentity(identity);
3947        }
3948    }
3949
3950    /**
3951     * Compares two sets of signatures. Returns:
3952     * <br />
3953     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3954     * <br />
3955     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3956     * <br />
3957     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3958     * <br />
3959     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3960     * <br />
3961     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3962     */
3963    static int compareSignatures(Signature[] s1, Signature[] s2) {
3964        if (s1 == null) {
3965            return s2 == null
3966                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3967                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3968        }
3969
3970        if (s2 == null) {
3971            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3972        }
3973
3974        if (s1.length != s2.length) {
3975            return PackageManager.SIGNATURE_NO_MATCH;
3976        }
3977
3978        // Since both signature sets are of size 1, we can compare without HashSets.
3979        if (s1.length == 1) {
3980            return s1[0].equals(s2[0]) ?
3981                    PackageManager.SIGNATURE_MATCH :
3982                    PackageManager.SIGNATURE_NO_MATCH;
3983        }
3984
3985        ArraySet<Signature> set1 = new ArraySet<Signature>();
3986        for (Signature sig : s1) {
3987            set1.add(sig);
3988        }
3989        ArraySet<Signature> set2 = new ArraySet<Signature>();
3990        for (Signature sig : s2) {
3991            set2.add(sig);
3992        }
3993        // Make sure s2 contains all signatures in s1.
3994        if (set1.equals(set2)) {
3995            return PackageManager.SIGNATURE_MATCH;
3996        }
3997        return PackageManager.SIGNATURE_NO_MATCH;
3998    }
3999
4000    /**
4001     * If the database version for this type of package (internal storage or
4002     * external storage) is less than the version where package signatures
4003     * were updated, return true.
4004     */
4005    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4006        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4007        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4008    }
4009
4010    /**
4011     * Used for backward compatibility to make sure any packages with
4012     * certificate chains get upgraded to the new style. {@code existingSigs}
4013     * will be in the old format (since they were stored on disk from before the
4014     * system upgrade) and {@code scannedSigs} will be in the newer format.
4015     */
4016    private int compareSignaturesCompat(PackageSignatures existingSigs,
4017            PackageParser.Package scannedPkg) {
4018        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4019            return PackageManager.SIGNATURE_NO_MATCH;
4020        }
4021
4022        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4023        for (Signature sig : existingSigs.mSignatures) {
4024            existingSet.add(sig);
4025        }
4026        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4027        for (Signature sig : scannedPkg.mSignatures) {
4028            try {
4029                Signature[] chainSignatures = sig.getChainSignatures();
4030                for (Signature chainSig : chainSignatures) {
4031                    scannedCompatSet.add(chainSig);
4032                }
4033            } catch (CertificateEncodingException e) {
4034                scannedCompatSet.add(sig);
4035            }
4036        }
4037        /*
4038         * Make sure the expanded scanned set contains all signatures in the
4039         * existing one.
4040         */
4041        if (scannedCompatSet.equals(existingSet)) {
4042            // Migrate the old signatures to the new scheme.
4043            existingSigs.assignSignatures(scannedPkg.mSignatures);
4044            // The new KeySets will be re-added later in the scanning process.
4045            synchronized (mPackages) {
4046                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4047            }
4048            return PackageManager.SIGNATURE_MATCH;
4049        }
4050        return PackageManager.SIGNATURE_NO_MATCH;
4051    }
4052
4053    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4054        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4055        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4056    }
4057
4058    private int compareSignaturesRecover(PackageSignatures existingSigs,
4059            PackageParser.Package scannedPkg) {
4060        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4061            return PackageManager.SIGNATURE_NO_MATCH;
4062        }
4063
4064        String msg = null;
4065        try {
4066            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4067                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4068                        + scannedPkg.packageName);
4069                return PackageManager.SIGNATURE_MATCH;
4070            }
4071        } catch (CertificateException e) {
4072            msg = e.getMessage();
4073        }
4074
4075        logCriticalInfo(Log.INFO,
4076                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4077        return PackageManager.SIGNATURE_NO_MATCH;
4078    }
4079
4080    @Override
4081    public String[] getPackagesForUid(int uid) {
4082        uid = UserHandle.getAppId(uid);
4083        // reader
4084        synchronized (mPackages) {
4085            Object obj = mSettings.getUserIdLPr(uid);
4086            if (obj instanceof SharedUserSetting) {
4087                final SharedUserSetting sus = (SharedUserSetting) obj;
4088                final int N = sus.packages.size();
4089                final String[] res = new String[N];
4090                final Iterator<PackageSetting> it = sus.packages.iterator();
4091                int i = 0;
4092                while (it.hasNext()) {
4093                    res[i++] = it.next().name;
4094                }
4095                return res;
4096            } else if (obj instanceof PackageSetting) {
4097                final PackageSetting ps = (PackageSetting) obj;
4098                return new String[] { ps.name };
4099            }
4100        }
4101        return null;
4102    }
4103
4104    @Override
4105    public String getNameForUid(int uid) {
4106        // reader
4107        synchronized (mPackages) {
4108            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4109            if (obj instanceof SharedUserSetting) {
4110                final SharedUserSetting sus = (SharedUserSetting) obj;
4111                return sus.name + ":" + sus.userId;
4112            } else if (obj instanceof PackageSetting) {
4113                final PackageSetting ps = (PackageSetting) obj;
4114                return ps.name;
4115            }
4116        }
4117        return null;
4118    }
4119
4120    @Override
4121    public int getUidForSharedUser(String sharedUserName) {
4122        if(sharedUserName == null) {
4123            return -1;
4124        }
4125        // reader
4126        synchronized (mPackages) {
4127            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4128            if (suid == null) {
4129                return -1;
4130            }
4131            return suid.userId;
4132        }
4133    }
4134
4135    @Override
4136    public int getFlagsForUid(int uid) {
4137        synchronized (mPackages) {
4138            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4139            if (obj instanceof SharedUserSetting) {
4140                final SharedUserSetting sus = (SharedUserSetting) obj;
4141                return sus.pkgFlags;
4142            } else if (obj instanceof PackageSetting) {
4143                final PackageSetting ps = (PackageSetting) obj;
4144                return ps.pkgFlags;
4145            }
4146        }
4147        return 0;
4148    }
4149
4150    @Override
4151    public int getPrivateFlagsForUid(int uid) {
4152        synchronized (mPackages) {
4153            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4154            if (obj instanceof SharedUserSetting) {
4155                final SharedUserSetting sus = (SharedUserSetting) obj;
4156                return sus.pkgPrivateFlags;
4157            } else if (obj instanceof PackageSetting) {
4158                final PackageSetting ps = (PackageSetting) obj;
4159                return ps.pkgPrivateFlags;
4160            }
4161        }
4162        return 0;
4163    }
4164
4165    @Override
4166    public boolean isUidPrivileged(int uid) {
4167        uid = UserHandle.getAppId(uid);
4168        // reader
4169        synchronized (mPackages) {
4170            Object obj = mSettings.getUserIdLPr(uid);
4171            if (obj instanceof SharedUserSetting) {
4172                final SharedUserSetting sus = (SharedUserSetting) obj;
4173                final Iterator<PackageSetting> it = sus.packages.iterator();
4174                while (it.hasNext()) {
4175                    if (it.next().isPrivileged()) {
4176                        return true;
4177                    }
4178                }
4179            } else if (obj instanceof PackageSetting) {
4180                final PackageSetting ps = (PackageSetting) obj;
4181                return ps.isPrivileged();
4182            }
4183        }
4184        return false;
4185    }
4186
4187    @Override
4188    public String[] getAppOpPermissionPackages(String permissionName) {
4189        synchronized (mPackages) {
4190            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4191            if (pkgs == null) {
4192                return null;
4193            }
4194            return pkgs.toArray(new String[pkgs.size()]);
4195        }
4196    }
4197
4198    @Override
4199    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4200            int flags, int userId) {
4201        if (!sUserManager.exists(userId)) return null;
4202        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4203        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4204        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4205    }
4206
4207    @Override
4208    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4209            IntentFilter filter, int match, ComponentName activity) {
4210        final int userId = UserHandle.getCallingUserId();
4211        if (DEBUG_PREFERRED) {
4212            Log.v(TAG, "setLastChosenActivity intent=" + intent
4213                + " resolvedType=" + resolvedType
4214                + " flags=" + flags
4215                + " filter=" + filter
4216                + " match=" + match
4217                + " activity=" + activity);
4218            filter.dump(new PrintStreamPrinter(System.out), "    ");
4219        }
4220        intent.setComponent(null);
4221        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4222        // Find any earlier preferred or last chosen entries and nuke them
4223        findPreferredActivity(intent, resolvedType,
4224                flags, query, 0, false, true, false, userId);
4225        // Add the new activity as the last chosen for this filter
4226        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4227                "Setting last chosen");
4228    }
4229
4230    @Override
4231    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4232        final int userId = UserHandle.getCallingUserId();
4233        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4234        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4235        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4236                false, false, false, userId);
4237    }
4238
4239    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4240            int flags, List<ResolveInfo> query, int userId) {
4241        if (query != null) {
4242            final int N = query.size();
4243            if (N == 1) {
4244                return query.get(0);
4245            } else if (N > 1) {
4246                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4247                // If there is more than one activity with the same priority,
4248                // then let the user decide between them.
4249                ResolveInfo r0 = query.get(0);
4250                ResolveInfo r1 = query.get(1);
4251                if (DEBUG_INTENT_MATCHING || debug) {
4252                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4253                            + r1.activityInfo.name + "=" + r1.priority);
4254                }
4255                // If the first activity has a higher priority, or a different
4256                // default, then it is always desireable to pick it.
4257                if (r0.priority != r1.priority
4258                        || r0.preferredOrder != r1.preferredOrder
4259                        || r0.isDefault != r1.isDefault) {
4260                    return query.get(0);
4261                }
4262                // If we have saved a preference for a preferred activity for
4263                // this Intent, use that.
4264                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4265                        flags, query, r0.priority, true, false, debug, userId);
4266                if (ri != null) {
4267                    return ri;
4268                }
4269                if (userId != 0) {
4270                    ri = new ResolveInfo(mResolveInfo);
4271                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4272                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4273                            ri.activityInfo.applicationInfo);
4274                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4275                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4276                    return ri;
4277                }
4278                return mResolveInfo;
4279            }
4280        }
4281        return null;
4282    }
4283
4284    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4285            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4286        final int N = query.size();
4287        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4288                .get(userId);
4289        // Get the list of persistent preferred activities that handle the intent
4290        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4291        List<PersistentPreferredActivity> pprefs = ppir != null
4292                ? ppir.queryIntent(intent, resolvedType,
4293                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4294                : null;
4295        if (pprefs != null && pprefs.size() > 0) {
4296            final int M = pprefs.size();
4297            for (int i=0; i<M; i++) {
4298                final PersistentPreferredActivity ppa = pprefs.get(i);
4299                if (DEBUG_PREFERRED || debug) {
4300                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4301                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4302                            + "\n  component=" + ppa.mComponent);
4303                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4304                }
4305                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4306                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4307                if (DEBUG_PREFERRED || debug) {
4308                    Slog.v(TAG, "Found persistent preferred activity:");
4309                    if (ai != null) {
4310                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4311                    } else {
4312                        Slog.v(TAG, "  null");
4313                    }
4314                }
4315                if (ai == null) {
4316                    // This previously registered persistent preferred activity
4317                    // component is no longer known. Ignore it and do NOT remove it.
4318                    continue;
4319                }
4320                for (int j=0; j<N; j++) {
4321                    final ResolveInfo ri = query.get(j);
4322                    if (!ri.activityInfo.applicationInfo.packageName
4323                            .equals(ai.applicationInfo.packageName)) {
4324                        continue;
4325                    }
4326                    if (!ri.activityInfo.name.equals(ai.name)) {
4327                        continue;
4328                    }
4329                    //  Found a persistent preference that can handle the intent.
4330                    if (DEBUG_PREFERRED || debug) {
4331                        Slog.v(TAG, "Returning persistent preferred activity: " +
4332                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4333                    }
4334                    return ri;
4335                }
4336            }
4337        }
4338        return null;
4339    }
4340
4341    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4342            List<ResolveInfo> query, int priority, boolean always,
4343            boolean removeMatches, boolean debug, int userId) {
4344        if (!sUserManager.exists(userId)) return null;
4345        // writer
4346        synchronized (mPackages) {
4347            if (intent.getSelector() != null) {
4348                intent = intent.getSelector();
4349            }
4350            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4351
4352            // Try to find a matching persistent preferred activity.
4353            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4354                    debug, userId);
4355
4356            // If a persistent preferred activity matched, use it.
4357            if (pri != null) {
4358                return pri;
4359            }
4360
4361            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4362            // Get the list of preferred activities that handle the intent
4363            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4364            List<PreferredActivity> prefs = pir != null
4365                    ? pir.queryIntent(intent, resolvedType,
4366                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4367                    : null;
4368            if (prefs != null && prefs.size() > 0) {
4369                boolean changed = false;
4370                try {
4371                    // First figure out how good the original match set is.
4372                    // We will only allow preferred activities that came
4373                    // from the same match quality.
4374                    int match = 0;
4375
4376                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4377
4378                    final int N = query.size();
4379                    for (int j=0; j<N; j++) {
4380                        final ResolveInfo ri = query.get(j);
4381                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4382                                + ": 0x" + Integer.toHexString(match));
4383                        if (ri.match > match) {
4384                            match = ri.match;
4385                        }
4386                    }
4387
4388                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4389                            + Integer.toHexString(match));
4390
4391                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4392                    final int M = prefs.size();
4393                    for (int i=0; i<M; i++) {
4394                        final PreferredActivity pa = prefs.get(i);
4395                        if (DEBUG_PREFERRED || debug) {
4396                            Slog.v(TAG, "Checking PreferredActivity ds="
4397                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4398                                    + "\n  component=" + pa.mPref.mComponent);
4399                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4400                        }
4401                        if (pa.mPref.mMatch != match) {
4402                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4403                                    + Integer.toHexString(pa.mPref.mMatch));
4404                            continue;
4405                        }
4406                        // If it's not an "always" type preferred activity and that's what we're
4407                        // looking for, skip it.
4408                        if (always && !pa.mPref.mAlways) {
4409                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4410                            continue;
4411                        }
4412                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4413                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4414                        if (DEBUG_PREFERRED || debug) {
4415                            Slog.v(TAG, "Found preferred activity:");
4416                            if (ai != null) {
4417                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4418                            } else {
4419                                Slog.v(TAG, "  null");
4420                            }
4421                        }
4422                        if (ai == null) {
4423                            // This previously registered preferred activity
4424                            // component is no longer known.  Most likely an update
4425                            // to the app was installed and in the new version this
4426                            // component no longer exists.  Clean it up by removing
4427                            // it from the preferred activities list, and skip it.
4428                            Slog.w(TAG, "Removing dangling preferred activity: "
4429                                    + pa.mPref.mComponent);
4430                            pir.removeFilter(pa);
4431                            changed = true;
4432                            continue;
4433                        }
4434                        for (int j=0; j<N; j++) {
4435                            final ResolveInfo ri = query.get(j);
4436                            if (!ri.activityInfo.applicationInfo.packageName
4437                                    .equals(ai.applicationInfo.packageName)) {
4438                                continue;
4439                            }
4440                            if (!ri.activityInfo.name.equals(ai.name)) {
4441                                continue;
4442                            }
4443
4444                            if (removeMatches) {
4445                                pir.removeFilter(pa);
4446                                changed = true;
4447                                if (DEBUG_PREFERRED) {
4448                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4449                                }
4450                                break;
4451                            }
4452
4453                            // Okay we found a previously set preferred or last chosen app.
4454                            // If the result set is different from when this
4455                            // was created, we need to clear it and re-ask the
4456                            // user their preference, if we're looking for an "always" type entry.
4457                            if (always && !pa.mPref.sameSet(query)) {
4458                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4459                                        + intent + " type " + resolvedType);
4460                                if (DEBUG_PREFERRED) {
4461                                    Slog.v(TAG, "Removing preferred activity since set changed "
4462                                            + pa.mPref.mComponent);
4463                                }
4464                                pir.removeFilter(pa);
4465                                // Re-add the filter as a "last chosen" entry (!always)
4466                                PreferredActivity lastChosen = new PreferredActivity(
4467                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4468                                pir.addFilter(lastChosen);
4469                                changed = true;
4470                                return null;
4471                            }
4472
4473                            // Yay! Either the set matched or we're looking for the last chosen
4474                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4475                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4476                            return ri;
4477                        }
4478                    }
4479                } finally {
4480                    if (changed) {
4481                        if (DEBUG_PREFERRED) {
4482                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4483                        }
4484                        scheduleWritePackageRestrictionsLocked(userId);
4485                    }
4486                }
4487            }
4488        }
4489        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4490        return null;
4491    }
4492
4493    /*
4494     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4495     */
4496    @Override
4497    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4498            int targetUserId) {
4499        mContext.enforceCallingOrSelfPermission(
4500                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4501        List<CrossProfileIntentFilter> matches =
4502                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4503        if (matches != null) {
4504            int size = matches.size();
4505            for (int i = 0; i < size; i++) {
4506                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4507            }
4508        }
4509        if (hasWebURI(intent)) {
4510            // cross-profile app linking works only towards the parent.
4511            final UserInfo parent = getProfileParent(sourceUserId);
4512            synchronized(mPackages) {
4513                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4514                        intent, resolvedType, 0, sourceUserId, parent.id);
4515                return xpDomainInfo != null;
4516            }
4517        }
4518        return false;
4519    }
4520
4521    private UserInfo getProfileParent(int userId) {
4522        final long identity = Binder.clearCallingIdentity();
4523        try {
4524            return sUserManager.getProfileParent(userId);
4525        } finally {
4526            Binder.restoreCallingIdentity(identity);
4527        }
4528    }
4529
4530    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4531            String resolvedType, int userId) {
4532        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4533        if (resolver != null) {
4534            return resolver.queryIntent(intent, resolvedType, false, userId);
4535        }
4536        return null;
4537    }
4538
4539    @Override
4540    public List<ResolveInfo> queryIntentActivities(Intent intent,
4541            String resolvedType, int flags, int userId) {
4542        if (!sUserManager.exists(userId)) return Collections.emptyList();
4543        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4544        ComponentName comp = intent.getComponent();
4545        if (comp == null) {
4546            if (intent.getSelector() != null) {
4547                intent = intent.getSelector();
4548                comp = intent.getComponent();
4549            }
4550        }
4551
4552        if (comp != null) {
4553            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4554            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4555            if (ai != null) {
4556                final ResolveInfo ri = new ResolveInfo();
4557                ri.activityInfo = ai;
4558                list.add(ri);
4559            }
4560            return list;
4561        }
4562
4563        // reader
4564        synchronized (mPackages) {
4565            final String pkgName = intent.getPackage();
4566            if (pkgName == null) {
4567                List<CrossProfileIntentFilter> matchingFilters =
4568                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4569                // Check for results that need to skip the current profile.
4570                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4571                        resolvedType, flags, userId);
4572                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4573                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4574                    result.add(xpResolveInfo);
4575                    return filterIfNotSystemUser(result, userId);
4576                }
4577
4578                // Check for results in the current profile.
4579                List<ResolveInfo> result = mActivities.queryIntent(
4580                        intent, resolvedType, flags, userId);
4581
4582                // Check for cross profile results.
4583                xpResolveInfo = queryCrossProfileIntents(
4584                        matchingFilters, intent, resolvedType, flags, userId);
4585                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4586                    result.add(xpResolveInfo);
4587                    Collections.sort(result, mResolvePrioritySorter);
4588                }
4589                result = filterIfNotSystemUser(result, userId);
4590                if (hasWebURI(intent)) {
4591                    CrossProfileDomainInfo xpDomainInfo = null;
4592                    final UserInfo parent = getProfileParent(userId);
4593                    if (parent != null) {
4594                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4595                                flags, userId, parent.id);
4596                    }
4597                    if (xpDomainInfo != null) {
4598                        if (xpResolveInfo != null) {
4599                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4600                            // in the result.
4601                            result.remove(xpResolveInfo);
4602                        }
4603                        if (result.size() == 0) {
4604                            result.add(xpDomainInfo.resolveInfo);
4605                            return result;
4606                        }
4607                    } else if (result.size() <= 1) {
4608                        return result;
4609                    }
4610                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4611                            xpDomainInfo, userId);
4612                    Collections.sort(result, mResolvePrioritySorter);
4613                }
4614                return result;
4615            }
4616            final PackageParser.Package pkg = mPackages.get(pkgName);
4617            if (pkg != null) {
4618                return filterIfNotSystemUser(
4619                        mActivities.queryIntentForPackage(
4620                                intent, resolvedType, flags, pkg.activities, userId),
4621                        userId);
4622            }
4623            return new ArrayList<ResolveInfo>();
4624        }
4625    }
4626
4627    private static class CrossProfileDomainInfo {
4628        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4629        ResolveInfo resolveInfo;
4630        /* Best domain verification status of the activities found in the other profile */
4631        int bestDomainVerificationStatus;
4632    }
4633
4634    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4635            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4636        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4637                sourceUserId)) {
4638            return null;
4639        }
4640        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4641                resolvedType, flags, parentUserId);
4642
4643        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4644            return null;
4645        }
4646        CrossProfileDomainInfo result = null;
4647        int size = resultTargetUser.size();
4648        for (int i = 0; i < size; i++) {
4649            ResolveInfo riTargetUser = resultTargetUser.get(i);
4650            // Intent filter verification is only for filters that specify a host. So don't return
4651            // those that handle all web uris.
4652            if (riTargetUser.handleAllWebDataURI) {
4653                continue;
4654            }
4655            String packageName = riTargetUser.activityInfo.packageName;
4656            PackageSetting ps = mSettings.mPackages.get(packageName);
4657            if (ps == null) {
4658                continue;
4659            }
4660            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4661            int status = (int)(verificationState >> 32);
4662            if (result == null) {
4663                result = new CrossProfileDomainInfo();
4664                result.resolveInfo =
4665                        createForwardingResolveInfo(new IntentFilter(), sourceUserId, parentUserId);
4666                result.bestDomainVerificationStatus = status;
4667            } else {
4668                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4669                        result.bestDomainVerificationStatus);
4670            }
4671        }
4672        // Don't consider matches with status NEVER across profiles.
4673        if (result != null && result.bestDomainVerificationStatus
4674                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4675            return null;
4676        }
4677        return result;
4678    }
4679
4680    /**
4681     * Verification statuses are ordered from the worse to the best, except for
4682     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4683     */
4684    private int bestDomainVerificationStatus(int status1, int status2) {
4685        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4686            return status2;
4687        }
4688        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4689            return status1;
4690        }
4691        return (int) MathUtils.max(status1, status2);
4692    }
4693
4694    private boolean isUserEnabled(int userId) {
4695        long callingId = Binder.clearCallingIdentity();
4696        try {
4697            UserInfo userInfo = sUserManager.getUserInfo(userId);
4698            return userInfo != null && userInfo.isEnabled();
4699        } finally {
4700            Binder.restoreCallingIdentity(callingId);
4701        }
4702    }
4703
4704    /**
4705     * Filter out activities with systemUserOnly flag set, when current user is not System.
4706     *
4707     * @return filtered list
4708     */
4709    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
4710        if (userId == UserHandle.USER_SYSTEM) {
4711            return resolveInfos;
4712        }
4713        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4714            ResolveInfo info = resolveInfos.get(i);
4715            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
4716                resolveInfos.remove(i);
4717            }
4718        }
4719        return resolveInfos;
4720    }
4721
4722    private static boolean hasWebURI(Intent intent) {
4723        if (intent.getData() == null) {
4724            return false;
4725        }
4726        final String scheme = intent.getScheme();
4727        if (TextUtils.isEmpty(scheme)) {
4728            return false;
4729        }
4730        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4731    }
4732
4733    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4734            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4735            int userId) {
4736        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4737
4738        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4739            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4740                    candidates.size());
4741        }
4742
4743        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4744        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4745        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4746        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
4747        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4748        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4749
4750        synchronized (mPackages) {
4751            final int count = candidates.size();
4752            // First, try to use linked apps. Partition the candidates into four lists:
4753            // one for the final results, one for the "do not use ever", one for "undefined status"
4754            // and finally one for "browser app type".
4755            for (int n=0; n<count; n++) {
4756                ResolveInfo info = candidates.get(n);
4757                String packageName = info.activityInfo.packageName;
4758                PackageSetting ps = mSettings.mPackages.get(packageName);
4759                if (ps != null) {
4760                    // Add to the special match all list (Browser use case)
4761                    if (info.handleAllWebDataURI) {
4762                        matchAllList.add(info);
4763                        continue;
4764                    }
4765                    // Try to get the status from User settings first
4766                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4767                    int status = (int)(packedStatus >> 32);
4768                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4769                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4770                        if (DEBUG_DOMAIN_VERIFICATION) {
4771                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4772                                    + " : linkgen=" + linkGeneration);
4773                        }
4774                        // Use link-enabled generation as preferredOrder, i.e.
4775                        // prefer newly-enabled over earlier-enabled.
4776                        info.preferredOrder = linkGeneration;
4777                        alwaysList.add(info);
4778                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4779                        if (DEBUG_DOMAIN_VERIFICATION) {
4780                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4781                        }
4782                        neverList.add(info);
4783                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4784                        if (DEBUG_DOMAIN_VERIFICATION) {
4785                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
4786                        }
4787                        alwaysAskList.add(info);
4788                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4789                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4790                        if (DEBUG_DOMAIN_VERIFICATION) {
4791                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4792                        }
4793                        undefinedList.add(info);
4794                    }
4795                }
4796            }
4797
4798            // We'll want to include browser possibilities in a few cases
4799            boolean includeBrowser = false;
4800
4801            // First try to add the "always" resolution(s) for the current user, if any
4802            if (alwaysList.size() > 0) {
4803                result.addAll(alwaysList);
4804            // if there is an "always" for the parent user, add it.
4805            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4806                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4807                result.add(xpDomainInfo.resolveInfo);
4808            } else {
4809                // Add all undefined apps as we want them to appear in the disambiguation dialog.
4810                result.addAll(undefinedList);
4811                if (xpDomainInfo != null && (
4812                        xpDomainInfo.bestDomainVerificationStatus
4813                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4814                        || xpDomainInfo.bestDomainVerificationStatus
4815                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4816                    result.add(xpDomainInfo.resolveInfo);
4817                }
4818                includeBrowser = true;
4819            }
4820
4821            // The presence of any 'always ask' alternatives means we'll also offer browsers.
4822            // If there were 'always' entries their preferred order has been set, so we also
4823            // back that off to make the alternatives equivalent
4824            if (alwaysAskList.size() > 0) {
4825                for (ResolveInfo i : result) {
4826                    i.preferredOrder = 0;
4827                }
4828                result.addAll(alwaysAskList);
4829                includeBrowser = true;
4830            }
4831
4832            if (includeBrowser) {
4833                // Also add browsers (all of them or only the default one)
4834                if (DEBUG_DOMAIN_VERIFICATION) {
4835                    Slog.v(TAG, "   ...including browsers in candidate set");
4836                }
4837                if ((matchFlags & MATCH_ALL) != 0) {
4838                    result.addAll(matchAllList);
4839                } else {
4840                    // Browser/generic handling case.  If there's a default browser, go straight
4841                    // to that (but only if there is no other higher-priority match).
4842                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4843                    int maxMatchPrio = 0;
4844                    ResolveInfo defaultBrowserMatch = null;
4845                    final int numCandidates = matchAllList.size();
4846                    for (int n = 0; n < numCandidates; n++) {
4847                        ResolveInfo info = matchAllList.get(n);
4848                        // track the highest overall match priority...
4849                        if (info.priority > maxMatchPrio) {
4850                            maxMatchPrio = info.priority;
4851                        }
4852                        // ...and the highest-priority default browser match
4853                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4854                            if (defaultBrowserMatch == null
4855                                    || (defaultBrowserMatch.priority < info.priority)) {
4856                                if (debug) {
4857                                    Slog.v(TAG, "Considering default browser match " + info);
4858                                }
4859                                defaultBrowserMatch = info;
4860                            }
4861                        }
4862                    }
4863                    if (defaultBrowserMatch != null
4864                            && defaultBrowserMatch.priority >= maxMatchPrio
4865                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4866                    {
4867                        if (debug) {
4868                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4869                        }
4870                        result.add(defaultBrowserMatch);
4871                    } else {
4872                        result.addAll(matchAllList);
4873                    }
4874                }
4875
4876                // If there is nothing selected, add all candidates and remove the ones that the user
4877                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4878                if (result.size() == 0) {
4879                    result.addAll(candidates);
4880                    result.removeAll(neverList);
4881                }
4882            }
4883        }
4884        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4885            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4886                    result.size());
4887            for (ResolveInfo info : result) {
4888                Slog.v(TAG, "  + " + info.activityInfo);
4889            }
4890        }
4891        return result;
4892    }
4893
4894    // Returns a packed value as a long:
4895    //
4896    // high 'int'-sized word: link status: undefined/ask/never/always.
4897    // low 'int'-sized word: relative priority among 'always' results.
4898    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4899        long result = ps.getDomainVerificationStatusForUser(userId);
4900        // if none available, get the master status
4901        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4902            if (ps.getIntentFilterVerificationInfo() != null) {
4903                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4904            }
4905        }
4906        return result;
4907    }
4908
4909    private ResolveInfo querySkipCurrentProfileIntents(
4910            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4911            int flags, int sourceUserId) {
4912        if (matchingFilters != null) {
4913            int size = matchingFilters.size();
4914            for (int i = 0; i < size; i ++) {
4915                CrossProfileIntentFilter filter = matchingFilters.get(i);
4916                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4917                    // Checking if there are activities in the target user that can handle the
4918                    // intent.
4919                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4920                            flags, sourceUserId);
4921                    if (resolveInfo != null) {
4922                        return resolveInfo;
4923                    }
4924                }
4925            }
4926        }
4927        return null;
4928    }
4929
4930    // Return matching ResolveInfo if any for skip current profile intent filters.
4931    private ResolveInfo queryCrossProfileIntents(
4932            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4933            int flags, int sourceUserId) {
4934        if (matchingFilters != null) {
4935            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4936            // match the same intent. For performance reasons, it is better not to
4937            // run queryIntent twice for the same userId
4938            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4939            int size = matchingFilters.size();
4940            for (int i = 0; i < size; i++) {
4941                CrossProfileIntentFilter filter = matchingFilters.get(i);
4942                int targetUserId = filter.getTargetUserId();
4943                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4944                        && !alreadyTriedUserIds.get(targetUserId)) {
4945                    // Checking if there are activities in the target user that can handle the
4946                    // intent.
4947                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4948                            flags, sourceUserId);
4949                    if (resolveInfo != null) return resolveInfo;
4950                    alreadyTriedUserIds.put(targetUserId, true);
4951                }
4952            }
4953        }
4954        return null;
4955    }
4956
4957    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4958            String resolvedType, int flags, int sourceUserId) {
4959        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4960                resolvedType, flags, filter.getTargetUserId());
4961        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4962            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4963        }
4964        return null;
4965    }
4966
4967    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4968            int sourceUserId, int targetUserId) {
4969        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4970        long ident = Binder.clearCallingIdentity();
4971        boolean targetIsProfile;
4972        try {
4973            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
4974        } finally {
4975            Binder.restoreCallingIdentity(ident);
4976        }
4977        String className;
4978        if (targetIsProfile) {
4979            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4980        } else {
4981            className = FORWARD_INTENT_TO_PARENT;
4982        }
4983        ComponentName forwardingActivityComponentName = new ComponentName(
4984                mAndroidApplication.packageName, className);
4985        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4986                sourceUserId);
4987        if (!targetIsProfile) {
4988            forwardingActivityInfo.showUserIcon = targetUserId;
4989            forwardingResolveInfo.noResourceId = true;
4990        }
4991        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4992        forwardingResolveInfo.priority = 0;
4993        forwardingResolveInfo.preferredOrder = 0;
4994        forwardingResolveInfo.match = 0;
4995        forwardingResolveInfo.isDefault = true;
4996        forwardingResolveInfo.filter = filter;
4997        forwardingResolveInfo.targetUserId = targetUserId;
4998        return forwardingResolveInfo;
4999    }
5000
5001    @Override
5002    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5003            Intent[] specifics, String[] specificTypes, Intent intent,
5004            String resolvedType, int flags, int userId) {
5005        if (!sUserManager.exists(userId)) return Collections.emptyList();
5006        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5007                false, "query intent activity options");
5008        final String resultsAction = intent.getAction();
5009
5010        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5011                | PackageManager.GET_RESOLVED_FILTER, userId);
5012
5013        if (DEBUG_INTENT_MATCHING) {
5014            Log.v(TAG, "Query " + intent + ": " + results);
5015        }
5016
5017        int specificsPos = 0;
5018        int N;
5019
5020        // todo: note that the algorithm used here is O(N^2).  This
5021        // isn't a problem in our current environment, but if we start running
5022        // into situations where we have more than 5 or 10 matches then this
5023        // should probably be changed to something smarter...
5024
5025        // First we go through and resolve each of the specific items
5026        // that were supplied, taking care of removing any corresponding
5027        // duplicate items in the generic resolve list.
5028        if (specifics != null) {
5029            for (int i=0; i<specifics.length; i++) {
5030                final Intent sintent = specifics[i];
5031                if (sintent == null) {
5032                    continue;
5033                }
5034
5035                if (DEBUG_INTENT_MATCHING) {
5036                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5037                }
5038
5039                String action = sintent.getAction();
5040                if (resultsAction != null && resultsAction.equals(action)) {
5041                    // If this action was explicitly requested, then don't
5042                    // remove things that have it.
5043                    action = null;
5044                }
5045
5046                ResolveInfo ri = null;
5047                ActivityInfo ai = null;
5048
5049                ComponentName comp = sintent.getComponent();
5050                if (comp == null) {
5051                    ri = resolveIntent(
5052                        sintent,
5053                        specificTypes != null ? specificTypes[i] : null,
5054                            flags, userId);
5055                    if (ri == null) {
5056                        continue;
5057                    }
5058                    if (ri == mResolveInfo) {
5059                        // ACK!  Must do something better with this.
5060                    }
5061                    ai = ri.activityInfo;
5062                    comp = new ComponentName(ai.applicationInfo.packageName,
5063                            ai.name);
5064                } else {
5065                    ai = getActivityInfo(comp, flags, userId);
5066                    if (ai == null) {
5067                        continue;
5068                    }
5069                }
5070
5071                // Look for any generic query activities that are duplicates
5072                // of this specific one, and remove them from the results.
5073                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5074                N = results.size();
5075                int j;
5076                for (j=specificsPos; j<N; j++) {
5077                    ResolveInfo sri = results.get(j);
5078                    if ((sri.activityInfo.name.equals(comp.getClassName())
5079                            && sri.activityInfo.applicationInfo.packageName.equals(
5080                                    comp.getPackageName()))
5081                        || (action != null && sri.filter.matchAction(action))) {
5082                        results.remove(j);
5083                        if (DEBUG_INTENT_MATCHING) Log.v(
5084                            TAG, "Removing duplicate item from " + j
5085                            + " due to specific " + specificsPos);
5086                        if (ri == null) {
5087                            ri = sri;
5088                        }
5089                        j--;
5090                        N--;
5091                    }
5092                }
5093
5094                // Add this specific item to its proper place.
5095                if (ri == null) {
5096                    ri = new ResolveInfo();
5097                    ri.activityInfo = ai;
5098                }
5099                results.add(specificsPos, ri);
5100                ri.specificIndex = i;
5101                specificsPos++;
5102            }
5103        }
5104
5105        // Now we go through the remaining generic results and remove any
5106        // duplicate actions that are found here.
5107        N = results.size();
5108        for (int i=specificsPos; i<N-1; i++) {
5109            final ResolveInfo rii = results.get(i);
5110            if (rii.filter == null) {
5111                continue;
5112            }
5113
5114            // Iterate over all of the actions of this result's intent
5115            // filter...  typically this should be just one.
5116            final Iterator<String> it = rii.filter.actionsIterator();
5117            if (it == null) {
5118                continue;
5119            }
5120            while (it.hasNext()) {
5121                final String action = it.next();
5122                if (resultsAction != null && resultsAction.equals(action)) {
5123                    // If this action was explicitly requested, then don't
5124                    // remove things that have it.
5125                    continue;
5126                }
5127                for (int j=i+1; j<N; j++) {
5128                    final ResolveInfo rij = results.get(j);
5129                    if (rij.filter != null && rij.filter.hasAction(action)) {
5130                        results.remove(j);
5131                        if (DEBUG_INTENT_MATCHING) Log.v(
5132                            TAG, "Removing duplicate item from " + j
5133                            + " due to action " + action + " at " + i);
5134                        j--;
5135                        N--;
5136                    }
5137                }
5138            }
5139
5140            // If the caller didn't request filter information, drop it now
5141            // so we don't have to marshall/unmarshall it.
5142            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5143                rii.filter = null;
5144            }
5145        }
5146
5147        // Filter out the caller activity if so requested.
5148        if (caller != null) {
5149            N = results.size();
5150            for (int i=0; i<N; i++) {
5151                ActivityInfo ainfo = results.get(i).activityInfo;
5152                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5153                        && caller.getClassName().equals(ainfo.name)) {
5154                    results.remove(i);
5155                    break;
5156                }
5157            }
5158        }
5159
5160        // If the caller didn't request filter information,
5161        // drop them now so we don't have to
5162        // marshall/unmarshall it.
5163        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5164            N = results.size();
5165            for (int i=0; i<N; i++) {
5166                results.get(i).filter = null;
5167            }
5168        }
5169
5170        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5171        return results;
5172    }
5173
5174    @Override
5175    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5176            int userId) {
5177        if (!sUserManager.exists(userId)) return Collections.emptyList();
5178        ComponentName comp = intent.getComponent();
5179        if (comp == null) {
5180            if (intent.getSelector() != null) {
5181                intent = intent.getSelector();
5182                comp = intent.getComponent();
5183            }
5184        }
5185        if (comp != null) {
5186            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5187            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5188            if (ai != null) {
5189                ResolveInfo ri = new ResolveInfo();
5190                ri.activityInfo = ai;
5191                list.add(ri);
5192            }
5193            return list;
5194        }
5195
5196        // reader
5197        synchronized (mPackages) {
5198            String pkgName = intent.getPackage();
5199            if (pkgName == null) {
5200                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5201            }
5202            final PackageParser.Package pkg = mPackages.get(pkgName);
5203            if (pkg != null) {
5204                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5205                        userId);
5206            }
5207            return null;
5208        }
5209    }
5210
5211    @Override
5212    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5213        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5214        if (!sUserManager.exists(userId)) return null;
5215        if (query != null) {
5216            if (query.size() >= 1) {
5217                // If there is more than one service with the same priority,
5218                // just arbitrarily pick the first one.
5219                return query.get(0);
5220            }
5221        }
5222        return null;
5223    }
5224
5225    @Override
5226    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5227            int userId) {
5228        if (!sUserManager.exists(userId)) return Collections.emptyList();
5229        ComponentName comp = intent.getComponent();
5230        if (comp == null) {
5231            if (intent.getSelector() != null) {
5232                intent = intent.getSelector();
5233                comp = intent.getComponent();
5234            }
5235        }
5236        if (comp != null) {
5237            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5238            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5239            if (si != null) {
5240                final ResolveInfo ri = new ResolveInfo();
5241                ri.serviceInfo = si;
5242                list.add(ri);
5243            }
5244            return list;
5245        }
5246
5247        // reader
5248        synchronized (mPackages) {
5249            String pkgName = intent.getPackage();
5250            if (pkgName == null) {
5251                return mServices.queryIntent(intent, resolvedType, flags, userId);
5252            }
5253            final PackageParser.Package pkg = mPackages.get(pkgName);
5254            if (pkg != null) {
5255                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5256                        userId);
5257            }
5258            return null;
5259        }
5260    }
5261
5262    @Override
5263    public List<ResolveInfo> queryIntentContentProviders(
5264            Intent intent, String resolvedType, int flags, int userId) {
5265        if (!sUserManager.exists(userId)) return Collections.emptyList();
5266        ComponentName comp = intent.getComponent();
5267        if (comp == null) {
5268            if (intent.getSelector() != null) {
5269                intent = intent.getSelector();
5270                comp = intent.getComponent();
5271            }
5272        }
5273        if (comp != null) {
5274            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5275            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5276            if (pi != null) {
5277                final ResolveInfo ri = new ResolveInfo();
5278                ri.providerInfo = pi;
5279                list.add(ri);
5280            }
5281            return list;
5282        }
5283
5284        // reader
5285        synchronized (mPackages) {
5286            String pkgName = intent.getPackage();
5287            if (pkgName == null) {
5288                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5289            }
5290            final PackageParser.Package pkg = mPackages.get(pkgName);
5291            if (pkg != null) {
5292                return mProviders.queryIntentForPackage(
5293                        intent, resolvedType, flags, pkg.providers, userId);
5294            }
5295            return null;
5296        }
5297    }
5298
5299    @Override
5300    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5301        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5302
5303        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5304
5305        // writer
5306        synchronized (mPackages) {
5307            ArrayList<PackageInfo> list;
5308            if (listUninstalled) {
5309                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5310                for (PackageSetting ps : mSettings.mPackages.values()) {
5311                    PackageInfo pi;
5312                    if (ps.pkg != null) {
5313                        pi = generatePackageInfo(ps.pkg, flags, userId);
5314                    } else {
5315                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5316                    }
5317                    if (pi != null) {
5318                        list.add(pi);
5319                    }
5320                }
5321            } else {
5322                list = new ArrayList<PackageInfo>(mPackages.size());
5323                for (PackageParser.Package p : mPackages.values()) {
5324                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5325                    if (pi != null) {
5326                        list.add(pi);
5327                    }
5328                }
5329            }
5330
5331            return new ParceledListSlice<PackageInfo>(list);
5332        }
5333    }
5334
5335    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5336            String[] permissions, boolean[] tmp, int flags, int userId) {
5337        int numMatch = 0;
5338        final PermissionsState permissionsState = ps.getPermissionsState();
5339        for (int i=0; i<permissions.length; i++) {
5340            final String permission = permissions[i];
5341            if (permissionsState.hasPermission(permission, userId)) {
5342                tmp[i] = true;
5343                numMatch++;
5344            } else {
5345                tmp[i] = false;
5346            }
5347        }
5348        if (numMatch == 0) {
5349            return;
5350        }
5351        PackageInfo pi;
5352        if (ps.pkg != null) {
5353            pi = generatePackageInfo(ps.pkg, flags, userId);
5354        } else {
5355            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5356        }
5357        // The above might return null in cases of uninstalled apps or install-state
5358        // skew across users/profiles.
5359        if (pi != null) {
5360            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5361                if (numMatch == permissions.length) {
5362                    pi.requestedPermissions = permissions;
5363                } else {
5364                    pi.requestedPermissions = new String[numMatch];
5365                    numMatch = 0;
5366                    for (int i=0; i<permissions.length; i++) {
5367                        if (tmp[i]) {
5368                            pi.requestedPermissions[numMatch] = permissions[i];
5369                            numMatch++;
5370                        }
5371                    }
5372                }
5373            }
5374            list.add(pi);
5375        }
5376    }
5377
5378    @Override
5379    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5380            String[] permissions, int flags, int userId) {
5381        if (!sUserManager.exists(userId)) return null;
5382        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5383
5384        // writer
5385        synchronized (mPackages) {
5386            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5387            boolean[] tmpBools = new boolean[permissions.length];
5388            if (listUninstalled) {
5389                for (PackageSetting ps : mSettings.mPackages.values()) {
5390                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5391                }
5392            } else {
5393                for (PackageParser.Package pkg : mPackages.values()) {
5394                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5395                    if (ps != null) {
5396                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5397                                userId);
5398                    }
5399                }
5400            }
5401
5402            return new ParceledListSlice<PackageInfo>(list);
5403        }
5404    }
5405
5406    @Override
5407    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5408        if (!sUserManager.exists(userId)) return null;
5409        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5410
5411        // writer
5412        synchronized (mPackages) {
5413            ArrayList<ApplicationInfo> list;
5414            if (listUninstalled) {
5415                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5416                for (PackageSetting ps : mSettings.mPackages.values()) {
5417                    ApplicationInfo ai;
5418                    if (ps.pkg != null) {
5419                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5420                                ps.readUserState(userId), userId);
5421                    } else {
5422                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5423                    }
5424                    if (ai != null) {
5425                        list.add(ai);
5426                    }
5427                }
5428            } else {
5429                list = new ArrayList<ApplicationInfo>(mPackages.size());
5430                for (PackageParser.Package p : mPackages.values()) {
5431                    if (p.mExtras != null) {
5432                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5433                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5434                        if (ai != null) {
5435                            list.add(ai);
5436                        }
5437                    }
5438                }
5439            }
5440
5441            return new ParceledListSlice<ApplicationInfo>(list);
5442        }
5443    }
5444
5445    public List<ApplicationInfo> getPersistentApplications(int flags) {
5446        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5447
5448        // reader
5449        synchronized (mPackages) {
5450            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5451            final int userId = UserHandle.getCallingUserId();
5452            while (i.hasNext()) {
5453                final PackageParser.Package p = i.next();
5454                if (p.applicationInfo != null
5455                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5456                        && (!mSafeMode || isSystemApp(p))) {
5457                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5458                    if (ps != null) {
5459                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5460                                ps.readUserState(userId), userId);
5461                        if (ai != null) {
5462                            finalList.add(ai);
5463                        }
5464                    }
5465                }
5466            }
5467        }
5468
5469        return finalList;
5470    }
5471
5472    @Override
5473    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5474        if (!sUserManager.exists(userId)) return null;
5475        // reader
5476        synchronized (mPackages) {
5477            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5478            PackageSetting ps = provider != null
5479                    ? mSettings.mPackages.get(provider.owner.packageName)
5480                    : null;
5481            return ps != null
5482                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5483                    && (!mSafeMode || (provider.info.applicationInfo.flags
5484                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5485                    ? PackageParser.generateProviderInfo(provider, flags,
5486                            ps.readUserState(userId), userId)
5487                    : null;
5488        }
5489    }
5490
5491    /**
5492     * @deprecated
5493     */
5494    @Deprecated
5495    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5496        // reader
5497        synchronized (mPackages) {
5498            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5499                    .entrySet().iterator();
5500            final int userId = UserHandle.getCallingUserId();
5501            while (i.hasNext()) {
5502                Map.Entry<String, PackageParser.Provider> entry = i.next();
5503                PackageParser.Provider p = entry.getValue();
5504                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5505
5506                if (ps != null && p.syncable
5507                        && (!mSafeMode || (p.info.applicationInfo.flags
5508                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5509                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5510                            ps.readUserState(userId), userId);
5511                    if (info != null) {
5512                        outNames.add(entry.getKey());
5513                        outInfo.add(info);
5514                    }
5515                }
5516            }
5517        }
5518    }
5519
5520    @Override
5521    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5522            int uid, int flags) {
5523        ArrayList<ProviderInfo> finalList = null;
5524        // reader
5525        synchronized (mPackages) {
5526            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5527            final int userId = processName != null ?
5528                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5529            while (i.hasNext()) {
5530                final PackageParser.Provider p = i.next();
5531                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5532                if (ps != null && p.info.authority != null
5533                        && (processName == null
5534                                || (p.info.processName.equals(processName)
5535                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5536                        && mSettings.isEnabledLPr(p.info, flags, userId)
5537                        && (!mSafeMode
5538                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5539                    if (finalList == null) {
5540                        finalList = new ArrayList<ProviderInfo>(3);
5541                    }
5542                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5543                            ps.readUserState(userId), userId);
5544                    if (info != null) {
5545                        finalList.add(info);
5546                    }
5547                }
5548            }
5549        }
5550
5551        if (finalList != null) {
5552            Collections.sort(finalList, mProviderInitOrderSorter);
5553            return new ParceledListSlice<ProviderInfo>(finalList);
5554        }
5555
5556        return null;
5557    }
5558
5559    @Override
5560    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5561            int flags) {
5562        // reader
5563        synchronized (mPackages) {
5564            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5565            return PackageParser.generateInstrumentationInfo(i, flags);
5566        }
5567    }
5568
5569    @Override
5570    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5571            int flags) {
5572        ArrayList<InstrumentationInfo> finalList =
5573            new ArrayList<InstrumentationInfo>();
5574
5575        // reader
5576        synchronized (mPackages) {
5577            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5578            while (i.hasNext()) {
5579                final PackageParser.Instrumentation p = i.next();
5580                if (targetPackage == null
5581                        || targetPackage.equals(p.info.targetPackage)) {
5582                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5583                            flags);
5584                    if (ii != null) {
5585                        finalList.add(ii);
5586                    }
5587                }
5588            }
5589        }
5590
5591        return finalList;
5592    }
5593
5594    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5595        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5596        if (overlays == null) {
5597            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5598            return;
5599        }
5600        for (PackageParser.Package opkg : overlays.values()) {
5601            // Not much to do if idmap fails: we already logged the error
5602            // and we certainly don't want to abort installation of pkg simply
5603            // because an overlay didn't fit properly. For these reasons,
5604            // ignore the return value of createIdmapForPackagePairLI.
5605            createIdmapForPackagePairLI(pkg, opkg);
5606        }
5607    }
5608
5609    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5610            PackageParser.Package opkg) {
5611        if (!opkg.mTrustedOverlay) {
5612            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5613                    opkg.baseCodePath + ": overlay not trusted");
5614            return false;
5615        }
5616        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5617        if (overlaySet == null) {
5618            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5619                    opkg.baseCodePath + " but target package has no known overlays");
5620            return false;
5621        }
5622        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5623        // TODO: generate idmap for split APKs
5624        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5625            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5626                    + opkg.baseCodePath);
5627            return false;
5628        }
5629        PackageParser.Package[] overlayArray =
5630            overlaySet.values().toArray(new PackageParser.Package[0]);
5631        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5632            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5633                return p1.mOverlayPriority - p2.mOverlayPriority;
5634            }
5635        };
5636        Arrays.sort(overlayArray, cmp);
5637
5638        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5639        int i = 0;
5640        for (PackageParser.Package p : overlayArray) {
5641            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5642        }
5643        return true;
5644    }
5645
5646    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5647        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
5648        try {
5649            scanDirLI(dir, parseFlags, scanFlags, currentTime);
5650        } finally {
5651            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5652        }
5653    }
5654
5655    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5656        final File[] files = dir.listFiles();
5657        if (ArrayUtils.isEmpty(files)) {
5658            Log.d(TAG, "No files in app dir " + dir);
5659            return;
5660        }
5661
5662        if (DEBUG_PACKAGE_SCANNING) {
5663            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5664                    + " flags=0x" + Integer.toHexString(parseFlags));
5665        }
5666
5667        for (File file : files) {
5668            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5669                    && !PackageInstallerService.isStageName(file.getName());
5670            if (!isPackage) {
5671                // Ignore entries which are not packages
5672                continue;
5673            }
5674            try {
5675                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5676                        scanFlags, currentTime, null);
5677            } catch (PackageManagerException e) {
5678                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5679
5680                // Delete invalid userdata apps
5681                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5682                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5683                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5684                    if (file.isDirectory()) {
5685                        mInstaller.rmPackageDir(file.getAbsolutePath());
5686                    } else {
5687                        file.delete();
5688                    }
5689                }
5690            }
5691        }
5692    }
5693
5694    private static File getSettingsProblemFile() {
5695        File dataDir = Environment.getDataDirectory();
5696        File systemDir = new File(dataDir, "system");
5697        File fname = new File(systemDir, "uiderrors.txt");
5698        return fname;
5699    }
5700
5701    static void reportSettingsProblem(int priority, String msg) {
5702        logCriticalInfo(priority, msg);
5703    }
5704
5705    static void logCriticalInfo(int priority, String msg) {
5706        Slog.println(priority, TAG, msg);
5707        EventLogTags.writePmCriticalInfo(msg);
5708        try {
5709            File fname = getSettingsProblemFile();
5710            FileOutputStream out = new FileOutputStream(fname, true);
5711            PrintWriter pw = new FastPrintWriter(out);
5712            SimpleDateFormat formatter = new SimpleDateFormat();
5713            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5714            pw.println(dateString + ": " + msg);
5715            pw.close();
5716            FileUtils.setPermissions(
5717                    fname.toString(),
5718                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5719                    -1, -1);
5720        } catch (java.io.IOException e) {
5721        }
5722    }
5723
5724    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5725            PackageParser.Package pkg, File srcFile, int parseFlags)
5726            throws PackageManagerException {
5727        if (ps != null
5728                && ps.codePath.equals(srcFile)
5729                && ps.timeStamp == srcFile.lastModified()
5730                && !isCompatSignatureUpdateNeeded(pkg)
5731                && !isRecoverSignatureUpdateNeeded(pkg)) {
5732            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5733            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5734            ArraySet<PublicKey> signingKs;
5735            synchronized (mPackages) {
5736                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5737            }
5738            if (ps.signatures.mSignatures != null
5739                    && ps.signatures.mSignatures.length != 0
5740                    && signingKs != null) {
5741                // Optimization: reuse the existing cached certificates
5742                // if the package appears to be unchanged.
5743                pkg.mSignatures = ps.signatures.mSignatures;
5744                pkg.mSigningKeys = signingKs;
5745                return;
5746            }
5747
5748            Slog.w(TAG, "PackageSetting for " + ps.name
5749                    + " is missing signatures.  Collecting certs again to recover them.");
5750        } else {
5751            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5752        }
5753
5754        try {
5755            pp.collectCertificates(pkg, parseFlags);
5756            pp.collectManifestDigest(pkg);
5757        } catch (PackageParserException e) {
5758            throw PackageManagerException.from(e);
5759        }
5760    }
5761
5762    /**
5763     *  Traces a package scan.
5764     *  @see #scanPackageLI(File, int, int, long, UserHandle)
5765     */
5766    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
5767            long currentTime, UserHandle user) throws PackageManagerException {
5768        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
5769        try {
5770            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
5771        } finally {
5772            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5773        }
5774    }
5775
5776    /**
5777     *  Scans a package and returns the newly parsed package.
5778     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
5779     */
5780    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5781            long currentTime, UserHandle user) throws PackageManagerException {
5782        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5783        parseFlags |= mDefParseFlags;
5784        PackageParser pp = new PackageParser();
5785        pp.setSeparateProcesses(mSeparateProcesses);
5786        pp.setOnlyCoreApps(mOnlyCore);
5787        pp.setDisplayMetrics(mMetrics);
5788
5789        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5790            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5791        }
5792
5793        final PackageParser.Package pkg;
5794        try {
5795            pkg = pp.parsePackage(scanFile, parseFlags);
5796        } catch (PackageParserException e) {
5797            throw PackageManagerException.from(e);
5798        }
5799
5800        PackageSetting ps = null;
5801        PackageSetting updatedPkg;
5802        // reader
5803        synchronized (mPackages) {
5804            // Look to see if we already know about this package.
5805            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5806            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5807                // This package has been renamed to its original name.  Let's
5808                // use that.
5809                ps = mSettings.peekPackageLPr(oldName);
5810            }
5811            // If there was no original package, see one for the real package name.
5812            if (ps == null) {
5813                ps = mSettings.peekPackageLPr(pkg.packageName);
5814            }
5815            // Check to see if this package could be hiding/updating a system
5816            // package.  Must look for it either under the original or real
5817            // package name depending on our state.
5818            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5819            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5820        }
5821        boolean updatedPkgBetter = false;
5822        // First check if this is a system package that may involve an update
5823        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5824            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5825            // it needs to drop FLAG_PRIVILEGED.
5826            if (locationIsPrivileged(scanFile)) {
5827                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5828            } else {
5829                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5830            }
5831
5832            if (ps != null && !ps.codePath.equals(scanFile)) {
5833                // The path has changed from what was last scanned...  check the
5834                // version of the new path against what we have stored to determine
5835                // what to do.
5836                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5837                if (pkg.mVersionCode <= ps.versionCode) {
5838                    // The system package has been updated and the code path does not match
5839                    // Ignore entry. Skip it.
5840                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5841                            + " ignored: updated version " + ps.versionCode
5842                            + " better than this " + pkg.mVersionCode);
5843                    if (!updatedPkg.codePath.equals(scanFile)) {
5844                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5845                                + ps.name + " changing from " + updatedPkg.codePathString
5846                                + " to " + scanFile);
5847                        updatedPkg.codePath = scanFile;
5848                        updatedPkg.codePathString = scanFile.toString();
5849                        updatedPkg.resourcePath = scanFile;
5850                        updatedPkg.resourcePathString = scanFile.toString();
5851                    }
5852                    updatedPkg.pkg = pkg;
5853                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5854                            "Package " + ps.name + " at " + scanFile
5855                                    + " ignored: updated version " + ps.versionCode
5856                                    + " better than this " + pkg.mVersionCode);
5857                } else {
5858                    // The current app on the system partition is better than
5859                    // what we have updated to on the data partition; switch
5860                    // back to the system partition version.
5861                    // At this point, its safely assumed that package installation for
5862                    // apps in system partition will go through. If not there won't be a working
5863                    // version of the app
5864                    // writer
5865                    synchronized (mPackages) {
5866                        // Just remove the loaded entries from package lists.
5867                        mPackages.remove(ps.name);
5868                    }
5869
5870                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5871                            + " reverting from " + ps.codePathString
5872                            + ": new version " + pkg.mVersionCode
5873                            + " better than installed " + ps.versionCode);
5874
5875                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5876                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5877                    synchronized (mInstallLock) {
5878                        args.cleanUpResourcesLI();
5879                    }
5880                    synchronized (mPackages) {
5881                        mSettings.enableSystemPackageLPw(ps.name);
5882                    }
5883                    updatedPkgBetter = true;
5884                }
5885            }
5886        }
5887
5888        if (updatedPkg != null) {
5889            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5890            // initially
5891            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5892
5893            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5894            // flag set initially
5895            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5896                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5897            }
5898        }
5899
5900        // Verify certificates against what was last scanned
5901        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5902
5903        /*
5904         * A new system app appeared, but we already had a non-system one of the
5905         * same name installed earlier.
5906         */
5907        boolean shouldHideSystemApp = false;
5908        if (updatedPkg == null && ps != null
5909                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5910            /*
5911             * Check to make sure the signatures match first. If they don't,
5912             * wipe the installed application and its data.
5913             */
5914            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5915                    != PackageManager.SIGNATURE_MATCH) {
5916                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5917                        + " signatures don't match existing userdata copy; removing");
5918                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5919                ps = null;
5920            } else {
5921                /*
5922                 * If the newly-added system app is an older version than the
5923                 * already installed version, hide it. It will be scanned later
5924                 * and re-added like an update.
5925                 */
5926                if (pkg.mVersionCode <= ps.versionCode) {
5927                    shouldHideSystemApp = true;
5928                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5929                            + " but new version " + pkg.mVersionCode + " better than installed "
5930                            + ps.versionCode + "; hiding system");
5931                } else {
5932                    /*
5933                     * The newly found system app is a newer version that the
5934                     * one previously installed. Simply remove the
5935                     * already-installed application and replace it with our own
5936                     * while keeping the application data.
5937                     */
5938                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5939                            + " reverting from " + ps.codePathString + ": new version "
5940                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5941                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5942                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5943                    synchronized (mInstallLock) {
5944                        args.cleanUpResourcesLI();
5945                    }
5946                }
5947            }
5948        }
5949
5950        // The apk is forward locked (not public) if its code and resources
5951        // are kept in different files. (except for app in either system or
5952        // vendor path).
5953        // TODO grab this value from PackageSettings
5954        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5955            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5956                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5957            }
5958        }
5959
5960        // TODO: extend to support forward-locked splits
5961        String resourcePath = null;
5962        String baseResourcePath = null;
5963        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5964            if (ps != null && ps.resourcePathString != null) {
5965                resourcePath = ps.resourcePathString;
5966                baseResourcePath = ps.resourcePathString;
5967            } else {
5968                // Should not happen at all. Just log an error.
5969                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5970            }
5971        } else {
5972            resourcePath = pkg.codePath;
5973            baseResourcePath = pkg.baseCodePath;
5974        }
5975
5976        // Set application objects path explicitly.
5977        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5978        pkg.applicationInfo.setCodePath(pkg.codePath);
5979        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5980        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5981        pkg.applicationInfo.setResourcePath(resourcePath);
5982        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5983        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5984
5985        // Note that we invoke the following method only if we are about to unpack an application
5986        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5987                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5988
5989        /*
5990         * If the system app should be overridden by a previously installed
5991         * data, hide the system app now and let the /data/app scan pick it up
5992         * again.
5993         */
5994        if (shouldHideSystemApp) {
5995            synchronized (mPackages) {
5996                /*
5997                 * We have to grant systems permissions before we hide, because
5998                 * grantPermissions will assume the package update is trying to
5999                 * expand its permissions.
6000                 */
6001                grantPermissionsLPw(pkg, true, pkg.packageName);
6002                mSettings.disableSystemPackageLPw(pkg.packageName);
6003            }
6004        }
6005
6006        return scannedPkg;
6007    }
6008
6009    private static String fixProcessName(String defProcessName,
6010            String processName, int uid) {
6011        if (processName == null) {
6012            return defProcessName;
6013        }
6014        return processName;
6015    }
6016
6017    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6018            throws PackageManagerException {
6019        if (pkgSetting.signatures.mSignatures != null) {
6020            // Already existing package. Make sure signatures match
6021            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6022                    == PackageManager.SIGNATURE_MATCH;
6023            if (!match) {
6024                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6025                        == PackageManager.SIGNATURE_MATCH;
6026            }
6027            if (!match) {
6028                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6029                        == PackageManager.SIGNATURE_MATCH;
6030            }
6031            if (!match) {
6032                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6033                        + pkg.packageName + " signatures do not match the "
6034                        + "previously installed version; ignoring!");
6035            }
6036        }
6037
6038        // Check for shared user signatures
6039        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6040            // Already existing package. Make sure signatures match
6041            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6042                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6043            if (!match) {
6044                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6045                        == PackageManager.SIGNATURE_MATCH;
6046            }
6047            if (!match) {
6048                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6049                        == PackageManager.SIGNATURE_MATCH;
6050            }
6051            if (!match) {
6052                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6053                        "Package " + pkg.packageName
6054                        + " has no signatures that match those in shared user "
6055                        + pkgSetting.sharedUser.name + "; ignoring!");
6056            }
6057        }
6058    }
6059
6060    /**
6061     * Enforces that only the system UID or root's UID can call a method exposed
6062     * via Binder.
6063     *
6064     * @param message used as message if SecurityException is thrown
6065     * @throws SecurityException if the caller is not system or root
6066     */
6067    private static final void enforceSystemOrRoot(String message) {
6068        final int uid = Binder.getCallingUid();
6069        if (uid != Process.SYSTEM_UID && uid != 0) {
6070            throw new SecurityException(message);
6071        }
6072    }
6073
6074    @Override
6075    public void performBootDexOpt() {
6076        enforceSystemOrRoot("Only the system can request dexopt be performed");
6077
6078        // Before everything else, see whether we need to fstrim.
6079        try {
6080            IMountService ms = PackageHelper.getMountService();
6081            if (ms != null) {
6082                final boolean isUpgrade = isUpgrade();
6083                boolean doTrim = isUpgrade;
6084                if (doTrim) {
6085                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6086                } else {
6087                    final long interval = android.provider.Settings.Global.getLong(
6088                            mContext.getContentResolver(),
6089                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6090                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6091                    if (interval > 0) {
6092                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6093                        if (timeSinceLast > interval) {
6094                            doTrim = true;
6095                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6096                                    + "; running immediately");
6097                        }
6098                    }
6099                }
6100                if (doTrim) {
6101                    if (!isFirstBoot()) {
6102                        try {
6103                            ActivityManagerNative.getDefault().showBootMessage(
6104                                    mContext.getResources().getString(
6105                                            R.string.android_upgrading_fstrim), true);
6106                        } catch (RemoteException e) {
6107                        }
6108                    }
6109                    ms.runMaintenance();
6110                }
6111            } else {
6112                Slog.e(TAG, "Mount service unavailable!");
6113            }
6114        } catch (RemoteException e) {
6115            // Can't happen; MountService is local
6116        }
6117
6118        final ArraySet<PackageParser.Package> pkgs;
6119        synchronized (mPackages) {
6120            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6121        }
6122
6123        if (pkgs != null) {
6124            // Sort apps by importance for dexopt ordering. Important apps are given more priority
6125            // in case the device runs out of space.
6126            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6127            // Give priority to core apps.
6128            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6129                PackageParser.Package pkg = it.next();
6130                if (pkg.coreApp) {
6131                    if (DEBUG_DEXOPT) {
6132                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6133                    }
6134                    sortedPkgs.add(pkg);
6135                    it.remove();
6136                }
6137            }
6138            // Give priority to system apps that listen for pre boot complete.
6139            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6140            ArraySet<String> pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM);
6141            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6142                PackageParser.Package pkg = it.next();
6143                if (pkgNames.contains(pkg.packageName)) {
6144                    if (DEBUG_DEXOPT) {
6145                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6146                    }
6147                    sortedPkgs.add(pkg);
6148                    it.remove();
6149                }
6150            }
6151            // Give priority to system apps.
6152            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6153                PackageParser.Package pkg = it.next();
6154                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6155                    if (DEBUG_DEXOPT) {
6156                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6157                    }
6158                    sortedPkgs.add(pkg);
6159                    it.remove();
6160                }
6161            }
6162            // Give priority to updated system apps.
6163            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6164                PackageParser.Package pkg = it.next();
6165                if (pkg.isUpdatedSystemApp()) {
6166                    if (DEBUG_DEXOPT) {
6167                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6168                    }
6169                    sortedPkgs.add(pkg);
6170                    it.remove();
6171                }
6172            }
6173            // Give priority to apps that listen for boot complete.
6174            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6175            pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM);
6176            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6177                PackageParser.Package pkg = it.next();
6178                if (pkgNames.contains(pkg.packageName)) {
6179                    if (DEBUG_DEXOPT) {
6180                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6181                    }
6182                    sortedPkgs.add(pkg);
6183                    it.remove();
6184                }
6185            }
6186            // Filter out packages that aren't recently used.
6187            filterRecentlyUsedApps(pkgs);
6188            // Add all remaining apps.
6189            for (PackageParser.Package pkg : pkgs) {
6190                if (DEBUG_DEXOPT) {
6191                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6192                }
6193                sortedPkgs.add(pkg);
6194            }
6195
6196            // If we want to be lazy, filter everything that wasn't recently used.
6197            if (mLazyDexOpt) {
6198                filterRecentlyUsedApps(sortedPkgs);
6199            }
6200
6201            int i = 0;
6202            int total = sortedPkgs.size();
6203            File dataDir = Environment.getDataDirectory();
6204            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6205            if (lowThreshold == 0) {
6206                throw new IllegalStateException("Invalid low memory threshold");
6207            }
6208            for (PackageParser.Package pkg : sortedPkgs) {
6209                long usableSpace = dataDir.getUsableSpace();
6210                if (usableSpace < lowThreshold) {
6211                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6212                    break;
6213                }
6214                performBootDexOpt(pkg, ++i, total);
6215            }
6216        }
6217    }
6218
6219    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6220        // Filter out packages that aren't recently used.
6221        //
6222        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6223        // should do a full dexopt.
6224        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6225            int total = pkgs.size();
6226            int skipped = 0;
6227            long now = System.currentTimeMillis();
6228            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6229                PackageParser.Package pkg = i.next();
6230                long then = pkg.mLastPackageUsageTimeInMills;
6231                if (then + mDexOptLRUThresholdInMills < now) {
6232                    if (DEBUG_DEXOPT) {
6233                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6234                              ((then == 0) ? "never" : new Date(then)));
6235                    }
6236                    i.remove();
6237                    skipped++;
6238                }
6239            }
6240            if (DEBUG_DEXOPT) {
6241                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6242            }
6243        }
6244    }
6245
6246    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6247        List<ResolveInfo> ris = null;
6248        try {
6249            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6250                    intent, null, 0, userId);
6251        } catch (RemoteException e) {
6252        }
6253        ArraySet<String> pkgNames = new ArraySet<String>();
6254        if (ris != null) {
6255            for (ResolveInfo ri : ris) {
6256                pkgNames.add(ri.activityInfo.packageName);
6257            }
6258        }
6259        return pkgNames;
6260    }
6261
6262    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6263        if (DEBUG_DEXOPT) {
6264            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6265        }
6266        if (!isFirstBoot()) {
6267            try {
6268                ActivityManagerNative.getDefault().showBootMessage(
6269                        mContext.getResources().getString(R.string.android_upgrading_apk,
6270                                curr, total), true);
6271            } catch (RemoteException e) {
6272            }
6273        }
6274        PackageParser.Package p = pkg;
6275        synchronized (mInstallLock) {
6276            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6277                    false /* force dex */, false /* defer */, true /* include dependencies */);
6278        }
6279    }
6280
6281    @Override
6282    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6283        return performDexOptTraced(packageName, instructionSet, false);
6284    }
6285
6286    public boolean performDexOpt(
6287            String packageName, String instructionSet, boolean backgroundDexopt) {
6288        return performDexOptTraced(packageName, instructionSet, backgroundDexopt);
6289    }
6290
6291    private boolean performDexOptTraced(
6292            String packageName, String instructionSet, boolean backgroundDexopt) {
6293        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6294        try {
6295            return performDexOptInternal(packageName, instructionSet, backgroundDexopt);
6296        } finally {
6297            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6298        }
6299    }
6300
6301    private boolean performDexOptInternal(
6302            String packageName, String instructionSet, boolean backgroundDexopt) {
6303        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6304        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6305        if (!dexopt && !updateUsage) {
6306            // We aren't going to dexopt or update usage, so bail early.
6307            return false;
6308        }
6309        PackageParser.Package p;
6310        final String targetInstructionSet;
6311        synchronized (mPackages) {
6312            p = mPackages.get(packageName);
6313            if (p == null) {
6314                return false;
6315            }
6316            if (updateUsage) {
6317                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6318            }
6319            mPackageUsage.write(false);
6320            if (!dexopt) {
6321                // We aren't going to dexopt, so bail early.
6322                return false;
6323            }
6324
6325            targetInstructionSet = instructionSet != null ? instructionSet :
6326                    getPrimaryInstructionSet(p.applicationInfo);
6327            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6328                return false;
6329            }
6330        }
6331        long callingId = Binder.clearCallingIdentity();
6332        try {
6333            synchronized (mInstallLock) {
6334                final String[] instructionSets = new String[] { targetInstructionSet };
6335                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6336                        false /* forceDex */, false /* defer */, true /* inclDependencies */);
6337                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6338            }
6339        } finally {
6340            Binder.restoreCallingIdentity(callingId);
6341        }
6342    }
6343
6344    public ArraySet<String> getPackagesThatNeedDexOpt() {
6345        ArraySet<String> pkgs = null;
6346        synchronized (mPackages) {
6347            for (PackageParser.Package p : mPackages.values()) {
6348                if (DEBUG_DEXOPT) {
6349                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6350                }
6351                if (!p.mDexOptPerformed.isEmpty()) {
6352                    continue;
6353                }
6354                if (pkgs == null) {
6355                    pkgs = new ArraySet<String>();
6356                }
6357                pkgs.add(p.packageName);
6358            }
6359        }
6360        return pkgs;
6361    }
6362
6363    public void shutdown() {
6364        mPackageUsage.write(true);
6365    }
6366
6367    @Override
6368    public void forceDexOpt(String packageName) {
6369        enforceSystemOrRoot("forceDexOpt");
6370
6371        PackageParser.Package pkg;
6372        synchronized (mPackages) {
6373            pkg = mPackages.get(packageName);
6374            if (pkg == null) {
6375                throw new IllegalArgumentException("Missing package: " + packageName);
6376            }
6377        }
6378
6379        synchronized (mInstallLock) {
6380            final String[] instructionSets = new String[] {
6381                    getPrimaryInstructionSet(pkg.applicationInfo) };
6382
6383            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6384
6385            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6386                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6387
6388            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6389            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6390                throw new IllegalStateException("Failed to dexopt: " + res);
6391            }
6392        }
6393    }
6394
6395    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6396        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6397            Slog.w(TAG, "Unable to update from " + oldPkg.name
6398                    + " to " + newPkg.packageName
6399                    + ": old package not in system partition");
6400            return false;
6401        } else if (mPackages.get(oldPkg.name) != null) {
6402            Slog.w(TAG, "Unable to update from " + oldPkg.name
6403                    + " to " + newPkg.packageName
6404                    + ": old package still exists");
6405            return false;
6406        }
6407        return true;
6408    }
6409
6410    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6411        int[] users = sUserManager.getUserIds();
6412        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6413        if (res < 0) {
6414            return res;
6415        }
6416        for (int user : users) {
6417            if (user != 0) {
6418                res = mInstaller.createUserData(volumeUuid, packageName,
6419                        UserHandle.getUid(user, uid), user, seinfo);
6420                if (res < 0) {
6421                    return res;
6422                }
6423            }
6424        }
6425        return res;
6426    }
6427
6428    private int removeDataDirsLI(String volumeUuid, String packageName) {
6429        int[] users = sUserManager.getUserIds();
6430        int res = 0;
6431        for (int user : users) {
6432            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6433            if (resInner < 0) {
6434                res = resInner;
6435            }
6436        }
6437
6438        return res;
6439    }
6440
6441    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6442        int[] users = sUserManager.getUserIds();
6443        int res = 0;
6444        for (int user : users) {
6445            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6446            if (resInner < 0) {
6447                res = resInner;
6448            }
6449        }
6450        return res;
6451    }
6452
6453    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6454            PackageParser.Package changingLib) {
6455        if (file.path != null) {
6456            usesLibraryFiles.add(file.path);
6457            return;
6458        }
6459        PackageParser.Package p = mPackages.get(file.apk);
6460        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6461            // If we are doing this while in the middle of updating a library apk,
6462            // then we need to make sure to use that new apk for determining the
6463            // dependencies here.  (We haven't yet finished committing the new apk
6464            // to the package manager state.)
6465            if (p == null || p.packageName.equals(changingLib.packageName)) {
6466                p = changingLib;
6467            }
6468        }
6469        if (p != null) {
6470            usesLibraryFiles.addAll(p.getAllCodePaths());
6471        }
6472    }
6473
6474    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6475            PackageParser.Package changingLib) throws PackageManagerException {
6476        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6477            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6478            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6479            for (int i=0; i<N; i++) {
6480                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6481                if (file == null) {
6482                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6483                            "Package " + pkg.packageName + " requires unavailable shared library "
6484                            + pkg.usesLibraries.get(i) + "; failing!");
6485                }
6486                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6487            }
6488            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6489            for (int i=0; i<N; i++) {
6490                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6491                if (file == null) {
6492                    Slog.w(TAG, "Package " + pkg.packageName
6493                            + " desires unavailable shared library "
6494                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6495                } else {
6496                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6497                }
6498            }
6499            N = usesLibraryFiles.size();
6500            if (N > 0) {
6501                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6502            } else {
6503                pkg.usesLibraryFiles = null;
6504            }
6505        }
6506    }
6507
6508    private static boolean hasString(List<String> list, List<String> which) {
6509        if (list == null) {
6510            return false;
6511        }
6512        for (int i=list.size()-1; i>=0; i--) {
6513            for (int j=which.size()-1; j>=0; j--) {
6514                if (which.get(j).equals(list.get(i))) {
6515                    return true;
6516                }
6517            }
6518        }
6519        return false;
6520    }
6521
6522    private void updateAllSharedLibrariesLPw() {
6523        for (PackageParser.Package pkg : mPackages.values()) {
6524            try {
6525                updateSharedLibrariesLPw(pkg, null);
6526            } catch (PackageManagerException e) {
6527                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6528            }
6529        }
6530    }
6531
6532    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6533            PackageParser.Package changingPkg) {
6534        ArrayList<PackageParser.Package> res = null;
6535        for (PackageParser.Package pkg : mPackages.values()) {
6536            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6537                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6538                if (res == null) {
6539                    res = new ArrayList<PackageParser.Package>();
6540                }
6541                res.add(pkg);
6542                try {
6543                    updateSharedLibrariesLPw(pkg, changingPkg);
6544                } catch (PackageManagerException e) {
6545                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6546                }
6547            }
6548        }
6549        return res;
6550    }
6551
6552    /**
6553     * Derive the value of the {@code cpuAbiOverride} based on the provided
6554     * value and an optional stored value from the package settings.
6555     */
6556    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6557        String cpuAbiOverride = null;
6558
6559        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6560            cpuAbiOverride = null;
6561        } else if (abiOverride != null) {
6562            cpuAbiOverride = abiOverride;
6563        } else if (settings != null) {
6564            cpuAbiOverride = settings.cpuAbiOverrideString;
6565        }
6566
6567        return cpuAbiOverride;
6568    }
6569
6570    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6571            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6572        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6573        try {
6574            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6575        } finally {
6576            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6577        }
6578    }
6579
6580    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6581            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6582        boolean success = false;
6583        try {
6584            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6585                    currentTime, user);
6586            success = true;
6587            return res;
6588        } finally {
6589            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6590                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6591            }
6592        }
6593    }
6594
6595    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6596            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6597        final File scanFile = new File(pkg.codePath);
6598        if (pkg.applicationInfo.getCodePath() == null ||
6599                pkg.applicationInfo.getResourcePath() == null) {
6600            // Bail out. The resource and code paths haven't been set.
6601            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6602                    "Code and resource paths haven't been set correctly");
6603        }
6604
6605        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6606            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6607        } else {
6608            // Only allow system apps to be flagged as core apps.
6609            pkg.coreApp = false;
6610        }
6611
6612        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6613            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6614        }
6615
6616        if (mCustomResolverComponentName != null &&
6617                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6618            setUpCustomResolverActivity(pkg);
6619        }
6620
6621        if (pkg.packageName.equals("android")) {
6622            synchronized (mPackages) {
6623                if (mAndroidApplication != null) {
6624                    Slog.w(TAG, "*************************************************");
6625                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6626                    Slog.w(TAG, " file=" + scanFile);
6627                    Slog.w(TAG, "*************************************************");
6628                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6629                            "Core android package being redefined.  Skipping.");
6630                }
6631
6632                // Set up information for our fall-back user intent resolution activity.
6633                mPlatformPackage = pkg;
6634                pkg.mVersionCode = mSdkVersion;
6635                mAndroidApplication = pkg.applicationInfo;
6636
6637                if (!mResolverReplaced) {
6638                    mResolveActivity.applicationInfo = mAndroidApplication;
6639                    mResolveActivity.name = ResolverActivity.class.getName();
6640                    mResolveActivity.packageName = mAndroidApplication.packageName;
6641                    mResolveActivity.processName = "system:ui";
6642                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6643                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6644                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6645                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6646                    mResolveActivity.exported = true;
6647                    mResolveActivity.enabled = true;
6648                    mResolveInfo.activityInfo = mResolveActivity;
6649                    mResolveInfo.priority = 0;
6650                    mResolveInfo.preferredOrder = 0;
6651                    mResolveInfo.match = 0;
6652                    mResolveComponentName = new ComponentName(
6653                            mAndroidApplication.packageName, mResolveActivity.name);
6654                }
6655            }
6656        }
6657
6658        if (DEBUG_PACKAGE_SCANNING) {
6659            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6660                Log.d(TAG, "Scanning package " + pkg.packageName);
6661        }
6662
6663        if (mPackages.containsKey(pkg.packageName)
6664                || mSharedLibraries.containsKey(pkg.packageName)) {
6665            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6666                    "Application package " + pkg.packageName
6667                    + " already installed.  Skipping duplicate.");
6668        }
6669
6670        // If we're only installing presumed-existing packages, require that the
6671        // scanned APK is both already known and at the path previously established
6672        // for it.  Previously unknown packages we pick up normally, but if we have an
6673        // a priori expectation about this package's install presence, enforce it.
6674        // With a singular exception for new system packages. When an OTA contains
6675        // a new system package, we allow the codepath to change from a system location
6676        // to the user-installed location. If we don't allow this change, any newer,
6677        // user-installed version of the application will be ignored.
6678        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6679            if (mExpectingBetter.containsKey(pkg.packageName)) {
6680                logCriticalInfo(Log.WARN,
6681                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6682            } else {
6683                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6684                if (known != null) {
6685                    if (DEBUG_PACKAGE_SCANNING) {
6686                        Log.d(TAG, "Examining " + pkg.codePath
6687                                + " and requiring known paths " + known.codePathString
6688                                + " & " + known.resourcePathString);
6689                    }
6690                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6691                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6692                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6693                                "Application package " + pkg.packageName
6694                                + " found at " + pkg.applicationInfo.getCodePath()
6695                                + " but expected at " + known.codePathString + "; ignoring.");
6696                    }
6697                }
6698            }
6699        }
6700
6701        // Initialize package source and resource directories
6702        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6703        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6704
6705        SharedUserSetting suid = null;
6706        PackageSetting pkgSetting = null;
6707
6708        if (!isSystemApp(pkg)) {
6709            // Only system apps can use these features.
6710            pkg.mOriginalPackages = null;
6711            pkg.mRealPackage = null;
6712            pkg.mAdoptPermissions = null;
6713        }
6714
6715        // writer
6716        synchronized (mPackages) {
6717            if (pkg.mSharedUserId != null) {
6718                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6719                if (suid == null) {
6720                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6721                            "Creating application package " + pkg.packageName
6722                            + " for shared user failed");
6723                }
6724                if (DEBUG_PACKAGE_SCANNING) {
6725                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6726                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6727                                + "): packages=" + suid.packages);
6728                }
6729            }
6730
6731            // Check if we are renaming from an original package name.
6732            PackageSetting origPackage = null;
6733            String realName = null;
6734            if (pkg.mOriginalPackages != null) {
6735                // This package may need to be renamed to a previously
6736                // installed name.  Let's check on that...
6737                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6738                if (pkg.mOriginalPackages.contains(renamed)) {
6739                    // This package had originally been installed as the
6740                    // original name, and we have already taken care of
6741                    // transitioning to the new one.  Just update the new
6742                    // one to continue using the old name.
6743                    realName = pkg.mRealPackage;
6744                    if (!pkg.packageName.equals(renamed)) {
6745                        // Callers into this function may have already taken
6746                        // care of renaming the package; only do it here if
6747                        // it is not already done.
6748                        pkg.setPackageName(renamed);
6749                    }
6750
6751                } else {
6752                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6753                        if ((origPackage = mSettings.peekPackageLPr(
6754                                pkg.mOriginalPackages.get(i))) != null) {
6755                            // We do have the package already installed under its
6756                            // original name...  should we use it?
6757                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6758                                // New package is not compatible with original.
6759                                origPackage = null;
6760                                continue;
6761                            } else if (origPackage.sharedUser != null) {
6762                                // Make sure uid is compatible between packages.
6763                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6764                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6765                                            + " to " + pkg.packageName + ": old uid "
6766                                            + origPackage.sharedUser.name
6767                                            + " differs from " + pkg.mSharedUserId);
6768                                    origPackage = null;
6769                                    continue;
6770                                }
6771                            } else {
6772                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6773                                        + pkg.packageName + " to old name " + origPackage.name);
6774                            }
6775                            break;
6776                        }
6777                    }
6778                }
6779            }
6780
6781            if (mTransferedPackages.contains(pkg.packageName)) {
6782                Slog.w(TAG, "Package " + pkg.packageName
6783                        + " was transferred to another, but its .apk remains");
6784            }
6785
6786            // Just create the setting, don't add it yet. For already existing packages
6787            // the PkgSetting exists already and doesn't have to be created.
6788            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6789                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6790                    pkg.applicationInfo.primaryCpuAbi,
6791                    pkg.applicationInfo.secondaryCpuAbi,
6792                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6793                    user, false);
6794            if (pkgSetting == null) {
6795                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6796                        "Creating application package " + pkg.packageName + " failed");
6797            }
6798
6799            if (pkgSetting.origPackage != null) {
6800                // If we are first transitioning from an original package,
6801                // fix up the new package's name now.  We need to do this after
6802                // looking up the package under its new name, so getPackageLP
6803                // can take care of fiddling things correctly.
6804                pkg.setPackageName(origPackage.name);
6805
6806                // File a report about this.
6807                String msg = "New package " + pkgSetting.realName
6808                        + " renamed to replace old package " + pkgSetting.name;
6809                reportSettingsProblem(Log.WARN, msg);
6810
6811                // Make a note of it.
6812                mTransferedPackages.add(origPackage.name);
6813
6814                // No longer need to retain this.
6815                pkgSetting.origPackage = null;
6816            }
6817
6818            if (realName != null) {
6819                // Make a note of it.
6820                mTransferedPackages.add(pkg.packageName);
6821            }
6822
6823            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6824                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6825            }
6826
6827            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6828                // Check all shared libraries and map to their actual file path.
6829                // We only do this here for apps not on a system dir, because those
6830                // are the only ones that can fail an install due to this.  We
6831                // will take care of the system apps by updating all of their
6832                // library paths after the scan is done.
6833                updateSharedLibrariesLPw(pkg, null);
6834            }
6835
6836            if (mFoundPolicyFile) {
6837                SELinuxMMAC.assignSeinfoValue(pkg);
6838            }
6839
6840            pkg.applicationInfo.uid = pkgSetting.appId;
6841            pkg.mExtras = pkgSetting;
6842            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6843                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6844                    // We just determined the app is signed correctly, so bring
6845                    // over the latest parsed certs.
6846                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6847                } else {
6848                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6849                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6850                                "Package " + pkg.packageName + " upgrade keys do not match the "
6851                                + "previously installed version");
6852                    } else {
6853                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6854                        String msg = "System package " + pkg.packageName
6855                            + " signature changed; retaining data.";
6856                        reportSettingsProblem(Log.WARN, msg);
6857                    }
6858                }
6859            } else {
6860                try {
6861                    verifySignaturesLP(pkgSetting, pkg);
6862                    // We just determined the app is signed correctly, so bring
6863                    // over the latest parsed certs.
6864                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6865                } catch (PackageManagerException e) {
6866                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6867                        throw e;
6868                    }
6869                    // The signature has changed, but this package is in the system
6870                    // image...  let's recover!
6871                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6872                    // However...  if this package is part of a shared user, but it
6873                    // doesn't match the signature of the shared user, let's fail.
6874                    // What this means is that you can't change the signatures
6875                    // associated with an overall shared user, which doesn't seem all
6876                    // that unreasonable.
6877                    if (pkgSetting.sharedUser != null) {
6878                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6879                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6880                            throw new PackageManagerException(
6881                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6882                                            "Signature mismatch for shared user : "
6883                                            + pkgSetting.sharedUser);
6884                        }
6885                    }
6886                    // File a report about this.
6887                    String msg = "System package " + pkg.packageName
6888                        + " signature changed; retaining data.";
6889                    reportSettingsProblem(Log.WARN, msg);
6890                }
6891            }
6892            // Verify that this new package doesn't have any content providers
6893            // that conflict with existing packages.  Only do this if the
6894            // package isn't already installed, since we don't want to break
6895            // things that are installed.
6896            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6897                final int N = pkg.providers.size();
6898                int i;
6899                for (i=0; i<N; i++) {
6900                    PackageParser.Provider p = pkg.providers.get(i);
6901                    if (p.info.authority != null) {
6902                        String names[] = p.info.authority.split(";");
6903                        for (int j = 0; j < names.length; j++) {
6904                            if (mProvidersByAuthority.containsKey(names[j])) {
6905                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6906                                final String otherPackageName =
6907                                        ((other != null && other.getComponentName() != null) ?
6908                                                other.getComponentName().getPackageName() : "?");
6909                                throw new PackageManagerException(
6910                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6911                                                "Can't install because provider name " + names[j]
6912                                                + " (in package " + pkg.applicationInfo.packageName
6913                                                + ") is already used by " + otherPackageName);
6914                            }
6915                        }
6916                    }
6917                }
6918            }
6919
6920            if (pkg.mAdoptPermissions != null) {
6921                // This package wants to adopt ownership of permissions from
6922                // another package.
6923                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6924                    final String origName = pkg.mAdoptPermissions.get(i);
6925                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6926                    if (orig != null) {
6927                        if (verifyPackageUpdateLPr(orig, pkg)) {
6928                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6929                                    + pkg.packageName);
6930                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6931                        }
6932                    }
6933                }
6934            }
6935        }
6936
6937        final String pkgName = pkg.packageName;
6938
6939        final long scanFileTime = scanFile.lastModified();
6940        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6941        pkg.applicationInfo.processName = fixProcessName(
6942                pkg.applicationInfo.packageName,
6943                pkg.applicationInfo.processName,
6944                pkg.applicationInfo.uid);
6945
6946        File dataPath;
6947        if (mPlatformPackage == pkg) {
6948            // The system package is special.
6949            dataPath = new File(Environment.getDataDirectory(), "system");
6950
6951            pkg.applicationInfo.dataDir = dataPath.getPath();
6952
6953        } else {
6954            // This is a normal package, need to make its data directory.
6955            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6956                    UserHandle.USER_OWNER, pkg.packageName);
6957
6958            boolean uidError = false;
6959            if (dataPath.exists()) {
6960                int currentUid = 0;
6961                try {
6962                    StructStat stat = Os.stat(dataPath.getPath());
6963                    currentUid = stat.st_uid;
6964                } catch (ErrnoException e) {
6965                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6966                }
6967
6968                // If we have mismatched owners for the data path, we have a problem.
6969                if (currentUid != pkg.applicationInfo.uid) {
6970                    boolean recovered = false;
6971                    if (currentUid == 0) {
6972                        // The directory somehow became owned by root.  Wow.
6973                        // This is probably because the system was stopped while
6974                        // installd was in the middle of messing with its libs
6975                        // directory.  Ask installd to fix that.
6976                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6977                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6978                        if (ret >= 0) {
6979                            recovered = true;
6980                            String msg = "Package " + pkg.packageName
6981                                    + " unexpectedly changed to uid 0; recovered to " +
6982                                    + pkg.applicationInfo.uid;
6983                            reportSettingsProblem(Log.WARN, msg);
6984                        }
6985                    }
6986                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6987                            || (scanFlags&SCAN_BOOTING) != 0)) {
6988                        // If this is a system app, we can at least delete its
6989                        // current data so the application will still work.
6990                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6991                        if (ret >= 0) {
6992                            // TODO: Kill the processes first
6993                            // Old data gone!
6994                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6995                                    ? "System package " : "Third party package ";
6996                            String msg = prefix + pkg.packageName
6997                                    + " has changed from uid: "
6998                                    + currentUid + " to "
6999                                    + pkg.applicationInfo.uid + "; old data erased";
7000                            reportSettingsProblem(Log.WARN, msg);
7001                            recovered = true;
7002
7003                            // And now re-install the app.
7004                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7005                                    pkg.applicationInfo.seinfo);
7006                            if (ret == -1) {
7007                                // Ack should not happen!
7008                                msg = prefix + pkg.packageName
7009                                        + " could not have data directory re-created after delete.";
7010                                reportSettingsProblem(Log.WARN, msg);
7011                                throw new PackageManagerException(
7012                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
7013                            }
7014                        }
7015                        if (!recovered) {
7016                            mHasSystemUidErrors = true;
7017                        }
7018                    } else if (!recovered) {
7019                        // If we allow this install to proceed, we will be broken.
7020                        // Abort, abort!
7021                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7022                                "scanPackageLI");
7023                    }
7024                    if (!recovered) {
7025                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7026                            + pkg.applicationInfo.uid + "/fs_"
7027                            + currentUid;
7028                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7029                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7030                        String msg = "Package " + pkg.packageName
7031                                + " has mismatched uid: "
7032                                + currentUid + " on disk, "
7033                                + pkg.applicationInfo.uid + " in settings";
7034                        // writer
7035                        synchronized (mPackages) {
7036                            mSettings.mReadMessages.append(msg);
7037                            mSettings.mReadMessages.append('\n');
7038                            uidError = true;
7039                            if (!pkgSetting.uidError) {
7040                                reportSettingsProblem(Log.ERROR, msg);
7041                            }
7042                        }
7043                    }
7044                }
7045                pkg.applicationInfo.dataDir = dataPath.getPath();
7046                if (mShouldRestoreconData) {
7047                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7048                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7049                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7050                }
7051            } else {
7052                if (DEBUG_PACKAGE_SCANNING) {
7053                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7054                        Log.v(TAG, "Want this data dir: " + dataPath);
7055                }
7056                //invoke installer to do the actual installation
7057                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7058                        pkg.applicationInfo.seinfo);
7059                if (ret < 0) {
7060                    // Error from installer
7061                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7062                            "Unable to create data dirs [errorCode=" + ret + "]");
7063                }
7064
7065                if (dataPath.exists()) {
7066                    pkg.applicationInfo.dataDir = dataPath.getPath();
7067                } else {
7068                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
7069                    pkg.applicationInfo.dataDir = null;
7070                }
7071            }
7072
7073            pkgSetting.uidError = uidError;
7074        }
7075
7076        final String path = scanFile.getPath();
7077        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7078
7079        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7080            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7081
7082            // Some system apps still use directory structure for native libraries
7083            // in which case we might end up not detecting abi solely based on apk
7084            // structure. Try to detect abi based on directory structure.
7085            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7086                    pkg.applicationInfo.primaryCpuAbi == null) {
7087                setBundledAppAbisAndRoots(pkg, pkgSetting);
7088                setNativeLibraryPaths(pkg);
7089            }
7090
7091        } else {
7092            if ((scanFlags & SCAN_MOVE) != 0) {
7093                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7094                // but we already have this packages package info in the PackageSetting. We just
7095                // use that and derive the native library path based on the new codepath.
7096                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7097                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7098            }
7099
7100            // Set native library paths again. For moves, the path will be updated based on the
7101            // ABIs we've determined above. For non-moves, the path will be updated based on the
7102            // ABIs we determined during compilation, but the path will depend on the final
7103            // package path (after the rename away from the stage path).
7104            setNativeLibraryPaths(pkg);
7105        }
7106
7107        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7108        final int[] userIds = sUserManager.getUserIds();
7109        synchronized (mInstallLock) {
7110            // Make sure all user data directories are ready to roll; we're okay
7111            // if they already exist
7112            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7113                for (int userId : userIds) {
7114                    if (userId != 0) {
7115                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7116                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7117                                pkg.applicationInfo.seinfo);
7118                    }
7119                }
7120            }
7121
7122            // Create a native library symlink only if we have native libraries
7123            // and if the native libraries are 32 bit libraries. We do not provide
7124            // this symlink for 64 bit libraries.
7125            if (pkg.applicationInfo.primaryCpuAbi != null &&
7126                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7127                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7128                try {
7129                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7130                    for (int userId : userIds) {
7131                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7132                                nativeLibPath, userId) < 0) {
7133                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7134                                    "Failed linking native library dir (user=" + userId + ")");
7135                        }
7136                    }
7137                } finally {
7138                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7139                }
7140            }
7141        }
7142
7143        // This is a special case for the "system" package, where the ABI is
7144        // dictated by the zygote configuration (and init.rc). We should keep track
7145        // of this ABI so that we can deal with "normal" applications that run under
7146        // the same UID correctly.
7147        if (mPlatformPackage == pkg) {
7148            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7149                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7150        }
7151
7152        // If there's a mismatch between the abi-override in the package setting
7153        // and the abiOverride specified for the install. Warn about this because we
7154        // would've already compiled the app without taking the package setting into
7155        // account.
7156        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7157            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7158                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7159                        " for package: " + pkg.packageName);
7160            }
7161        }
7162
7163        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7164        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7165        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7166
7167        // Copy the derived override back to the parsed package, so that we can
7168        // update the package settings accordingly.
7169        pkg.cpuAbiOverride = cpuAbiOverride;
7170
7171        if (DEBUG_ABI_SELECTION) {
7172            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7173                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7174                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7175        }
7176
7177        // Push the derived path down into PackageSettings so we know what to
7178        // clean up at uninstall time.
7179        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7180
7181        if (DEBUG_ABI_SELECTION) {
7182            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7183                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7184                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7185        }
7186
7187        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7188            // We don't do this here during boot because we can do it all
7189            // at once after scanning all existing packages.
7190            //
7191            // We also do this *before* we perform dexopt on this package, so that
7192            // we can avoid redundant dexopts, and also to make sure we've got the
7193            // code and package path correct.
7194            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7195                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
7196        }
7197
7198        if ((scanFlags & SCAN_NO_DEX) == 0) {
7199            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7200
7201            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7202                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
7203
7204            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7205            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7206                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7207            }
7208        }
7209        if (mFactoryTest && pkg.requestedPermissions.contains(
7210                android.Manifest.permission.FACTORY_TEST)) {
7211            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7212        }
7213
7214        ArrayList<PackageParser.Package> clientLibPkgs = null;
7215
7216        // writer
7217        synchronized (mPackages) {
7218            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7219                // Only system apps can add new shared libraries.
7220                if (pkg.libraryNames != null) {
7221                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7222                        String name = pkg.libraryNames.get(i);
7223                        boolean allowed = false;
7224                        if (pkg.isUpdatedSystemApp()) {
7225                            // New library entries can only be added through the
7226                            // system image.  This is important to get rid of a lot
7227                            // of nasty edge cases: for example if we allowed a non-
7228                            // system update of the app to add a library, then uninstalling
7229                            // the update would make the library go away, and assumptions
7230                            // we made such as through app install filtering would now
7231                            // have allowed apps on the device which aren't compatible
7232                            // with it.  Better to just have the restriction here, be
7233                            // conservative, and create many fewer cases that can negatively
7234                            // impact the user experience.
7235                            final PackageSetting sysPs = mSettings
7236                                    .getDisabledSystemPkgLPr(pkg.packageName);
7237                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7238                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7239                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7240                                        allowed = true;
7241                                        allowed = true;
7242                                        break;
7243                                    }
7244                                }
7245                            }
7246                        } else {
7247                            allowed = true;
7248                        }
7249                        if (allowed) {
7250                            if (!mSharedLibraries.containsKey(name)) {
7251                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7252                            } else if (!name.equals(pkg.packageName)) {
7253                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7254                                        + name + " already exists; skipping");
7255                            }
7256                        } else {
7257                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7258                                    + name + " that is not declared on system image; skipping");
7259                        }
7260                    }
7261                    if ((scanFlags&SCAN_BOOTING) == 0) {
7262                        // If we are not booting, we need to update any applications
7263                        // that are clients of our shared library.  If we are booting,
7264                        // this will all be done once the scan is complete.
7265                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7266                    }
7267                }
7268            }
7269        }
7270
7271        // We also need to dexopt any apps that are dependent on this library.  Note that
7272        // if these fail, we should abort the install since installing the library will
7273        // result in some apps being broken.
7274        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7275        try {
7276            if (clientLibPkgs != null) {
7277                if ((scanFlags & SCAN_NO_DEX) == 0) {
7278                    for (int i = 0; i < clientLibPkgs.size(); i++) {
7279                        PackageParser.Package clientPkg = clientLibPkgs.get(i);
7280                        int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7281                                null /* instruction sets */, forceDex,
7282                                (scanFlags & SCAN_DEFER_DEX) != 0, false);
7283                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7284                            throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7285                                    "scanPackageLI failed to dexopt clientLibPkgs");
7286                        }
7287                    }
7288                }
7289            }
7290        } finally {
7291            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7292        }
7293
7294        // Request the ActivityManager to kill the process(only for existing packages)
7295        // so that we do not end up in a confused state while the user is still using the older
7296        // version of the application while the new one gets installed.
7297        if ((scanFlags & SCAN_REPLACING) != 0) {
7298            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7299
7300            killApplication(pkg.applicationInfo.packageName,
7301                        pkg.applicationInfo.uid, "replace pkg");
7302
7303            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7304        }
7305
7306        // Also need to kill any apps that are dependent on the library.
7307        if (clientLibPkgs != null) {
7308            for (int i=0; i<clientLibPkgs.size(); i++) {
7309                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7310                killApplication(clientPkg.applicationInfo.packageName,
7311                        clientPkg.applicationInfo.uid, "update lib");
7312            }
7313        }
7314
7315        // Make sure we're not adding any bogus keyset info
7316        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7317        ksms.assertScannedPackageValid(pkg);
7318
7319        // writer
7320        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7321
7322        boolean createIdmapFailed = false;
7323        synchronized (mPackages) {
7324            // We don't expect installation to fail beyond this point
7325
7326            // Add the new setting to mSettings
7327            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7328            // Add the new setting to mPackages
7329            mPackages.put(pkg.applicationInfo.packageName, pkg);
7330            // Make sure we don't accidentally delete its data.
7331            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7332            while (iter.hasNext()) {
7333                PackageCleanItem item = iter.next();
7334                if (pkgName.equals(item.packageName)) {
7335                    iter.remove();
7336                }
7337            }
7338
7339            // Take care of first install / last update times.
7340            if (currentTime != 0) {
7341                if (pkgSetting.firstInstallTime == 0) {
7342                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7343                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7344                    pkgSetting.lastUpdateTime = currentTime;
7345                }
7346            } else if (pkgSetting.firstInstallTime == 0) {
7347                // We need *something*.  Take time time stamp of the file.
7348                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7349            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7350                if (scanFileTime != pkgSetting.timeStamp) {
7351                    // A package on the system image has changed; consider this
7352                    // to be an update.
7353                    pkgSetting.lastUpdateTime = scanFileTime;
7354                }
7355            }
7356
7357            // Add the package's KeySets to the global KeySetManagerService
7358            ksms.addScannedPackageLPw(pkg);
7359
7360            int N = pkg.providers.size();
7361            StringBuilder r = null;
7362            int i;
7363            for (i=0; i<N; i++) {
7364                PackageParser.Provider p = pkg.providers.get(i);
7365                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7366                        p.info.processName, pkg.applicationInfo.uid);
7367                mProviders.addProvider(p);
7368                p.syncable = p.info.isSyncable;
7369                if (p.info.authority != null) {
7370                    String names[] = p.info.authority.split(";");
7371                    p.info.authority = null;
7372                    for (int j = 0; j < names.length; j++) {
7373                        if (j == 1 && p.syncable) {
7374                            // We only want the first authority for a provider to possibly be
7375                            // syncable, so if we already added this provider using a different
7376                            // authority clear the syncable flag. We copy the provider before
7377                            // changing it because the mProviders object contains a reference
7378                            // to a provider that we don't want to change.
7379                            // Only do this for the second authority since the resulting provider
7380                            // object can be the same for all future authorities for this provider.
7381                            p = new PackageParser.Provider(p);
7382                            p.syncable = false;
7383                        }
7384                        if (!mProvidersByAuthority.containsKey(names[j])) {
7385                            mProvidersByAuthority.put(names[j], p);
7386                            if (p.info.authority == null) {
7387                                p.info.authority = names[j];
7388                            } else {
7389                                p.info.authority = p.info.authority + ";" + names[j];
7390                            }
7391                            if (DEBUG_PACKAGE_SCANNING) {
7392                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7393                                    Log.d(TAG, "Registered content provider: " + names[j]
7394                                            + ", className = " + p.info.name + ", isSyncable = "
7395                                            + p.info.isSyncable);
7396                            }
7397                        } else {
7398                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7399                            Slog.w(TAG, "Skipping provider name " + names[j] +
7400                                    " (in package " + pkg.applicationInfo.packageName +
7401                                    "): name already used by "
7402                                    + ((other != null && other.getComponentName() != null)
7403                                            ? other.getComponentName().getPackageName() : "?"));
7404                        }
7405                    }
7406                }
7407                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7408                    if (r == null) {
7409                        r = new StringBuilder(256);
7410                    } else {
7411                        r.append(' ');
7412                    }
7413                    r.append(p.info.name);
7414                }
7415            }
7416            if (r != null) {
7417                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7418            }
7419
7420            N = pkg.services.size();
7421            r = null;
7422            for (i=0; i<N; i++) {
7423                PackageParser.Service s = pkg.services.get(i);
7424                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7425                        s.info.processName, pkg.applicationInfo.uid);
7426                mServices.addService(s);
7427                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7428                    if (r == null) {
7429                        r = new StringBuilder(256);
7430                    } else {
7431                        r.append(' ');
7432                    }
7433                    r.append(s.info.name);
7434                }
7435            }
7436            if (r != null) {
7437                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7438            }
7439
7440            N = pkg.receivers.size();
7441            r = null;
7442            for (i=0; i<N; i++) {
7443                PackageParser.Activity a = pkg.receivers.get(i);
7444                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7445                        a.info.processName, pkg.applicationInfo.uid);
7446                mReceivers.addActivity(a, "receiver");
7447                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7448                    if (r == null) {
7449                        r = new StringBuilder(256);
7450                    } else {
7451                        r.append(' ');
7452                    }
7453                    r.append(a.info.name);
7454                }
7455            }
7456            if (r != null) {
7457                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7458            }
7459
7460            N = pkg.activities.size();
7461            r = null;
7462            for (i=0; i<N; i++) {
7463                PackageParser.Activity a = pkg.activities.get(i);
7464                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7465                        a.info.processName, pkg.applicationInfo.uid);
7466                mActivities.addActivity(a, "activity");
7467                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7468                    if (r == null) {
7469                        r = new StringBuilder(256);
7470                    } else {
7471                        r.append(' ');
7472                    }
7473                    r.append(a.info.name);
7474                }
7475            }
7476            if (r != null) {
7477                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7478            }
7479
7480            N = pkg.permissionGroups.size();
7481            r = null;
7482            for (i=0; i<N; i++) {
7483                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7484                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7485                if (cur == null) {
7486                    mPermissionGroups.put(pg.info.name, pg);
7487                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7488                        if (r == null) {
7489                            r = new StringBuilder(256);
7490                        } else {
7491                            r.append(' ');
7492                        }
7493                        r.append(pg.info.name);
7494                    }
7495                } else {
7496                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7497                            + pg.info.packageName + " ignored: original from "
7498                            + cur.info.packageName);
7499                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7500                        if (r == null) {
7501                            r = new StringBuilder(256);
7502                        } else {
7503                            r.append(' ');
7504                        }
7505                        r.append("DUP:");
7506                        r.append(pg.info.name);
7507                    }
7508                }
7509            }
7510            if (r != null) {
7511                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7512            }
7513
7514            N = pkg.permissions.size();
7515            r = null;
7516            for (i=0; i<N; i++) {
7517                PackageParser.Permission p = pkg.permissions.get(i);
7518
7519                // Assume by default that we did not install this permission into the system.
7520                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7521
7522                // Now that permission groups have a special meaning, we ignore permission
7523                // groups for legacy apps to prevent unexpected behavior. In particular,
7524                // permissions for one app being granted to someone just becuase they happen
7525                // to be in a group defined by another app (before this had no implications).
7526                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7527                    p.group = mPermissionGroups.get(p.info.group);
7528                    // Warn for a permission in an unknown group.
7529                    if (p.info.group != null && p.group == null) {
7530                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7531                                + p.info.packageName + " in an unknown group " + p.info.group);
7532                    }
7533                }
7534
7535                ArrayMap<String, BasePermission> permissionMap =
7536                        p.tree ? mSettings.mPermissionTrees
7537                                : mSettings.mPermissions;
7538                BasePermission bp = permissionMap.get(p.info.name);
7539
7540                // Allow system apps to redefine non-system permissions
7541                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7542                    final boolean currentOwnerIsSystem = (bp.perm != null
7543                            && isSystemApp(bp.perm.owner));
7544                    if (isSystemApp(p.owner)) {
7545                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7546                            // It's a built-in permission and no owner, take ownership now
7547                            bp.packageSetting = pkgSetting;
7548                            bp.perm = p;
7549                            bp.uid = pkg.applicationInfo.uid;
7550                            bp.sourcePackage = p.info.packageName;
7551                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7552                        } else if (!currentOwnerIsSystem) {
7553                            String msg = "New decl " + p.owner + " of permission  "
7554                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7555                            reportSettingsProblem(Log.WARN, msg);
7556                            bp = null;
7557                        }
7558                    }
7559                }
7560
7561                if (bp == null) {
7562                    bp = new BasePermission(p.info.name, p.info.packageName,
7563                            BasePermission.TYPE_NORMAL);
7564                    permissionMap.put(p.info.name, bp);
7565                }
7566
7567                if (bp.perm == null) {
7568                    if (bp.sourcePackage == null
7569                            || bp.sourcePackage.equals(p.info.packageName)) {
7570                        BasePermission tree = findPermissionTreeLP(p.info.name);
7571                        if (tree == null
7572                                || tree.sourcePackage.equals(p.info.packageName)) {
7573                            bp.packageSetting = pkgSetting;
7574                            bp.perm = p;
7575                            bp.uid = pkg.applicationInfo.uid;
7576                            bp.sourcePackage = p.info.packageName;
7577                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7578                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7579                                if (r == null) {
7580                                    r = new StringBuilder(256);
7581                                } else {
7582                                    r.append(' ');
7583                                }
7584                                r.append(p.info.name);
7585                            }
7586                        } else {
7587                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7588                                    + p.info.packageName + " ignored: base tree "
7589                                    + tree.name + " is from package "
7590                                    + tree.sourcePackage);
7591                        }
7592                    } else {
7593                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7594                                + p.info.packageName + " ignored: original from "
7595                                + bp.sourcePackage);
7596                    }
7597                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7598                    if (r == null) {
7599                        r = new StringBuilder(256);
7600                    } else {
7601                        r.append(' ');
7602                    }
7603                    r.append("DUP:");
7604                    r.append(p.info.name);
7605                }
7606                if (bp.perm == p) {
7607                    bp.protectionLevel = p.info.protectionLevel;
7608                }
7609            }
7610
7611            if (r != null) {
7612                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7613            }
7614
7615            N = pkg.instrumentation.size();
7616            r = null;
7617            for (i=0; i<N; i++) {
7618                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7619                a.info.packageName = pkg.applicationInfo.packageName;
7620                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7621                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7622                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7623                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7624                a.info.dataDir = pkg.applicationInfo.dataDir;
7625
7626                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7627                // need other information about the application, like the ABI and what not ?
7628                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7629                mInstrumentation.put(a.getComponentName(), a);
7630                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7631                    if (r == null) {
7632                        r = new StringBuilder(256);
7633                    } else {
7634                        r.append(' ');
7635                    }
7636                    r.append(a.info.name);
7637                }
7638            }
7639            if (r != null) {
7640                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7641            }
7642
7643            if (pkg.protectedBroadcasts != null) {
7644                N = pkg.protectedBroadcasts.size();
7645                for (i=0; i<N; i++) {
7646                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7647                }
7648            }
7649
7650            pkgSetting.setTimeStamp(scanFileTime);
7651
7652            // Create idmap files for pairs of (packages, overlay packages).
7653            // Note: "android", ie framework-res.apk, is handled by native layers.
7654            if (pkg.mOverlayTarget != null) {
7655                // This is an overlay package.
7656                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7657                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7658                        mOverlays.put(pkg.mOverlayTarget,
7659                                new ArrayMap<String, PackageParser.Package>());
7660                    }
7661                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7662                    map.put(pkg.packageName, pkg);
7663                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7664                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7665                        createIdmapFailed = true;
7666                    }
7667                }
7668            } else if (mOverlays.containsKey(pkg.packageName) &&
7669                    !pkg.packageName.equals("android")) {
7670                // This is a regular package, with one or more known overlay packages.
7671                createIdmapsForPackageLI(pkg);
7672            }
7673        }
7674
7675        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7676
7677        if (createIdmapFailed) {
7678            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7679                    "scanPackageLI failed to createIdmap");
7680        }
7681        return pkg;
7682    }
7683
7684    /**
7685     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7686     * is derived purely on the basis of the contents of {@code scanFile} and
7687     * {@code cpuAbiOverride}.
7688     *
7689     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7690     */
7691    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7692                                 String cpuAbiOverride, boolean extractLibs)
7693            throws PackageManagerException {
7694        // TODO: We can probably be smarter about this stuff. For installed apps,
7695        // we can calculate this information at install time once and for all. For
7696        // system apps, we can probably assume that this information doesn't change
7697        // after the first boot scan. As things stand, we do lots of unnecessary work.
7698
7699        // Give ourselves some initial paths; we'll come back for another
7700        // pass once we've determined ABI below.
7701        setNativeLibraryPaths(pkg);
7702
7703        // We would never need to extract libs for forward-locked and external packages,
7704        // since the container service will do it for us. We shouldn't attempt to
7705        // extract libs from system app when it was not updated.
7706        if (pkg.isForwardLocked() || isExternal(pkg) ||
7707            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7708            extractLibs = false;
7709        }
7710
7711        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7712        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7713
7714        NativeLibraryHelper.Handle handle = null;
7715        try {
7716            handle = NativeLibraryHelper.Handle.create(pkg);
7717            // TODO(multiArch): This can be null for apps that didn't go through the
7718            // usual installation process. We can calculate it again, like we
7719            // do during install time.
7720            //
7721            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7722            // unnecessary.
7723            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7724
7725            // Null out the abis so that they can be recalculated.
7726            pkg.applicationInfo.primaryCpuAbi = null;
7727            pkg.applicationInfo.secondaryCpuAbi = null;
7728            if (isMultiArch(pkg.applicationInfo)) {
7729                // Warn if we've set an abiOverride for multi-lib packages..
7730                // By definition, we need to copy both 32 and 64 bit libraries for
7731                // such packages.
7732                if (pkg.cpuAbiOverride != null
7733                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7734                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7735                }
7736
7737                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7738                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7739                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7740                    if (extractLibs) {
7741                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7742                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7743                                useIsaSpecificSubdirs);
7744                    } else {
7745                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7746                    }
7747                }
7748
7749                maybeThrowExceptionForMultiArchCopy(
7750                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7751
7752                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7753                    if (extractLibs) {
7754                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7755                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7756                                useIsaSpecificSubdirs);
7757                    } else {
7758                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7759                    }
7760                }
7761
7762                maybeThrowExceptionForMultiArchCopy(
7763                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7764
7765                if (abi64 >= 0) {
7766                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7767                }
7768
7769                if (abi32 >= 0) {
7770                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7771                    if (abi64 >= 0) {
7772                        pkg.applicationInfo.secondaryCpuAbi = abi;
7773                    } else {
7774                        pkg.applicationInfo.primaryCpuAbi = abi;
7775                    }
7776                }
7777            } else {
7778                String[] abiList = (cpuAbiOverride != null) ?
7779                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7780
7781                // Enable gross and lame hacks for apps that are built with old
7782                // SDK tools. We must scan their APKs for renderscript bitcode and
7783                // not launch them if it's present. Don't bother checking on devices
7784                // that don't have 64 bit support.
7785                boolean needsRenderScriptOverride = false;
7786                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7787                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7788                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7789                    needsRenderScriptOverride = true;
7790                }
7791
7792                final int copyRet;
7793                if (extractLibs) {
7794                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7795                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7796                } else {
7797                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7798                }
7799
7800                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7801                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7802                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7803                }
7804
7805                if (copyRet >= 0) {
7806                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7807                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7808                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7809                } else if (needsRenderScriptOverride) {
7810                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7811                }
7812            }
7813        } catch (IOException ioe) {
7814            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7815        } finally {
7816            IoUtils.closeQuietly(handle);
7817        }
7818
7819        // Now that we've calculated the ABIs and determined if it's an internal app,
7820        // we will go ahead and populate the nativeLibraryPath.
7821        setNativeLibraryPaths(pkg);
7822    }
7823
7824    /**
7825     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7826     * i.e, so that all packages can be run inside a single process if required.
7827     *
7828     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7829     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7830     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7831     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7832     * updating a package that belongs to a shared user.
7833     *
7834     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7835     * adds unnecessary complexity.
7836     */
7837    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7838            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7839        String requiredInstructionSet = null;
7840        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7841            requiredInstructionSet = VMRuntime.getInstructionSet(
7842                     scannedPackage.applicationInfo.primaryCpuAbi);
7843        }
7844
7845        PackageSetting requirer = null;
7846        for (PackageSetting ps : packagesForUser) {
7847            // If packagesForUser contains scannedPackage, we skip it. This will happen
7848            // when scannedPackage is an update of an existing package. Without this check,
7849            // we will never be able to change the ABI of any package belonging to a shared
7850            // user, even if it's compatible with other packages.
7851            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7852                if (ps.primaryCpuAbiString == null) {
7853                    continue;
7854                }
7855
7856                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7857                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7858                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7859                    // this but there's not much we can do.
7860                    String errorMessage = "Instruction set mismatch, "
7861                            + ((requirer == null) ? "[caller]" : requirer)
7862                            + " requires " + requiredInstructionSet + " whereas " + ps
7863                            + " requires " + instructionSet;
7864                    Slog.w(TAG, errorMessage);
7865                }
7866
7867                if (requiredInstructionSet == null) {
7868                    requiredInstructionSet = instructionSet;
7869                    requirer = ps;
7870                }
7871            }
7872        }
7873
7874        if (requiredInstructionSet != null) {
7875            String adjustedAbi;
7876            if (requirer != null) {
7877                // requirer != null implies that either scannedPackage was null or that scannedPackage
7878                // did not require an ABI, in which case we have to adjust scannedPackage to match
7879                // the ABI of the set (which is the same as requirer's ABI)
7880                adjustedAbi = requirer.primaryCpuAbiString;
7881                if (scannedPackage != null) {
7882                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7883                }
7884            } else {
7885                // requirer == null implies that we're updating all ABIs in the set to
7886                // match scannedPackage.
7887                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7888            }
7889
7890            for (PackageSetting ps : packagesForUser) {
7891                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7892                    if (ps.primaryCpuAbiString != null) {
7893                        continue;
7894                    }
7895
7896                    ps.primaryCpuAbiString = adjustedAbi;
7897                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7898                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7899                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7900
7901                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7902
7903                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7904                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7905
7906                        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7907                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7908                            ps.primaryCpuAbiString = null;
7909                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7910                            return;
7911                        } else {
7912                            mInstaller.rmdex(ps.codePathString,
7913                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7914                        }
7915                    }
7916                }
7917            }
7918        }
7919    }
7920
7921    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7922        synchronized (mPackages) {
7923            mResolverReplaced = true;
7924            // Set up information for custom user intent resolution activity.
7925            mResolveActivity.applicationInfo = pkg.applicationInfo;
7926            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7927            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7928            mResolveActivity.processName = pkg.applicationInfo.packageName;
7929            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7930            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7931                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7932            mResolveActivity.theme = 0;
7933            mResolveActivity.exported = true;
7934            mResolveActivity.enabled = true;
7935            mResolveInfo.activityInfo = mResolveActivity;
7936            mResolveInfo.priority = 0;
7937            mResolveInfo.preferredOrder = 0;
7938            mResolveInfo.match = 0;
7939            mResolveComponentName = mCustomResolverComponentName;
7940            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7941                    mResolveComponentName);
7942        }
7943    }
7944
7945    private static String calculateBundledApkRoot(final String codePathString) {
7946        final File codePath = new File(codePathString);
7947        final File codeRoot;
7948        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7949            codeRoot = Environment.getRootDirectory();
7950        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7951            codeRoot = Environment.getOemDirectory();
7952        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7953            codeRoot = Environment.getVendorDirectory();
7954        } else {
7955            // Unrecognized code path; take its top real segment as the apk root:
7956            // e.g. /something/app/blah.apk => /something
7957            try {
7958                File f = codePath.getCanonicalFile();
7959                File parent = f.getParentFile();    // non-null because codePath is a file
7960                File tmp;
7961                while ((tmp = parent.getParentFile()) != null) {
7962                    f = parent;
7963                    parent = tmp;
7964                }
7965                codeRoot = f;
7966                Slog.w(TAG, "Unrecognized code path "
7967                        + codePath + " - using " + codeRoot);
7968            } catch (IOException e) {
7969                // Can't canonicalize the code path -- shenanigans?
7970                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7971                return Environment.getRootDirectory().getPath();
7972            }
7973        }
7974        return codeRoot.getPath();
7975    }
7976
7977    /**
7978     * Derive and set the location of native libraries for the given package,
7979     * which varies depending on where and how the package was installed.
7980     */
7981    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7982        final ApplicationInfo info = pkg.applicationInfo;
7983        final String codePath = pkg.codePath;
7984        final File codeFile = new File(codePath);
7985        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7986        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7987
7988        info.nativeLibraryRootDir = null;
7989        info.nativeLibraryRootRequiresIsa = false;
7990        info.nativeLibraryDir = null;
7991        info.secondaryNativeLibraryDir = null;
7992
7993        if (isApkFile(codeFile)) {
7994            // Monolithic install
7995            if (bundledApp) {
7996                // If "/system/lib64/apkname" exists, assume that is the per-package
7997                // native library directory to use; otherwise use "/system/lib/apkname".
7998                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7999                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8000                        getPrimaryInstructionSet(info));
8001
8002                // This is a bundled system app so choose the path based on the ABI.
8003                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8004                // is just the default path.
8005                final String apkName = deriveCodePathName(codePath);
8006                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8007                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8008                        apkName).getAbsolutePath();
8009
8010                if (info.secondaryCpuAbi != null) {
8011                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8012                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8013                            secondaryLibDir, apkName).getAbsolutePath();
8014                }
8015            } else if (asecApp) {
8016                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8017                        .getAbsolutePath();
8018            } else {
8019                final String apkName = deriveCodePathName(codePath);
8020                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8021                        .getAbsolutePath();
8022            }
8023
8024            info.nativeLibraryRootRequiresIsa = false;
8025            info.nativeLibraryDir = info.nativeLibraryRootDir;
8026        } else {
8027            // Cluster install
8028            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8029            info.nativeLibraryRootRequiresIsa = true;
8030
8031            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8032                    getPrimaryInstructionSet(info)).getAbsolutePath();
8033
8034            if (info.secondaryCpuAbi != null) {
8035                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8036                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8037            }
8038        }
8039    }
8040
8041    /**
8042     * Calculate the abis and roots for a bundled app. These can uniquely
8043     * be determined from the contents of the system partition, i.e whether
8044     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8045     * of this information, and instead assume that the system was built
8046     * sensibly.
8047     */
8048    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8049                                           PackageSetting pkgSetting) {
8050        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8051
8052        // If "/system/lib64/apkname" exists, assume that is the per-package
8053        // native library directory to use; otherwise use "/system/lib/apkname".
8054        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8055        setBundledAppAbi(pkg, apkRoot, apkName);
8056        // pkgSetting might be null during rescan following uninstall of updates
8057        // to a bundled app, so accommodate that possibility.  The settings in
8058        // that case will be established later from the parsed package.
8059        //
8060        // If the settings aren't null, sync them up with what we've just derived.
8061        // note that apkRoot isn't stored in the package settings.
8062        if (pkgSetting != null) {
8063            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8064            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8065        }
8066    }
8067
8068    /**
8069     * Deduces the ABI of a bundled app and sets the relevant fields on the
8070     * parsed pkg object.
8071     *
8072     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8073     *        under which system libraries are installed.
8074     * @param apkName the name of the installed package.
8075     */
8076    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8077        final File codeFile = new File(pkg.codePath);
8078
8079        final boolean has64BitLibs;
8080        final boolean has32BitLibs;
8081        if (isApkFile(codeFile)) {
8082            // Monolithic install
8083            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8084            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8085        } else {
8086            // Cluster install
8087            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8088            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8089                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8090                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8091                has64BitLibs = (new File(rootDir, isa)).exists();
8092            } else {
8093                has64BitLibs = false;
8094            }
8095            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8096                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8097                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8098                has32BitLibs = (new File(rootDir, isa)).exists();
8099            } else {
8100                has32BitLibs = false;
8101            }
8102        }
8103
8104        if (has64BitLibs && !has32BitLibs) {
8105            // The package has 64 bit libs, but not 32 bit libs. Its primary
8106            // ABI should be 64 bit. We can safely assume here that the bundled
8107            // native libraries correspond to the most preferred ABI in the list.
8108
8109            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8110            pkg.applicationInfo.secondaryCpuAbi = null;
8111        } else if (has32BitLibs && !has64BitLibs) {
8112            // The package has 32 bit libs but not 64 bit libs. Its primary
8113            // ABI should be 32 bit.
8114
8115            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8116            pkg.applicationInfo.secondaryCpuAbi = null;
8117        } else if (has32BitLibs && has64BitLibs) {
8118            // The application has both 64 and 32 bit bundled libraries. We check
8119            // here that the app declares multiArch support, and warn if it doesn't.
8120            //
8121            // We will be lenient here and record both ABIs. The primary will be the
8122            // ABI that's higher on the list, i.e, a device that's configured to prefer
8123            // 64 bit apps will see a 64 bit primary ABI,
8124
8125            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8126                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8127            }
8128
8129            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8130                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8131                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8132            } else {
8133                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8134                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8135            }
8136        } else {
8137            pkg.applicationInfo.primaryCpuAbi = null;
8138            pkg.applicationInfo.secondaryCpuAbi = null;
8139        }
8140    }
8141
8142    private void killApplication(String pkgName, int appId, String reason) {
8143        // Request the ActivityManager to kill the process(only for existing packages)
8144        // so that we do not end up in a confused state while the user is still using the older
8145        // version of the application while the new one gets installed.
8146        IActivityManager am = ActivityManagerNative.getDefault();
8147        if (am != null) {
8148            try {
8149                am.killApplicationWithAppId(pkgName, appId, reason);
8150            } catch (RemoteException e) {
8151            }
8152        }
8153    }
8154
8155    void removePackageLI(PackageSetting ps, boolean chatty) {
8156        if (DEBUG_INSTALL) {
8157            if (chatty)
8158                Log.d(TAG, "Removing package " + ps.name);
8159        }
8160
8161        // writer
8162        synchronized (mPackages) {
8163            mPackages.remove(ps.name);
8164            final PackageParser.Package pkg = ps.pkg;
8165            if (pkg != null) {
8166                cleanPackageDataStructuresLILPw(pkg, chatty);
8167            }
8168        }
8169    }
8170
8171    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8172        if (DEBUG_INSTALL) {
8173            if (chatty)
8174                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8175        }
8176
8177        // writer
8178        synchronized (mPackages) {
8179            mPackages.remove(pkg.applicationInfo.packageName);
8180            cleanPackageDataStructuresLILPw(pkg, chatty);
8181        }
8182    }
8183
8184    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8185        int N = pkg.providers.size();
8186        StringBuilder r = null;
8187        int i;
8188        for (i=0; i<N; i++) {
8189            PackageParser.Provider p = pkg.providers.get(i);
8190            mProviders.removeProvider(p);
8191            if (p.info.authority == null) {
8192
8193                /* There was another ContentProvider with this authority when
8194                 * this app was installed so this authority is null,
8195                 * Ignore it as we don't have to unregister the provider.
8196                 */
8197                continue;
8198            }
8199            String names[] = p.info.authority.split(";");
8200            for (int j = 0; j < names.length; j++) {
8201                if (mProvidersByAuthority.get(names[j]) == p) {
8202                    mProvidersByAuthority.remove(names[j]);
8203                    if (DEBUG_REMOVE) {
8204                        if (chatty)
8205                            Log.d(TAG, "Unregistered content provider: " + names[j]
8206                                    + ", className = " + p.info.name + ", isSyncable = "
8207                                    + p.info.isSyncable);
8208                    }
8209                }
8210            }
8211            if (DEBUG_REMOVE && chatty) {
8212                if (r == null) {
8213                    r = new StringBuilder(256);
8214                } else {
8215                    r.append(' ');
8216                }
8217                r.append(p.info.name);
8218            }
8219        }
8220        if (r != null) {
8221            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8222        }
8223
8224        N = pkg.services.size();
8225        r = null;
8226        for (i=0; i<N; i++) {
8227            PackageParser.Service s = pkg.services.get(i);
8228            mServices.removeService(s);
8229            if (chatty) {
8230                if (r == null) {
8231                    r = new StringBuilder(256);
8232                } else {
8233                    r.append(' ');
8234                }
8235                r.append(s.info.name);
8236            }
8237        }
8238        if (r != null) {
8239            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8240        }
8241
8242        N = pkg.receivers.size();
8243        r = null;
8244        for (i=0; i<N; i++) {
8245            PackageParser.Activity a = pkg.receivers.get(i);
8246            mReceivers.removeActivity(a, "receiver");
8247            if (DEBUG_REMOVE && chatty) {
8248                if (r == null) {
8249                    r = new StringBuilder(256);
8250                } else {
8251                    r.append(' ');
8252                }
8253                r.append(a.info.name);
8254            }
8255        }
8256        if (r != null) {
8257            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8258        }
8259
8260        N = pkg.activities.size();
8261        r = null;
8262        for (i=0; i<N; i++) {
8263            PackageParser.Activity a = pkg.activities.get(i);
8264            mActivities.removeActivity(a, "activity");
8265            if (DEBUG_REMOVE && chatty) {
8266                if (r == null) {
8267                    r = new StringBuilder(256);
8268                } else {
8269                    r.append(' ');
8270                }
8271                r.append(a.info.name);
8272            }
8273        }
8274        if (r != null) {
8275            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8276        }
8277
8278        N = pkg.permissions.size();
8279        r = null;
8280        for (i=0; i<N; i++) {
8281            PackageParser.Permission p = pkg.permissions.get(i);
8282            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8283            if (bp == null) {
8284                bp = mSettings.mPermissionTrees.get(p.info.name);
8285            }
8286            if (bp != null && bp.perm == p) {
8287                bp.perm = null;
8288                if (DEBUG_REMOVE && chatty) {
8289                    if (r == null) {
8290                        r = new StringBuilder(256);
8291                    } else {
8292                        r.append(' ');
8293                    }
8294                    r.append(p.info.name);
8295                }
8296            }
8297            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8298                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8299                if (appOpPerms != null) {
8300                    appOpPerms.remove(pkg.packageName);
8301                }
8302            }
8303        }
8304        if (r != null) {
8305            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8306        }
8307
8308        N = pkg.requestedPermissions.size();
8309        r = null;
8310        for (i=0; i<N; i++) {
8311            String perm = pkg.requestedPermissions.get(i);
8312            BasePermission bp = mSettings.mPermissions.get(perm);
8313            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8314                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8315                if (appOpPerms != null) {
8316                    appOpPerms.remove(pkg.packageName);
8317                    if (appOpPerms.isEmpty()) {
8318                        mAppOpPermissionPackages.remove(perm);
8319                    }
8320                }
8321            }
8322        }
8323        if (r != null) {
8324            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8325        }
8326
8327        N = pkg.instrumentation.size();
8328        r = null;
8329        for (i=0; i<N; i++) {
8330            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8331            mInstrumentation.remove(a.getComponentName());
8332            if (DEBUG_REMOVE && chatty) {
8333                if (r == null) {
8334                    r = new StringBuilder(256);
8335                } else {
8336                    r.append(' ');
8337                }
8338                r.append(a.info.name);
8339            }
8340        }
8341        if (r != null) {
8342            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8343        }
8344
8345        r = null;
8346        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8347            // Only system apps can hold shared libraries.
8348            if (pkg.libraryNames != null) {
8349                for (i=0; i<pkg.libraryNames.size(); i++) {
8350                    String name = pkg.libraryNames.get(i);
8351                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8352                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8353                        mSharedLibraries.remove(name);
8354                        if (DEBUG_REMOVE && chatty) {
8355                            if (r == null) {
8356                                r = new StringBuilder(256);
8357                            } else {
8358                                r.append(' ');
8359                            }
8360                            r.append(name);
8361                        }
8362                    }
8363                }
8364            }
8365        }
8366        if (r != null) {
8367            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8368        }
8369    }
8370
8371    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8372        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8373            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8374                return true;
8375            }
8376        }
8377        return false;
8378    }
8379
8380    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8381    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8382    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8383
8384    private void updatePermissionsLPw(String changingPkg,
8385            PackageParser.Package pkgInfo, int flags) {
8386        // Make sure there are no dangling permission trees.
8387        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8388        while (it.hasNext()) {
8389            final BasePermission bp = it.next();
8390            if (bp.packageSetting == null) {
8391                // We may not yet have parsed the package, so just see if
8392                // we still know about its settings.
8393                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8394            }
8395            if (bp.packageSetting == null) {
8396                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8397                        + " from package " + bp.sourcePackage);
8398                it.remove();
8399            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8400                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8401                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8402                            + " from package " + bp.sourcePackage);
8403                    flags |= UPDATE_PERMISSIONS_ALL;
8404                    it.remove();
8405                }
8406            }
8407        }
8408
8409        // Make sure all dynamic permissions have been assigned to a package,
8410        // and make sure there are no dangling permissions.
8411        it = mSettings.mPermissions.values().iterator();
8412        while (it.hasNext()) {
8413            final BasePermission bp = it.next();
8414            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8415                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8416                        + bp.name + " pkg=" + bp.sourcePackage
8417                        + " info=" + bp.pendingInfo);
8418                if (bp.packageSetting == null && bp.pendingInfo != null) {
8419                    final BasePermission tree = findPermissionTreeLP(bp.name);
8420                    if (tree != null && tree.perm != null) {
8421                        bp.packageSetting = tree.packageSetting;
8422                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8423                                new PermissionInfo(bp.pendingInfo));
8424                        bp.perm.info.packageName = tree.perm.info.packageName;
8425                        bp.perm.info.name = bp.name;
8426                        bp.uid = tree.uid;
8427                    }
8428                }
8429            }
8430            if (bp.packageSetting == null) {
8431                // We may not yet have parsed the package, so just see if
8432                // we still know about its settings.
8433                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8434            }
8435            if (bp.packageSetting == null) {
8436                Slog.w(TAG, "Removing dangling permission: " + bp.name
8437                        + " from package " + bp.sourcePackage);
8438                it.remove();
8439            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8440                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8441                    Slog.i(TAG, "Removing old permission: " + bp.name
8442                            + " from package " + bp.sourcePackage);
8443                    flags |= UPDATE_PERMISSIONS_ALL;
8444                    it.remove();
8445                }
8446            }
8447        }
8448
8449        // Now update the permissions for all packages, in particular
8450        // replace the granted permissions of the system packages.
8451        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8452            for (PackageParser.Package pkg : mPackages.values()) {
8453                if (pkg != pkgInfo) {
8454                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8455                            changingPkg);
8456                }
8457            }
8458        }
8459
8460        if (pkgInfo != null) {
8461            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8462        }
8463    }
8464
8465    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8466            String packageOfInterest) {
8467        // IMPORTANT: There are two types of permissions: install and runtime.
8468        // Install time permissions are granted when the app is installed to
8469        // all device users and users added in the future. Runtime permissions
8470        // are granted at runtime explicitly to specific users. Normal and signature
8471        // protected permissions are install time permissions. Dangerous permissions
8472        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8473        // otherwise they are runtime permissions. This function does not manage
8474        // runtime permissions except for the case an app targeting Lollipop MR1
8475        // being upgraded to target a newer SDK, in which case dangerous permissions
8476        // are transformed from install time to runtime ones.
8477
8478        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8479        if (ps == null) {
8480            return;
8481        }
8482
8483        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8484
8485        PermissionsState permissionsState = ps.getPermissionsState();
8486        PermissionsState origPermissions = permissionsState;
8487
8488        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8489
8490        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8491
8492        boolean changedInstallPermission = false;
8493
8494        if (replace) {
8495            ps.installPermissionsFixed = false;
8496            if (!ps.isSharedUser()) {
8497                origPermissions = new PermissionsState(permissionsState);
8498                permissionsState.reset();
8499            }
8500        }
8501
8502        permissionsState.setGlobalGids(mGlobalGids);
8503
8504        final int N = pkg.requestedPermissions.size();
8505        for (int i=0; i<N; i++) {
8506            final String name = pkg.requestedPermissions.get(i);
8507            final BasePermission bp = mSettings.mPermissions.get(name);
8508
8509            if (DEBUG_INSTALL) {
8510                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8511            }
8512
8513            if (bp == null || bp.packageSetting == null) {
8514                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8515                    Slog.w(TAG, "Unknown permission " + name
8516                            + " in package " + pkg.packageName);
8517                }
8518                continue;
8519            }
8520
8521            final String perm = bp.name;
8522            boolean allowedSig = false;
8523            int grant = GRANT_DENIED;
8524
8525            // Keep track of app op permissions.
8526            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8527                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8528                if (pkgs == null) {
8529                    pkgs = new ArraySet<>();
8530                    mAppOpPermissionPackages.put(bp.name, pkgs);
8531                }
8532                pkgs.add(pkg.packageName);
8533            }
8534
8535            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8536            switch (level) {
8537                case PermissionInfo.PROTECTION_NORMAL: {
8538                    // For all apps normal permissions are install time ones.
8539                    grant = GRANT_INSTALL;
8540                } break;
8541
8542                case PermissionInfo.PROTECTION_DANGEROUS: {
8543                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8544                        // For legacy apps dangerous permissions are install time ones.
8545                        grant = GRANT_INSTALL_LEGACY;
8546                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8547                        // For legacy apps that became modern, install becomes runtime.
8548                        grant = GRANT_UPGRADE;
8549                    } else if (mPromoteSystemApps
8550                            && isSystemApp(ps)
8551                            && mExistingSystemPackages.contains(ps.name)) {
8552                        // For legacy system apps, install becomes runtime.
8553                        // We cannot check hasInstallPermission() for system apps since those
8554                        // permissions were granted implicitly and not persisted pre-M.
8555                        grant = GRANT_UPGRADE;
8556                    } else {
8557                        // For modern apps keep runtime permissions unchanged.
8558                        grant = GRANT_RUNTIME;
8559                    }
8560                } break;
8561
8562                case PermissionInfo.PROTECTION_SIGNATURE: {
8563                    // For all apps signature permissions are install time ones.
8564                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8565                    if (allowedSig) {
8566                        grant = GRANT_INSTALL;
8567                    }
8568                } break;
8569            }
8570
8571            if (DEBUG_INSTALL) {
8572                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8573            }
8574
8575            if (grant != GRANT_DENIED) {
8576                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8577                    // If this is an existing, non-system package, then
8578                    // we can't add any new permissions to it.
8579                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8580                        // Except...  if this is a permission that was added
8581                        // to the platform (note: need to only do this when
8582                        // updating the platform).
8583                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8584                            grant = GRANT_DENIED;
8585                        }
8586                    }
8587                }
8588
8589                switch (grant) {
8590                    case GRANT_INSTALL: {
8591                        // Revoke this as runtime permission to handle the case of
8592                        // a runtime permission being downgraded to an install one.
8593                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8594                            if (origPermissions.getRuntimePermissionState(
8595                                    bp.name, userId) != null) {
8596                                // Revoke the runtime permission and clear the flags.
8597                                origPermissions.revokeRuntimePermission(bp, userId);
8598                                origPermissions.updatePermissionFlags(bp, userId,
8599                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8600                                // If we revoked a permission permission, we have to write.
8601                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8602                                        changedRuntimePermissionUserIds, userId);
8603                            }
8604                        }
8605                        // Grant an install permission.
8606                        if (permissionsState.grantInstallPermission(bp) !=
8607                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8608                            changedInstallPermission = true;
8609                        }
8610                    } break;
8611
8612                    case GRANT_INSTALL_LEGACY: {
8613                        // Grant an install permission.
8614                        if (permissionsState.grantInstallPermission(bp) !=
8615                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8616                            changedInstallPermission = true;
8617                        }
8618                    } break;
8619
8620                    case GRANT_RUNTIME: {
8621                        // Grant previously granted runtime permissions.
8622                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8623                            PermissionState permissionState = origPermissions
8624                                    .getRuntimePermissionState(bp.name, userId);
8625                            final int flags = permissionState != null
8626                                    ? permissionState.getFlags() : 0;
8627                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8628                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8629                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8630                                    // If we cannot put the permission as it was, we have to write.
8631                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8632                                            changedRuntimePermissionUserIds, userId);
8633                                }
8634                            }
8635                            // Propagate the permission flags.
8636                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8637                        }
8638                    } break;
8639
8640                    case GRANT_UPGRADE: {
8641                        // Grant runtime permissions for a previously held install permission.
8642                        PermissionState permissionState = origPermissions
8643                                .getInstallPermissionState(bp.name);
8644                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8645
8646                        if (origPermissions.revokeInstallPermission(bp)
8647                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8648                            // We will be transferring the permission flags, so clear them.
8649                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8650                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8651                            changedInstallPermission = true;
8652                        }
8653
8654                        // If the permission is not to be promoted to runtime we ignore it and
8655                        // also its other flags as they are not applicable to install permissions.
8656                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8657                            for (int userId : currentUserIds) {
8658                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8659                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8660                                    // Transfer the permission flags.
8661                                    permissionsState.updatePermissionFlags(bp, userId,
8662                                            flags, flags);
8663                                    // If we granted the permission, we have to write.
8664                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8665                                            changedRuntimePermissionUserIds, userId);
8666                                }
8667                            }
8668                        }
8669                    } break;
8670
8671                    default: {
8672                        if (packageOfInterest == null
8673                                || packageOfInterest.equals(pkg.packageName)) {
8674                            Slog.w(TAG, "Not granting permission " + perm
8675                                    + " to package " + pkg.packageName
8676                                    + " because it was previously installed without");
8677                        }
8678                    } break;
8679                }
8680            } else {
8681                if (permissionsState.revokeInstallPermission(bp) !=
8682                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8683                    // Also drop the permission flags.
8684                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8685                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8686                    changedInstallPermission = true;
8687                    Slog.i(TAG, "Un-granting permission " + perm
8688                            + " from package " + pkg.packageName
8689                            + " (protectionLevel=" + bp.protectionLevel
8690                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8691                            + ")");
8692                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8693                    // Don't print warning for app op permissions, since it is fine for them
8694                    // not to be granted, there is a UI for the user to decide.
8695                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8696                        Slog.w(TAG, "Not granting permission " + perm
8697                                + " to package " + pkg.packageName
8698                                + " (protectionLevel=" + bp.protectionLevel
8699                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8700                                + ")");
8701                    }
8702                }
8703            }
8704        }
8705
8706        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8707                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8708            // This is the first that we have heard about this package, so the
8709            // permissions we have now selected are fixed until explicitly
8710            // changed.
8711            ps.installPermissionsFixed = true;
8712        }
8713
8714        // Persist the runtime permissions state for users with changes.
8715        for (int userId : changedRuntimePermissionUserIds) {
8716            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8717        }
8718
8719        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8720    }
8721
8722    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8723        boolean allowed = false;
8724        final int NP = PackageParser.NEW_PERMISSIONS.length;
8725        for (int ip=0; ip<NP; ip++) {
8726            final PackageParser.NewPermissionInfo npi
8727                    = PackageParser.NEW_PERMISSIONS[ip];
8728            if (npi.name.equals(perm)
8729                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8730                allowed = true;
8731                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8732                        + pkg.packageName);
8733                break;
8734            }
8735        }
8736        return allowed;
8737    }
8738
8739    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8740            BasePermission bp, PermissionsState origPermissions) {
8741        boolean allowed;
8742        allowed = (compareSignatures(
8743                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8744                        == PackageManager.SIGNATURE_MATCH)
8745                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8746                        == PackageManager.SIGNATURE_MATCH);
8747        if (!allowed && (bp.protectionLevel
8748                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8749            if (isSystemApp(pkg)) {
8750                // For updated system applications, a system permission
8751                // is granted only if it had been defined by the original application.
8752                if (pkg.isUpdatedSystemApp()) {
8753                    final PackageSetting sysPs = mSettings
8754                            .getDisabledSystemPkgLPr(pkg.packageName);
8755                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8756                        // If the original was granted this permission, we take
8757                        // that grant decision as read and propagate it to the
8758                        // update.
8759                        if (sysPs.isPrivileged()) {
8760                            allowed = true;
8761                        }
8762                    } else {
8763                        // The system apk may have been updated with an older
8764                        // version of the one on the data partition, but which
8765                        // granted a new system permission that it didn't have
8766                        // before.  In this case we do want to allow the app to
8767                        // now get the new permission if the ancestral apk is
8768                        // privileged to get it.
8769                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8770                            for (int j=0;
8771                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8772                                if (perm.equals(
8773                                        sysPs.pkg.requestedPermissions.get(j))) {
8774                                    allowed = true;
8775                                    break;
8776                                }
8777                            }
8778                        }
8779                    }
8780                } else {
8781                    allowed = isPrivilegedApp(pkg);
8782                }
8783            }
8784        }
8785        if (!allowed) {
8786            if (!allowed && (bp.protectionLevel
8787                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8788                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8789                // If this was a previously normal/dangerous permission that got moved
8790                // to a system permission as part of the runtime permission redesign, then
8791                // we still want to blindly grant it to old apps.
8792                allowed = true;
8793            }
8794            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8795                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8796                // If this permission is to be granted to the system installer and
8797                // this app is an installer, then it gets the permission.
8798                allowed = true;
8799            }
8800            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8801                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8802                // If this permission is to be granted to the system verifier and
8803                // this app is a verifier, then it gets the permission.
8804                allowed = true;
8805            }
8806            if (!allowed && (bp.protectionLevel
8807                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8808                    && isSystemApp(pkg)) {
8809                // Any pre-installed system app is allowed to get this permission.
8810                allowed = true;
8811            }
8812            if (!allowed && (bp.protectionLevel
8813                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8814                // For development permissions, a development permission
8815                // is granted only if it was already granted.
8816                allowed = origPermissions.hasInstallPermission(perm);
8817            }
8818        }
8819        return allowed;
8820    }
8821
8822    final class ActivityIntentResolver
8823            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8824        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8825                boolean defaultOnly, int userId) {
8826            if (!sUserManager.exists(userId)) return null;
8827            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8828            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8829        }
8830
8831        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8832                int userId) {
8833            if (!sUserManager.exists(userId)) return null;
8834            mFlags = flags;
8835            return super.queryIntent(intent, resolvedType,
8836                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8837        }
8838
8839        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8840                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8841            if (!sUserManager.exists(userId)) return null;
8842            if (packageActivities == null) {
8843                return null;
8844            }
8845            mFlags = flags;
8846            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8847            final int N = packageActivities.size();
8848            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8849                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8850
8851            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8852            for (int i = 0; i < N; ++i) {
8853                intentFilters = packageActivities.get(i).intents;
8854                if (intentFilters != null && intentFilters.size() > 0) {
8855                    PackageParser.ActivityIntentInfo[] array =
8856                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8857                    intentFilters.toArray(array);
8858                    listCut.add(array);
8859                }
8860            }
8861            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8862        }
8863
8864        public final void addActivity(PackageParser.Activity a, String type) {
8865            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8866            mActivities.put(a.getComponentName(), a);
8867            if (DEBUG_SHOW_INFO)
8868                Log.v(
8869                TAG, "  " + type + " " +
8870                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8871            if (DEBUG_SHOW_INFO)
8872                Log.v(TAG, "    Class=" + a.info.name);
8873            final int NI = a.intents.size();
8874            for (int j=0; j<NI; j++) {
8875                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8876                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8877                    intent.setPriority(0);
8878                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8879                            + a.className + " with priority > 0, forcing to 0");
8880                }
8881                if (DEBUG_SHOW_INFO) {
8882                    Log.v(TAG, "    IntentFilter:");
8883                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8884                }
8885                if (!intent.debugCheck()) {
8886                    Log.w(TAG, "==> For Activity " + a.info.name);
8887                }
8888                addFilter(intent);
8889            }
8890        }
8891
8892        public final void removeActivity(PackageParser.Activity a, String type) {
8893            mActivities.remove(a.getComponentName());
8894            if (DEBUG_SHOW_INFO) {
8895                Log.v(TAG, "  " + type + " "
8896                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8897                                : a.info.name) + ":");
8898                Log.v(TAG, "    Class=" + a.info.name);
8899            }
8900            final int NI = a.intents.size();
8901            for (int j=0; j<NI; j++) {
8902                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8903                if (DEBUG_SHOW_INFO) {
8904                    Log.v(TAG, "    IntentFilter:");
8905                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8906                }
8907                removeFilter(intent);
8908            }
8909        }
8910
8911        @Override
8912        protected boolean allowFilterResult(
8913                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8914            ActivityInfo filterAi = filter.activity.info;
8915            for (int i=dest.size()-1; i>=0; i--) {
8916                ActivityInfo destAi = dest.get(i).activityInfo;
8917                if (destAi.name == filterAi.name
8918                        && destAi.packageName == filterAi.packageName) {
8919                    return false;
8920                }
8921            }
8922            return true;
8923        }
8924
8925        @Override
8926        protected ActivityIntentInfo[] newArray(int size) {
8927            return new ActivityIntentInfo[size];
8928        }
8929
8930        @Override
8931        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8932            if (!sUserManager.exists(userId)) return true;
8933            PackageParser.Package p = filter.activity.owner;
8934            if (p != null) {
8935                PackageSetting ps = (PackageSetting)p.mExtras;
8936                if (ps != null) {
8937                    // System apps are never considered stopped for purposes of
8938                    // filtering, because there may be no way for the user to
8939                    // actually re-launch them.
8940                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8941                            && ps.getStopped(userId);
8942                }
8943            }
8944            return false;
8945        }
8946
8947        @Override
8948        protected boolean isPackageForFilter(String packageName,
8949                PackageParser.ActivityIntentInfo info) {
8950            return packageName.equals(info.activity.owner.packageName);
8951        }
8952
8953        @Override
8954        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8955                int match, int userId) {
8956            if (!sUserManager.exists(userId)) return null;
8957            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8958                return null;
8959            }
8960            final PackageParser.Activity activity = info.activity;
8961            if (mSafeMode && (activity.info.applicationInfo.flags
8962                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8963                return null;
8964            }
8965            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8966            if (ps == null) {
8967                return null;
8968            }
8969            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8970                    ps.readUserState(userId), userId);
8971            if (ai == null) {
8972                return null;
8973            }
8974            final ResolveInfo res = new ResolveInfo();
8975            res.activityInfo = ai;
8976            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8977                res.filter = info;
8978            }
8979            if (info != null) {
8980                res.handleAllWebDataURI = info.handleAllWebDataURI();
8981            }
8982            res.priority = info.getPriority();
8983            res.preferredOrder = activity.owner.mPreferredOrder;
8984            //System.out.println("Result: " + res.activityInfo.className +
8985            //                   " = " + res.priority);
8986            res.match = match;
8987            res.isDefault = info.hasDefault;
8988            res.labelRes = info.labelRes;
8989            res.nonLocalizedLabel = info.nonLocalizedLabel;
8990            if (userNeedsBadging(userId)) {
8991                res.noResourceId = true;
8992            } else {
8993                res.icon = info.icon;
8994            }
8995            res.iconResourceId = info.icon;
8996            res.system = res.activityInfo.applicationInfo.isSystemApp();
8997            return res;
8998        }
8999
9000        @Override
9001        protected void sortResults(List<ResolveInfo> results) {
9002            Collections.sort(results, mResolvePrioritySorter);
9003        }
9004
9005        @Override
9006        protected void dumpFilter(PrintWriter out, String prefix,
9007                PackageParser.ActivityIntentInfo filter) {
9008            out.print(prefix); out.print(
9009                    Integer.toHexString(System.identityHashCode(filter.activity)));
9010                    out.print(' ');
9011                    filter.activity.printComponentShortName(out);
9012                    out.print(" filter ");
9013                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9014        }
9015
9016        @Override
9017        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9018            return filter.activity;
9019        }
9020
9021        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9022            PackageParser.Activity activity = (PackageParser.Activity)label;
9023            out.print(prefix); out.print(
9024                    Integer.toHexString(System.identityHashCode(activity)));
9025                    out.print(' ');
9026                    activity.printComponentShortName(out);
9027            if (count > 1) {
9028                out.print(" ("); out.print(count); out.print(" filters)");
9029            }
9030            out.println();
9031        }
9032
9033//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9034//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9035//            final List<ResolveInfo> retList = Lists.newArrayList();
9036//            while (i.hasNext()) {
9037//                final ResolveInfo resolveInfo = i.next();
9038//                if (isEnabledLP(resolveInfo.activityInfo)) {
9039//                    retList.add(resolveInfo);
9040//                }
9041//            }
9042//            return retList;
9043//        }
9044
9045        // Keys are String (activity class name), values are Activity.
9046        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9047                = new ArrayMap<ComponentName, PackageParser.Activity>();
9048        private int mFlags;
9049    }
9050
9051    private final class ServiceIntentResolver
9052            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9053        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9054                boolean defaultOnly, int userId) {
9055            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9056            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9057        }
9058
9059        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9060                int userId) {
9061            if (!sUserManager.exists(userId)) return null;
9062            mFlags = flags;
9063            return super.queryIntent(intent, resolvedType,
9064                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9065        }
9066
9067        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9068                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9069            if (!sUserManager.exists(userId)) return null;
9070            if (packageServices == null) {
9071                return null;
9072            }
9073            mFlags = flags;
9074            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9075            final int N = packageServices.size();
9076            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9077                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9078
9079            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9080            for (int i = 0; i < N; ++i) {
9081                intentFilters = packageServices.get(i).intents;
9082                if (intentFilters != null && intentFilters.size() > 0) {
9083                    PackageParser.ServiceIntentInfo[] array =
9084                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9085                    intentFilters.toArray(array);
9086                    listCut.add(array);
9087                }
9088            }
9089            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9090        }
9091
9092        public final void addService(PackageParser.Service s) {
9093            mServices.put(s.getComponentName(), s);
9094            if (DEBUG_SHOW_INFO) {
9095                Log.v(TAG, "  "
9096                        + (s.info.nonLocalizedLabel != null
9097                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9098                Log.v(TAG, "    Class=" + s.info.name);
9099            }
9100            final int NI = s.intents.size();
9101            int j;
9102            for (j=0; j<NI; j++) {
9103                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9104                if (DEBUG_SHOW_INFO) {
9105                    Log.v(TAG, "    IntentFilter:");
9106                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9107                }
9108                if (!intent.debugCheck()) {
9109                    Log.w(TAG, "==> For Service " + s.info.name);
9110                }
9111                addFilter(intent);
9112            }
9113        }
9114
9115        public final void removeService(PackageParser.Service s) {
9116            mServices.remove(s.getComponentName());
9117            if (DEBUG_SHOW_INFO) {
9118                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9119                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9120                Log.v(TAG, "    Class=" + s.info.name);
9121            }
9122            final int NI = s.intents.size();
9123            int j;
9124            for (j=0; j<NI; j++) {
9125                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9126                if (DEBUG_SHOW_INFO) {
9127                    Log.v(TAG, "    IntentFilter:");
9128                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9129                }
9130                removeFilter(intent);
9131            }
9132        }
9133
9134        @Override
9135        protected boolean allowFilterResult(
9136                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9137            ServiceInfo filterSi = filter.service.info;
9138            for (int i=dest.size()-1; i>=0; i--) {
9139                ServiceInfo destAi = dest.get(i).serviceInfo;
9140                if (destAi.name == filterSi.name
9141                        && destAi.packageName == filterSi.packageName) {
9142                    return false;
9143                }
9144            }
9145            return true;
9146        }
9147
9148        @Override
9149        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9150            return new PackageParser.ServiceIntentInfo[size];
9151        }
9152
9153        @Override
9154        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9155            if (!sUserManager.exists(userId)) return true;
9156            PackageParser.Package p = filter.service.owner;
9157            if (p != null) {
9158                PackageSetting ps = (PackageSetting)p.mExtras;
9159                if (ps != null) {
9160                    // System apps are never considered stopped for purposes of
9161                    // filtering, because there may be no way for the user to
9162                    // actually re-launch them.
9163                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9164                            && ps.getStopped(userId);
9165                }
9166            }
9167            return false;
9168        }
9169
9170        @Override
9171        protected boolean isPackageForFilter(String packageName,
9172                PackageParser.ServiceIntentInfo info) {
9173            return packageName.equals(info.service.owner.packageName);
9174        }
9175
9176        @Override
9177        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9178                int match, int userId) {
9179            if (!sUserManager.exists(userId)) return null;
9180            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9181            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
9182                return null;
9183            }
9184            final PackageParser.Service service = info.service;
9185            if (mSafeMode && (service.info.applicationInfo.flags
9186                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9187                return null;
9188            }
9189            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9190            if (ps == null) {
9191                return null;
9192            }
9193            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9194                    ps.readUserState(userId), userId);
9195            if (si == null) {
9196                return null;
9197            }
9198            final ResolveInfo res = new ResolveInfo();
9199            res.serviceInfo = si;
9200            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9201                res.filter = filter;
9202            }
9203            res.priority = info.getPriority();
9204            res.preferredOrder = service.owner.mPreferredOrder;
9205            res.match = match;
9206            res.isDefault = info.hasDefault;
9207            res.labelRes = info.labelRes;
9208            res.nonLocalizedLabel = info.nonLocalizedLabel;
9209            res.icon = info.icon;
9210            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9211            return res;
9212        }
9213
9214        @Override
9215        protected void sortResults(List<ResolveInfo> results) {
9216            Collections.sort(results, mResolvePrioritySorter);
9217        }
9218
9219        @Override
9220        protected void dumpFilter(PrintWriter out, String prefix,
9221                PackageParser.ServiceIntentInfo filter) {
9222            out.print(prefix); out.print(
9223                    Integer.toHexString(System.identityHashCode(filter.service)));
9224                    out.print(' ');
9225                    filter.service.printComponentShortName(out);
9226                    out.print(" filter ");
9227                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9228        }
9229
9230        @Override
9231        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9232            return filter.service;
9233        }
9234
9235        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9236            PackageParser.Service service = (PackageParser.Service)label;
9237            out.print(prefix); out.print(
9238                    Integer.toHexString(System.identityHashCode(service)));
9239                    out.print(' ');
9240                    service.printComponentShortName(out);
9241            if (count > 1) {
9242                out.print(" ("); out.print(count); out.print(" filters)");
9243            }
9244            out.println();
9245        }
9246
9247//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9248//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9249//            final List<ResolveInfo> retList = Lists.newArrayList();
9250//            while (i.hasNext()) {
9251//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9252//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9253//                    retList.add(resolveInfo);
9254//                }
9255//            }
9256//            return retList;
9257//        }
9258
9259        // Keys are String (activity class name), values are Activity.
9260        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9261                = new ArrayMap<ComponentName, PackageParser.Service>();
9262        private int mFlags;
9263    };
9264
9265    private final class ProviderIntentResolver
9266            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9267        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9268                boolean defaultOnly, int userId) {
9269            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9270            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9271        }
9272
9273        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9274                int userId) {
9275            if (!sUserManager.exists(userId))
9276                return null;
9277            mFlags = flags;
9278            return super.queryIntent(intent, resolvedType,
9279                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9280        }
9281
9282        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9283                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9284            if (!sUserManager.exists(userId))
9285                return null;
9286            if (packageProviders == null) {
9287                return null;
9288            }
9289            mFlags = flags;
9290            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9291            final int N = packageProviders.size();
9292            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9293                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9294
9295            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9296            for (int i = 0; i < N; ++i) {
9297                intentFilters = packageProviders.get(i).intents;
9298                if (intentFilters != null && intentFilters.size() > 0) {
9299                    PackageParser.ProviderIntentInfo[] array =
9300                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9301                    intentFilters.toArray(array);
9302                    listCut.add(array);
9303                }
9304            }
9305            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9306        }
9307
9308        public final void addProvider(PackageParser.Provider p) {
9309            if (mProviders.containsKey(p.getComponentName())) {
9310                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9311                return;
9312            }
9313
9314            mProviders.put(p.getComponentName(), p);
9315            if (DEBUG_SHOW_INFO) {
9316                Log.v(TAG, "  "
9317                        + (p.info.nonLocalizedLabel != null
9318                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9319                Log.v(TAG, "    Class=" + p.info.name);
9320            }
9321            final int NI = p.intents.size();
9322            int j;
9323            for (j = 0; j < NI; j++) {
9324                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9325                if (DEBUG_SHOW_INFO) {
9326                    Log.v(TAG, "    IntentFilter:");
9327                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9328                }
9329                if (!intent.debugCheck()) {
9330                    Log.w(TAG, "==> For Provider " + p.info.name);
9331                }
9332                addFilter(intent);
9333            }
9334        }
9335
9336        public final void removeProvider(PackageParser.Provider p) {
9337            mProviders.remove(p.getComponentName());
9338            if (DEBUG_SHOW_INFO) {
9339                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9340                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9341                Log.v(TAG, "    Class=" + p.info.name);
9342            }
9343            final int NI = p.intents.size();
9344            int j;
9345            for (j = 0; j < NI; j++) {
9346                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9347                if (DEBUG_SHOW_INFO) {
9348                    Log.v(TAG, "    IntentFilter:");
9349                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9350                }
9351                removeFilter(intent);
9352            }
9353        }
9354
9355        @Override
9356        protected boolean allowFilterResult(
9357                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9358            ProviderInfo filterPi = filter.provider.info;
9359            for (int i = dest.size() - 1; i >= 0; i--) {
9360                ProviderInfo destPi = dest.get(i).providerInfo;
9361                if (destPi.name == filterPi.name
9362                        && destPi.packageName == filterPi.packageName) {
9363                    return false;
9364                }
9365            }
9366            return true;
9367        }
9368
9369        @Override
9370        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9371            return new PackageParser.ProviderIntentInfo[size];
9372        }
9373
9374        @Override
9375        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9376            if (!sUserManager.exists(userId))
9377                return true;
9378            PackageParser.Package p = filter.provider.owner;
9379            if (p != null) {
9380                PackageSetting ps = (PackageSetting) p.mExtras;
9381                if (ps != null) {
9382                    // System apps are never considered stopped for purposes of
9383                    // filtering, because there may be no way for the user to
9384                    // actually re-launch them.
9385                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9386                            && ps.getStopped(userId);
9387                }
9388            }
9389            return false;
9390        }
9391
9392        @Override
9393        protected boolean isPackageForFilter(String packageName,
9394                PackageParser.ProviderIntentInfo info) {
9395            return packageName.equals(info.provider.owner.packageName);
9396        }
9397
9398        @Override
9399        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9400                int match, int userId) {
9401            if (!sUserManager.exists(userId))
9402                return null;
9403            final PackageParser.ProviderIntentInfo info = filter;
9404            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9405                return null;
9406            }
9407            final PackageParser.Provider provider = info.provider;
9408            if (mSafeMode && (provider.info.applicationInfo.flags
9409                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9410                return null;
9411            }
9412            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9413            if (ps == null) {
9414                return null;
9415            }
9416            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9417                    ps.readUserState(userId), userId);
9418            if (pi == null) {
9419                return null;
9420            }
9421            final ResolveInfo res = new ResolveInfo();
9422            res.providerInfo = pi;
9423            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9424                res.filter = filter;
9425            }
9426            res.priority = info.getPriority();
9427            res.preferredOrder = provider.owner.mPreferredOrder;
9428            res.match = match;
9429            res.isDefault = info.hasDefault;
9430            res.labelRes = info.labelRes;
9431            res.nonLocalizedLabel = info.nonLocalizedLabel;
9432            res.icon = info.icon;
9433            res.system = res.providerInfo.applicationInfo.isSystemApp();
9434            return res;
9435        }
9436
9437        @Override
9438        protected void sortResults(List<ResolveInfo> results) {
9439            Collections.sort(results, mResolvePrioritySorter);
9440        }
9441
9442        @Override
9443        protected void dumpFilter(PrintWriter out, String prefix,
9444                PackageParser.ProviderIntentInfo filter) {
9445            out.print(prefix);
9446            out.print(
9447                    Integer.toHexString(System.identityHashCode(filter.provider)));
9448            out.print(' ');
9449            filter.provider.printComponentShortName(out);
9450            out.print(" filter ");
9451            out.println(Integer.toHexString(System.identityHashCode(filter)));
9452        }
9453
9454        @Override
9455        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9456            return filter.provider;
9457        }
9458
9459        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9460            PackageParser.Provider provider = (PackageParser.Provider)label;
9461            out.print(prefix); out.print(
9462                    Integer.toHexString(System.identityHashCode(provider)));
9463                    out.print(' ');
9464                    provider.printComponentShortName(out);
9465            if (count > 1) {
9466                out.print(" ("); out.print(count); out.print(" filters)");
9467            }
9468            out.println();
9469        }
9470
9471        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9472                = new ArrayMap<ComponentName, PackageParser.Provider>();
9473        private int mFlags;
9474    };
9475
9476    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9477            new Comparator<ResolveInfo>() {
9478        public int compare(ResolveInfo r1, ResolveInfo r2) {
9479            int v1 = r1.priority;
9480            int v2 = r2.priority;
9481            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9482            if (v1 != v2) {
9483                return (v1 > v2) ? -1 : 1;
9484            }
9485            v1 = r1.preferredOrder;
9486            v2 = r2.preferredOrder;
9487            if (v1 != v2) {
9488                return (v1 > v2) ? -1 : 1;
9489            }
9490            if (r1.isDefault != r2.isDefault) {
9491                return r1.isDefault ? -1 : 1;
9492            }
9493            v1 = r1.match;
9494            v2 = r2.match;
9495            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9496            if (v1 != v2) {
9497                return (v1 > v2) ? -1 : 1;
9498            }
9499            if (r1.system != r2.system) {
9500                return r1.system ? -1 : 1;
9501            }
9502            return 0;
9503        }
9504    };
9505
9506    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9507            new Comparator<ProviderInfo>() {
9508        public int compare(ProviderInfo p1, ProviderInfo p2) {
9509            final int v1 = p1.initOrder;
9510            final int v2 = p2.initOrder;
9511            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9512        }
9513    };
9514
9515    final void sendPackageBroadcast(final String action, final String pkg,
9516            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9517            final int[] userIds) {
9518        mHandler.post(new Runnable() {
9519            @Override
9520            public void run() {
9521                try {
9522                    final IActivityManager am = ActivityManagerNative.getDefault();
9523                    if (am == null) return;
9524                    final int[] resolvedUserIds;
9525                    if (userIds == null) {
9526                        resolvedUserIds = am.getRunningUserIds();
9527                    } else {
9528                        resolvedUserIds = userIds;
9529                    }
9530                    for (int id : resolvedUserIds) {
9531                        final Intent intent = new Intent(action,
9532                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9533                        if (extras != null) {
9534                            intent.putExtras(extras);
9535                        }
9536                        if (targetPkg != null) {
9537                            intent.setPackage(targetPkg);
9538                        }
9539                        // Modify the UID when posting to other users
9540                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9541                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9542                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9543                            intent.putExtra(Intent.EXTRA_UID, uid);
9544                        }
9545                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9546                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9547                        if (DEBUG_BROADCASTS) {
9548                            RuntimeException here = new RuntimeException("here");
9549                            here.fillInStackTrace();
9550                            Slog.d(TAG, "Sending to user " + id + ": "
9551                                    + intent.toShortString(false, true, false, false)
9552                                    + " " + intent.getExtras(), here);
9553                        }
9554                        am.broadcastIntent(null, intent, null, finishedReceiver,
9555                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9556                                null, finishedReceiver != null, false, id);
9557                    }
9558                } catch (RemoteException ex) {
9559                }
9560            }
9561        });
9562    }
9563
9564    /**
9565     * Check if the external storage media is available. This is true if there
9566     * is a mounted external storage medium or if the external storage is
9567     * emulated.
9568     */
9569    private boolean isExternalMediaAvailable() {
9570        return mMediaMounted || Environment.isExternalStorageEmulated();
9571    }
9572
9573    @Override
9574    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9575        // writer
9576        synchronized (mPackages) {
9577            if (!isExternalMediaAvailable()) {
9578                // If the external storage is no longer mounted at this point,
9579                // the caller may not have been able to delete all of this
9580                // packages files and can not delete any more.  Bail.
9581                return null;
9582            }
9583            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9584            if (lastPackage != null) {
9585                pkgs.remove(lastPackage);
9586            }
9587            if (pkgs.size() > 0) {
9588                return pkgs.get(0);
9589            }
9590        }
9591        return null;
9592    }
9593
9594    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9595        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9596                userId, andCode ? 1 : 0, packageName);
9597        if (mSystemReady) {
9598            msg.sendToTarget();
9599        } else {
9600            if (mPostSystemReadyMessages == null) {
9601                mPostSystemReadyMessages = new ArrayList<>();
9602            }
9603            mPostSystemReadyMessages.add(msg);
9604        }
9605    }
9606
9607    void startCleaningPackages() {
9608        // reader
9609        synchronized (mPackages) {
9610            if (!isExternalMediaAvailable()) {
9611                return;
9612            }
9613            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9614                return;
9615            }
9616        }
9617        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9618        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9619        IActivityManager am = ActivityManagerNative.getDefault();
9620        if (am != null) {
9621            try {
9622                am.startService(null, intent, null, mContext.getOpPackageName(),
9623                        UserHandle.USER_OWNER);
9624            } catch (RemoteException e) {
9625            }
9626        }
9627    }
9628
9629    @Override
9630    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9631            int installFlags, String installerPackageName, VerificationParams verificationParams,
9632            String packageAbiOverride) {
9633        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9634                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9635    }
9636
9637    @Override
9638    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9639            int installFlags, String installerPackageName, VerificationParams verificationParams,
9640            String packageAbiOverride, int userId) {
9641        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9642
9643        final int callingUid = Binder.getCallingUid();
9644        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9645
9646        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9647            try {
9648                if (observer != null) {
9649                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9650                }
9651            } catch (RemoteException re) {
9652            }
9653            return;
9654        }
9655
9656        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9657            installFlags |= PackageManager.INSTALL_FROM_ADB;
9658
9659        } else {
9660            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9661            // about installerPackageName.
9662
9663            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9664            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9665        }
9666
9667        UserHandle user;
9668        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9669            user = UserHandle.ALL;
9670        } else {
9671            user = new UserHandle(userId);
9672        }
9673
9674        // Only system components can circumvent runtime permissions when installing.
9675        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9676                && mContext.checkCallingOrSelfPermission(Manifest.permission
9677                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9678            throw new SecurityException("You need the "
9679                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9680                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9681        }
9682
9683        verificationParams.setInstallerUid(callingUid);
9684
9685        final File originFile = new File(originPath);
9686        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9687
9688        final Message msg = mHandler.obtainMessage(INIT_COPY);
9689        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9690                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9691        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
9692        msg.obj = params;
9693
9694        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
9695                System.identityHashCode(msg.obj));
9696        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9697                System.identityHashCode(msg.obj));
9698
9699        mHandler.sendMessage(msg);
9700    }
9701
9702    void installStage(String packageName, File stagedDir, String stagedCid,
9703            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
9704            String installerPackageName, int installerUid, UserHandle user) {
9705        final VerificationParams verifParams = new VerificationParams(
9706                null, sessionParams.originatingUri, sessionParams.referrerUri, installerUid, null);
9707        verifParams.setInstallerUid(installerUid);
9708
9709        final OriginInfo origin;
9710        if (stagedDir != null) {
9711            origin = OriginInfo.fromStagedFile(stagedDir);
9712        } else {
9713            origin = OriginInfo.fromStagedContainer(stagedCid);
9714        }
9715
9716        final Message msg = mHandler.obtainMessage(INIT_COPY);
9717        final InstallParams params = new InstallParams(origin, null, observer,
9718                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
9719                verifParams, user, sessionParams.abiOverride,
9720                sessionParams.grantedRuntimePermissions);
9721        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
9722        msg.obj = params;
9723
9724        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
9725                System.identityHashCode(msg.obj));
9726        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9727                System.identityHashCode(msg.obj));
9728
9729        mHandler.sendMessage(msg);
9730    }
9731
9732    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9733        Bundle extras = new Bundle(1);
9734        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9735
9736        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9737                packageName, extras, null, null, new int[] {userId});
9738        try {
9739            IActivityManager am = ActivityManagerNative.getDefault();
9740            final boolean isSystem =
9741                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9742            if (isSystem && am.isUserRunning(userId, false)) {
9743                // The just-installed/enabled app is bundled on the system, so presumed
9744                // to be able to run automatically without needing an explicit launch.
9745                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9746                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9747                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9748                        .setPackage(packageName);
9749                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9750                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9751            }
9752        } catch (RemoteException e) {
9753            // shouldn't happen
9754            Slog.w(TAG, "Unable to bootstrap installed package", e);
9755        }
9756    }
9757
9758    @Override
9759    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9760            int userId) {
9761        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9762        PackageSetting pkgSetting;
9763        final int uid = Binder.getCallingUid();
9764        enforceCrossUserPermission(uid, userId, true, true,
9765                "setApplicationHiddenSetting for user " + userId);
9766
9767        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9768            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9769            return false;
9770        }
9771
9772        long callingId = Binder.clearCallingIdentity();
9773        try {
9774            boolean sendAdded = false;
9775            boolean sendRemoved = false;
9776            // writer
9777            synchronized (mPackages) {
9778                pkgSetting = mSettings.mPackages.get(packageName);
9779                if (pkgSetting == null) {
9780                    return false;
9781                }
9782                if (pkgSetting.getHidden(userId) != hidden) {
9783                    pkgSetting.setHidden(hidden, userId);
9784                    mSettings.writePackageRestrictionsLPr(userId);
9785                    if (hidden) {
9786                        sendRemoved = true;
9787                    } else {
9788                        sendAdded = true;
9789                    }
9790                }
9791            }
9792            if (sendAdded) {
9793                sendPackageAddedForUser(packageName, pkgSetting, userId);
9794                return true;
9795            }
9796            if (sendRemoved) {
9797                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9798                        "hiding pkg");
9799                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9800                return true;
9801            }
9802        } finally {
9803            Binder.restoreCallingIdentity(callingId);
9804        }
9805        return false;
9806    }
9807
9808    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9809            int userId) {
9810        final PackageRemovedInfo info = new PackageRemovedInfo();
9811        info.removedPackage = packageName;
9812        info.removedUsers = new int[] {userId};
9813        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9814        info.sendBroadcast(false, false, false);
9815    }
9816
9817    /**
9818     * Returns true if application is not found or there was an error. Otherwise it returns
9819     * the hidden state of the package for the given user.
9820     */
9821    @Override
9822    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9823        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9824        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9825                false, "getApplicationHidden for user " + userId);
9826        PackageSetting pkgSetting;
9827        long callingId = Binder.clearCallingIdentity();
9828        try {
9829            // writer
9830            synchronized (mPackages) {
9831                pkgSetting = mSettings.mPackages.get(packageName);
9832                if (pkgSetting == null) {
9833                    return true;
9834                }
9835                return pkgSetting.getHidden(userId);
9836            }
9837        } finally {
9838            Binder.restoreCallingIdentity(callingId);
9839        }
9840    }
9841
9842    /**
9843     * @hide
9844     */
9845    @Override
9846    public int installExistingPackageAsUser(String packageName, int userId) {
9847        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9848                null);
9849        PackageSetting pkgSetting;
9850        final int uid = Binder.getCallingUid();
9851        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9852                + userId);
9853        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9854            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9855        }
9856
9857        long callingId = Binder.clearCallingIdentity();
9858        try {
9859            boolean sendAdded = false;
9860
9861            // writer
9862            synchronized (mPackages) {
9863                pkgSetting = mSettings.mPackages.get(packageName);
9864                if (pkgSetting == null) {
9865                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9866                }
9867                if (!pkgSetting.getInstalled(userId)) {
9868                    pkgSetting.setInstalled(true, userId);
9869                    pkgSetting.setHidden(false, userId);
9870                    mSettings.writePackageRestrictionsLPr(userId);
9871                    sendAdded = true;
9872                }
9873            }
9874
9875            if (sendAdded) {
9876                sendPackageAddedForUser(packageName, pkgSetting, userId);
9877            }
9878        } finally {
9879            Binder.restoreCallingIdentity(callingId);
9880        }
9881
9882        return PackageManager.INSTALL_SUCCEEDED;
9883    }
9884
9885    boolean isUserRestricted(int userId, String restrictionKey) {
9886        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9887        if (restrictions.getBoolean(restrictionKey, false)) {
9888            Log.w(TAG, "User is restricted: " + restrictionKey);
9889            return true;
9890        }
9891        return false;
9892    }
9893
9894    @Override
9895    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9896        mContext.enforceCallingOrSelfPermission(
9897                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9898                "Only package verification agents can verify applications");
9899
9900        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9901        final PackageVerificationResponse response = new PackageVerificationResponse(
9902                verificationCode, Binder.getCallingUid());
9903        msg.arg1 = id;
9904        msg.obj = response;
9905        mHandler.sendMessage(msg);
9906    }
9907
9908    @Override
9909    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9910            long millisecondsToDelay) {
9911        mContext.enforceCallingOrSelfPermission(
9912                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9913                "Only package verification agents can extend verification timeouts");
9914
9915        final PackageVerificationState state = mPendingVerification.get(id);
9916        final PackageVerificationResponse response = new PackageVerificationResponse(
9917                verificationCodeAtTimeout, Binder.getCallingUid());
9918
9919        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9920            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9921        }
9922        if (millisecondsToDelay < 0) {
9923            millisecondsToDelay = 0;
9924        }
9925        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9926                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9927            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9928        }
9929
9930        if ((state != null) && !state.timeoutExtended()) {
9931            state.extendTimeout();
9932
9933            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9934            msg.arg1 = id;
9935            msg.obj = response;
9936            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9937        }
9938    }
9939
9940    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9941            int verificationCode, UserHandle user) {
9942        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9943        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9944        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9945        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9946        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9947
9948        mContext.sendBroadcastAsUser(intent, user,
9949                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9950    }
9951
9952    private ComponentName matchComponentForVerifier(String packageName,
9953            List<ResolveInfo> receivers) {
9954        ActivityInfo targetReceiver = null;
9955
9956        final int NR = receivers.size();
9957        for (int i = 0; i < NR; i++) {
9958            final ResolveInfo info = receivers.get(i);
9959            if (info.activityInfo == null) {
9960                continue;
9961            }
9962
9963            if (packageName.equals(info.activityInfo.packageName)) {
9964                targetReceiver = info.activityInfo;
9965                break;
9966            }
9967        }
9968
9969        if (targetReceiver == null) {
9970            return null;
9971        }
9972
9973        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9974    }
9975
9976    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9977            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9978        if (pkgInfo.verifiers.length == 0) {
9979            return null;
9980        }
9981
9982        final int N = pkgInfo.verifiers.length;
9983        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9984        for (int i = 0; i < N; i++) {
9985            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9986
9987            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9988                    receivers);
9989            if (comp == null) {
9990                continue;
9991            }
9992
9993            final int verifierUid = getUidForVerifier(verifierInfo);
9994            if (verifierUid == -1) {
9995                continue;
9996            }
9997
9998            if (DEBUG_VERIFY) {
9999                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10000                        + " with the correct signature");
10001            }
10002            sufficientVerifiers.add(comp);
10003            verificationState.addSufficientVerifier(verifierUid);
10004        }
10005
10006        return sufficientVerifiers;
10007    }
10008
10009    private int getUidForVerifier(VerifierInfo verifierInfo) {
10010        synchronized (mPackages) {
10011            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10012            if (pkg == null) {
10013                return -1;
10014            } else if (pkg.mSignatures.length != 1) {
10015                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10016                        + " has more than one signature; ignoring");
10017                return -1;
10018            }
10019
10020            /*
10021             * If the public key of the package's signature does not match
10022             * our expected public key, then this is a different package and
10023             * we should skip.
10024             */
10025
10026            final byte[] expectedPublicKey;
10027            try {
10028                final Signature verifierSig = pkg.mSignatures[0];
10029                final PublicKey publicKey = verifierSig.getPublicKey();
10030                expectedPublicKey = publicKey.getEncoded();
10031            } catch (CertificateException e) {
10032                return -1;
10033            }
10034
10035            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10036
10037            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10038                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10039                        + " does not have the expected public key; ignoring");
10040                return -1;
10041            }
10042
10043            return pkg.applicationInfo.uid;
10044        }
10045    }
10046
10047    @Override
10048    public void finishPackageInstall(int token) {
10049        enforceSystemOrRoot("Only the system is allowed to finish installs");
10050
10051        if (DEBUG_INSTALL) {
10052            Slog.v(TAG, "BM finishing package install for " + token);
10053        }
10054        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10055
10056        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10057        mHandler.sendMessage(msg);
10058    }
10059
10060    /**
10061     * Get the verification agent timeout.
10062     *
10063     * @return verification timeout in milliseconds
10064     */
10065    private long getVerificationTimeout() {
10066        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10067                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10068                DEFAULT_VERIFICATION_TIMEOUT);
10069    }
10070
10071    /**
10072     * Get the default verification agent response code.
10073     *
10074     * @return default verification response code
10075     */
10076    private int getDefaultVerificationResponse() {
10077        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10078                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10079                DEFAULT_VERIFICATION_RESPONSE);
10080    }
10081
10082    /**
10083     * Check whether or not package verification has been enabled.
10084     *
10085     * @return true if verification should be performed
10086     */
10087    private boolean isVerificationEnabled(int userId, int installFlags) {
10088        if (!DEFAULT_VERIFY_ENABLE) {
10089            return false;
10090        }
10091
10092        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10093
10094        // Check if installing from ADB
10095        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10096            // Do not run verification in a test harness environment
10097            if (ActivityManager.isRunningInTestHarness()) {
10098                return false;
10099            }
10100            if (ensureVerifyAppsEnabled) {
10101                return true;
10102            }
10103            // Check if the developer does not want package verification for ADB installs
10104            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10105                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10106                return false;
10107            }
10108        }
10109
10110        if (ensureVerifyAppsEnabled) {
10111            return true;
10112        }
10113
10114        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10115                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10116    }
10117
10118    @Override
10119    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10120            throws RemoteException {
10121        mContext.enforceCallingOrSelfPermission(
10122                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10123                "Only intentfilter verification agents can verify applications");
10124
10125        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10126        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10127                Binder.getCallingUid(), verificationCode, failedDomains);
10128        msg.arg1 = id;
10129        msg.obj = response;
10130        mHandler.sendMessage(msg);
10131    }
10132
10133    @Override
10134    public int getIntentVerificationStatus(String packageName, int userId) {
10135        synchronized (mPackages) {
10136            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10137        }
10138    }
10139
10140    @Override
10141    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10142        mContext.enforceCallingOrSelfPermission(
10143                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10144
10145        boolean result = false;
10146        synchronized (mPackages) {
10147            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10148        }
10149        if (result) {
10150            scheduleWritePackageRestrictionsLocked(userId);
10151        }
10152        return result;
10153    }
10154
10155    @Override
10156    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10157        synchronized (mPackages) {
10158            return mSettings.getIntentFilterVerificationsLPr(packageName);
10159        }
10160    }
10161
10162    @Override
10163    public List<IntentFilter> getAllIntentFilters(String packageName) {
10164        if (TextUtils.isEmpty(packageName)) {
10165            return Collections.<IntentFilter>emptyList();
10166        }
10167        synchronized (mPackages) {
10168            PackageParser.Package pkg = mPackages.get(packageName);
10169            if (pkg == null || pkg.activities == null) {
10170                return Collections.<IntentFilter>emptyList();
10171            }
10172            final int count = pkg.activities.size();
10173            ArrayList<IntentFilter> result = new ArrayList<>();
10174            for (int n=0; n<count; n++) {
10175                PackageParser.Activity activity = pkg.activities.get(n);
10176                if (activity.intents != null || activity.intents.size() > 0) {
10177                    result.addAll(activity.intents);
10178                }
10179            }
10180            return result;
10181        }
10182    }
10183
10184    @Override
10185    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10186        mContext.enforceCallingOrSelfPermission(
10187                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10188
10189        synchronized (mPackages) {
10190            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10191            if (packageName != null) {
10192                result |= updateIntentVerificationStatus(packageName,
10193                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10194                        userId);
10195                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10196                        packageName, userId);
10197            }
10198            return result;
10199        }
10200    }
10201
10202    @Override
10203    public String getDefaultBrowserPackageName(int userId) {
10204        synchronized (mPackages) {
10205            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10206        }
10207    }
10208
10209    /**
10210     * Get the "allow unknown sources" setting.
10211     *
10212     * @return the current "allow unknown sources" setting
10213     */
10214    private int getUnknownSourcesSettings() {
10215        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10216                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10217                -1);
10218    }
10219
10220    @Override
10221    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10222        final int uid = Binder.getCallingUid();
10223        // writer
10224        synchronized (mPackages) {
10225            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10226            if (targetPackageSetting == null) {
10227                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10228            }
10229
10230            PackageSetting installerPackageSetting;
10231            if (installerPackageName != null) {
10232                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10233                if (installerPackageSetting == null) {
10234                    throw new IllegalArgumentException("Unknown installer package: "
10235                            + installerPackageName);
10236                }
10237            } else {
10238                installerPackageSetting = null;
10239            }
10240
10241            Signature[] callerSignature;
10242            Object obj = mSettings.getUserIdLPr(uid);
10243            if (obj != null) {
10244                if (obj instanceof SharedUserSetting) {
10245                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10246                } else if (obj instanceof PackageSetting) {
10247                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10248                } else {
10249                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10250                }
10251            } else {
10252                throw new SecurityException("Unknown calling uid " + uid);
10253            }
10254
10255            // Verify: can't set installerPackageName to a package that is
10256            // not signed with the same cert as the caller.
10257            if (installerPackageSetting != null) {
10258                if (compareSignatures(callerSignature,
10259                        installerPackageSetting.signatures.mSignatures)
10260                        != PackageManager.SIGNATURE_MATCH) {
10261                    throw new SecurityException(
10262                            "Caller does not have same cert as new installer package "
10263                            + installerPackageName);
10264                }
10265            }
10266
10267            // Verify: if target already has an installer package, it must
10268            // be signed with the same cert as the caller.
10269            if (targetPackageSetting.installerPackageName != null) {
10270                PackageSetting setting = mSettings.mPackages.get(
10271                        targetPackageSetting.installerPackageName);
10272                // If the currently set package isn't valid, then it's always
10273                // okay to change it.
10274                if (setting != null) {
10275                    if (compareSignatures(callerSignature,
10276                            setting.signatures.mSignatures)
10277                            != PackageManager.SIGNATURE_MATCH) {
10278                        throw new SecurityException(
10279                                "Caller does not have same cert as old installer package "
10280                                + targetPackageSetting.installerPackageName);
10281                    }
10282                }
10283            }
10284
10285            // Okay!
10286            targetPackageSetting.installerPackageName = installerPackageName;
10287            scheduleWriteSettingsLocked();
10288        }
10289    }
10290
10291    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10292        // Queue up an async operation since the package installation may take a little while.
10293        mHandler.post(new Runnable() {
10294            public void run() {
10295                mHandler.removeCallbacks(this);
10296                 // Result object to be returned
10297                PackageInstalledInfo res = new PackageInstalledInfo();
10298                res.returnCode = currentStatus;
10299                res.uid = -1;
10300                res.pkg = null;
10301                res.removedInfo = new PackageRemovedInfo();
10302                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10303                    args.doPreInstall(res.returnCode);
10304                    synchronized (mInstallLock) {
10305                        installPackageTracedLI(args, res);
10306                    }
10307                    args.doPostInstall(res.returnCode, res.uid);
10308                }
10309
10310                // A restore should be performed at this point if (a) the install
10311                // succeeded, (b) the operation is not an update, and (c) the new
10312                // package has not opted out of backup participation.
10313                final boolean update = res.removedInfo.removedPackage != null;
10314                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10315                boolean doRestore = !update
10316                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10317
10318                // Set up the post-install work request bookkeeping.  This will be used
10319                // and cleaned up by the post-install event handling regardless of whether
10320                // there's a restore pass performed.  Token values are >= 1.
10321                int token;
10322                if (mNextInstallToken < 0) mNextInstallToken = 1;
10323                token = mNextInstallToken++;
10324
10325                PostInstallData data = new PostInstallData(args, res);
10326                mRunningInstalls.put(token, data);
10327                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10328
10329                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10330                    // Pass responsibility to the Backup Manager.  It will perform a
10331                    // restore if appropriate, then pass responsibility back to the
10332                    // Package Manager to run the post-install observer callbacks
10333                    // and broadcasts.
10334                    IBackupManager bm = IBackupManager.Stub.asInterface(
10335                            ServiceManager.getService(Context.BACKUP_SERVICE));
10336                    if (bm != null) {
10337                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10338                                + " to BM for possible restore");
10339                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10340                        try {
10341                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10342                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10343                            } else {
10344                                doRestore = false;
10345                            }
10346                        } catch (RemoteException e) {
10347                            // can't happen; the backup manager is local
10348                        } catch (Exception e) {
10349                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10350                            doRestore = false;
10351                        }
10352                    } else {
10353                        Slog.e(TAG, "Backup Manager not found!");
10354                        doRestore = false;
10355                    }
10356                }
10357
10358                if (!doRestore) {
10359                    // No restore possible, or the Backup Manager was mysteriously not
10360                    // available -- just fire the post-install work request directly.
10361                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10362
10363                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10364
10365                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10366                    mHandler.sendMessage(msg);
10367                }
10368            }
10369        });
10370    }
10371
10372    private abstract class HandlerParams {
10373        private static final int MAX_RETRIES = 4;
10374
10375        /**
10376         * Number of times startCopy() has been attempted and had a non-fatal
10377         * error.
10378         */
10379        private int mRetries = 0;
10380
10381        /** User handle for the user requesting the information or installation. */
10382        private final UserHandle mUser;
10383        String traceMethod;
10384        int traceCookie;
10385
10386        HandlerParams(UserHandle user) {
10387            mUser = user;
10388        }
10389
10390        UserHandle getUser() {
10391            return mUser;
10392        }
10393
10394        HandlerParams setTraceMethod(String traceMethod) {
10395            this.traceMethod = traceMethod;
10396            return this;
10397        }
10398
10399        HandlerParams setTraceCookie(int traceCookie) {
10400            this.traceCookie = traceCookie;
10401            return this;
10402        }
10403
10404        final boolean startCopy() {
10405            boolean res;
10406            try {
10407                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10408
10409                if (++mRetries > MAX_RETRIES) {
10410                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10411                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10412                    handleServiceError();
10413                    return false;
10414                } else {
10415                    handleStartCopy();
10416                    res = true;
10417                }
10418            } catch (RemoteException e) {
10419                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10420                mHandler.sendEmptyMessage(MCS_RECONNECT);
10421                res = false;
10422            }
10423            handleReturnCode();
10424            return res;
10425        }
10426
10427        final void serviceError() {
10428            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10429            handleServiceError();
10430            handleReturnCode();
10431        }
10432
10433        abstract void handleStartCopy() throws RemoteException;
10434        abstract void handleServiceError();
10435        abstract void handleReturnCode();
10436    }
10437
10438    class MeasureParams extends HandlerParams {
10439        private final PackageStats mStats;
10440        private boolean mSuccess;
10441
10442        private final IPackageStatsObserver mObserver;
10443
10444        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10445            super(new UserHandle(stats.userHandle));
10446            mObserver = observer;
10447            mStats = stats;
10448        }
10449
10450        @Override
10451        public String toString() {
10452            return "MeasureParams{"
10453                + Integer.toHexString(System.identityHashCode(this))
10454                + " " + mStats.packageName + "}";
10455        }
10456
10457        @Override
10458        void handleStartCopy() throws RemoteException {
10459            synchronized (mInstallLock) {
10460                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10461            }
10462
10463            if (mSuccess) {
10464                final boolean mounted;
10465                if (Environment.isExternalStorageEmulated()) {
10466                    mounted = true;
10467                } else {
10468                    final String status = Environment.getExternalStorageState();
10469                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10470                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10471                }
10472
10473                if (mounted) {
10474                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10475
10476                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10477                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10478
10479                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10480                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10481
10482                    // Always subtract cache size, since it's a subdirectory
10483                    mStats.externalDataSize -= mStats.externalCacheSize;
10484
10485                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10486                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10487
10488                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10489                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10490                }
10491            }
10492        }
10493
10494        @Override
10495        void handleReturnCode() {
10496            if (mObserver != null) {
10497                try {
10498                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10499                } catch (RemoteException e) {
10500                    Slog.i(TAG, "Observer no longer exists.");
10501                }
10502            }
10503        }
10504
10505        @Override
10506        void handleServiceError() {
10507            Slog.e(TAG, "Could not measure application " + mStats.packageName
10508                            + " external storage");
10509        }
10510    }
10511
10512    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10513            throws RemoteException {
10514        long result = 0;
10515        for (File path : paths) {
10516            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10517        }
10518        return result;
10519    }
10520
10521    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10522        for (File path : paths) {
10523            try {
10524                mcs.clearDirectory(path.getAbsolutePath());
10525            } catch (RemoteException e) {
10526            }
10527        }
10528    }
10529
10530    static class OriginInfo {
10531        /**
10532         * Location where install is coming from, before it has been
10533         * copied/renamed into place. This could be a single monolithic APK
10534         * file, or a cluster directory. This location may be untrusted.
10535         */
10536        final File file;
10537        final String cid;
10538
10539        /**
10540         * Flag indicating that {@link #file} or {@link #cid} has already been
10541         * staged, meaning downstream users don't need to defensively copy the
10542         * contents.
10543         */
10544        final boolean staged;
10545
10546        /**
10547         * Flag indicating that {@link #file} or {@link #cid} is an already
10548         * installed app that is being moved.
10549         */
10550        final boolean existing;
10551
10552        final String resolvedPath;
10553        final File resolvedFile;
10554
10555        static OriginInfo fromNothing() {
10556            return new OriginInfo(null, null, false, false);
10557        }
10558
10559        static OriginInfo fromUntrustedFile(File file) {
10560            return new OriginInfo(file, null, false, false);
10561        }
10562
10563        static OriginInfo fromExistingFile(File file) {
10564            return new OriginInfo(file, null, false, true);
10565        }
10566
10567        static OriginInfo fromStagedFile(File file) {
10568            return new OriginInfo(file, null, true, false);
10569        }
10570
10571        static OriginInfo fromStagedContainer(String cid) {
10572            return new OriginInfo(null, cid, true, false);
10573        }
10574
10575        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10576            this.file = file;
10577            this.cid = cid;
10578            this.staged = staged;
10579            this.existing = existing;
10580
10581            if (cid != null) {
10582                resolvedPath = PackageHelper.getSdDir(cid);
10583                resolvedFile = new File(resolvedPath);
10584            } else if (file != null) {
10585                resolvedPath = file.getAbsolutePath();
10586                resolvedFile = file;
10587            } else {
10588                resolvedPath = null;
10589                resolvedFile = null;
10590            }
10591        }
10592    }
10593
10594    class MoveInfo {
10595        final int moveId;
10596        final String fromUuid;
10597        final String toUuid;
10598        final String packageName;
10599        final String dataAppName;
10600        final int appId;
10601        final String seinfo;
10602
10603        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10604                String dataAppName, int appId, String seinfo) {
10605            this.moveId = moveId;
10606            this.fromUuid = fromUuid;
10607            this.toUuid = toUuid;
10608            this.packageName = packageName;
10609            this.dataAppName = dataAppName;
10610            this.appId = appId;
10611            this.seinfo = seinfo;
10612        }
10613    }
10614
10615    class InstallParams extends HandlerParams {
10616        final OriginInfo origin;
10617        final MoveInfo move;
10618        final IPackageInstallObserver2 observer;
10619        int installFlags;
10620        final String installerPackageName;
10621        final String volumeUuid;
10622        final VerificationParams verificationParams;
10623        private InstallArgs mArgs;
10624        private int mRet;
10625        final String packageAbiOverride;
10626        final String[] grantedRuntimePermissions;
10627
10628        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10629                int installFlags, String installerPackageName, String volumeUuid,
10630                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10631                String[] grantedPermissions) {
10632            super(user);
10633            this.origin = origin;
10634            this.move = move;
10635            this.observer = observer;
10636            this.installFlags = installFlags;
10637            this.installerPackageName = installerPackageName;
10638            this.volumeUuid = volumeUuid;
10639            this.verificationParams = verificationParams;
10640            this.packageAbiOverride = packageAbiOverride;
10641            this.grantedRuntimePermissions = grantedPermissions;
10642        }
10643
10644        @Override
10645        public String toString() {
10646            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10647                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10648        }
10649
10650        public ManifestDigest getManifestDigest() {
10651            if (verificationParams == null) {
10652                return null;
10653            }
10654            return verificationParams.getManifestDigest();
10655        }
10656
10657        private int installLocationPolicy(PackageInfoLite pkgLite) {
10658            String packageName = pkgLite.packageName;
10659            int installLocation = pkgLite.installLocation;
10660            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10661            // reader
10662            synchronized (mPackages) {
10663                PackageParser.Package pkg = mPackages.get(packageName);
10664                if (pkg != null) {
10665                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10666                        // Check for downgrading.
10667                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10668                            try {
10669                                checkDowngrade(pkg, pkgLite);
10670                            } catch (PackageManagerException e) {
10671                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10672                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10673                            }
10674                        }
10675                        // Check for updated system application.
10676                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10677                            if (onSd) {
10678                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10679                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10680                            }
10681                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10682                        } else {
10683                            if (onSd) {
10684                                // Install flag overrides everything.
10685                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10686                            }
10687                            // If current upgrade specifies particular preference
10688                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10689                                // Application explicitly specified internal.
10690                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10691                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10692                                // App explictly prefers external. Let policy decide
10693                            } else {
10694                                // Prefer previous location
10695                                if (isExternal(pkg)) {
10696                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10697                                }
10698                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10699                            }
10700                        }
10701                    } else {
10702                        // Invalid install. Return error code
10703                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10704                    }
10705                }
10706            }
10707            // All the special cases have been taken care of.
10708            // Return result based on recommended install location.
10709            if (onSd) {
10710                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10711            }
10712            return pkgLite.recommendedInstallLocation;
10713        }
10714
10715        /*
10716         * Invoke remote method to get package information and install
10717         * location values. Override install location based on default
10718         * policy if needed and then create install arguments based
10719         * on the install location.
10720         */
10721        public void handleStartCopy() throws RemoteException {
10722            int ret = PackageManager.INSTALL_SUCCEEDED;
10723
10724            // If we're already staged, we've firmly committed to an install location
10725            if (origin.staged) {
10726                if (origin.file != null) {
10727                    installFlags |= PackageManager.INSTALL_INTERNAL;
10728                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10729                } else if (origin.cid != null) {
10730                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10731                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10732                } else {
10733                    throw new IllegalStateException("Invalid stage location");
10734                }
10735            }
10736
10737            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10738            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10739            PackageInfoLite pkgLite = null;
10740
10741            if (onInt && onSd) {
10742                // Check if both bits are set.
10743                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10744                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10745            } else {
10746                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10747                        packageAbiOverride);
10748
10749                /*
10750                 * If we have too little free space, try to free cache
10751                 * before giving up.
10752                 */
10753                if (!origin.staged && pkgLite.recommendedInstallLocation
10754                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10755                    // TODO: focus freeing disk space on the target device
10756                    final StorageManager storage = StorageManager.from(mContext);
10757                    final long lowThreshold = storage.getStorageLowBytes(
10758                            Environment.getDataDirectory());
10759
10760                    final long sizeBytes = mContainerService.calculateInstalledSize(
10761                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10762
10763                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10764                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10765                                installFlags, packageAbiOverride);
10766                    }
10767
10768                    /*
10769                     * The cache free must have deleted the file we
10770                     * downloaded to install.
10771                     *
10772                     * TODO: fix the "freeCache" call to not delete
10773                     *       the file we care about.
10774                     */
10775                    if (pkgLite.recommendedInstallLocation
10776                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10777                        pkgLite.recommendedInstallLocation
10778                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10779                    }
10780                }
10781            }
10782
10783            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10784                int loc = pkgLite.recommendedInstallLocation;
10785                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10786                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10787                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10788                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10789                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10790                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10791                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10792                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10793                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10794                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10795                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10796                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10797                } else {
10798                    // Override with defaults if needed.
10799                    loc = installLocationPolicy(pkgLite);
10800                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10801                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10802                    } else if (!onSd && !onInt) {
10803                        // Override install location with flags
10804                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10805                            // Set the flag to install on external media.
10806                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10807                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10808                        } else {
10809                            // Make sure the flag for installing on external
10810                            // media is unset
10811                            installFlags |= PackageManager.INSTALL_INTERNAL;
10812                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10813                        }
10814                    }
10815                }
10816            }
10817
10818            final InstallArgs args = createInstallArgs(this);
10819            mArgs = args;
10820
10821            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10822                 /*
10823                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10824                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10825                 */
10826                int userIdentifier = getUser().getIdentifier();
10827                if (userIdentifier == UserHandle.USER_ALL
10828                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10829                    userIdentifier = UserHandle.USER_OWNER;
10830                }
10831
10832                /*
10833                 * Determine if we have any installed package verifiers. If we
10834                 * do, then we'll defer to them to verify the packages.
10835                 */
10836                final int requiredUid = mRequiredVerifierPackage == null ? -1
10837                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10838                if (!origin.existing && requiredUid != -1
10839                        && isVerificationEnabled(userIdentifier, installFlags)) {
10840                    final Intent verification = new Intent(
10841                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10842                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10843                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10844                            PACKAGE_MIME_TYPE);
10845                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10846
10847                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10848                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10849                            0 /* TODO: Which userId? */);
10850
10851                    if (DEBUG_VERIFY) {
10852                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10853                                + verification.toString() + " with " + pkgLite.verifiers.length
10854                                + " optional verifiers");
10855                    }
10856
10857                    final int verificationId = mPendingVerificationToken++;
10858
10859                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10860
10861                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10862                            installerPackageName);
10863
10864                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10865                            installFlags);
10866
10867                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10868                            pkgLite.packageName);
10869
10870                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10871                            pkgLite.versionCode);
10872
10873                    if (verificationParams != null) {
10874                        if (verificationParams.getVerificationURI() != null) {
10875                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10876                                 verificationParams.getVerificationURI());
10877                        }
10878                        if (verificationParams.getOriginatingURI() != null) {
10879                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10880                                  verificationParams.getOriginatingURI());
10881                        }
10882                        if (verificationParams.getReferrer() != null) {
10883                            verification.putExtra(Intent.EXTRA_REFERRER,
10884                                  verificationParams.getReferrer());
10885                        }
10886                        if (verificationParams.getOriginatingUid() >= 0) {
10887                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10888                                  verificationParams.getOriginatingUid());
10889                        }
10890                        if (verificationParams.getInstallerUid() >= 0) {
10891                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10892                                  verificationParams.getInstallerUid());
10893                        }
10894                    }
10895
10896                    final PackageVerificationState verificationState = new PackageVerificationState(
10897                            requiredUid, args);
10898
10899                    mPendingVerification.append(verificationId, verificationState);
10900
10901                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10902                            receivers, verificationState);
10903
10904                    // Apps installed for "all" users use the device owner to verify the app
10905                    UserHandle verifierUser = getUser();
10906                    if (verifierUser == UserHandle.ALL) {
10907                        verifierUser = UserHandle.OWNER;
10908                    }
10909
10910                    /*
10911                     * If any sufficient verifiers were listed in the package
10912                     * manifest, attempt to ask them.
10913                     */
10914                    if (sufficientVerifiers != null) {
10915                        final int N = sufficientVerifiers.size();
10916                        if (N == 0) {
10917                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10918                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10919                        } else {
10920                            for (int i = 0; i < N; i++) {
10921                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10922
10923                                final Intent sufficientIntent = new Intent(verification);
10924                                sufficientIntent.setComponent(verifierComponent);
10925                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10926                            }
10927                        }
10928                    }
10929
10930                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10931                            mRequiredVerifierPackage, receivers);
10932                    if (ret == PackageManager.INSTALL_SUCCEEDED
10933                            && mRequiredVerifierPackage != null) {
10934                        Trace.asyncTraceBegin(
10935                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
10936                        /*
10937                         * Send the intent to the required verification agent,
10938                         * but only start the verification timeout after the
10939                         * target BroadcastReceivers have run.
10940                         */
10941                        verification.setComponent(requiredVerifierComponent);
10942                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10943                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10944                                new BroadcastReceiver() {
10945                                    @Override
10946                                    public void onReceive(Context context, Intent intent) {
10947                                        final Message msg = mHandler
10948                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10949                                        msg.arg1 = verificationId;
10950                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10951                                    }
10952                                }, null, 0, null, null);
10953
10954                        /*
10955                         * We don't want the copy to proceed until verification
10956                         * succeeds, so null out this field.
10957                         */
10958                        mArgs = null;
10959                    }
10960                } else {
10961                    /*
10962                     * No package verification is enabled, so immediately start
10963                     * the remote call to initiate copy using temporary file.
10964                     */
10965                    ret = args.copyApk(mContainerService, true);
10966                }
10967            }
10968
10969            mRet = ret;
10970        }
10971
10972        @Override
10973        void handleReturnCode() {
10974            // If mArgs is null, then MCS couldn't be reached. When it
10975            // reconnects, it will try again to install. At that point, this
10976            // will succeed.
10977            if (mArgs != null) {
10978                processPendingInstall(mArgs, mRet);
10979            }
10980        }
10981
10982        @Override
10983        void handleServiceError() {
10984            mArgs = createInstallArgs(this);
10985            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10986        }
10987
10988        public boolean isForwardLocked() {
10989            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10990        }
10991    }
10992
10993    /**
10994     * Used during creation of InstallArgs
10995     *
10996     * @param installFlags package installation flags
10997     * @return true if should be installed on external storage
10998     */
10999    private static boolean installOnExternalAsec(int installFlags) {
11000        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11001            return false;
11002        }
11003        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11004            return true;
11005        }
11006        return false;
11007    }
11008
11009    /**
11010     * Used during creation of InstallArgs
11011     *
11012     * @param installFlags package installation flags
11013     * @return true if should be installed as forward locked
11014     */
11015    private static boolean installForwardLocked(int installFlags) {
11016        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11017    }
11018
11019    private InstallArgs createInstallArgs(InstallParams params) {
11020        if (params.move != null) {
11021            return new MoveInstallArgs(params);
11022        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11023            return new AsecInstallArgs(params);
11024        } else {
11025            return new FileInstallArgs(params);
11026        }
11027    }
11028
11029    /**
11030     * Create args that describe an existing installed package. Typically used
11031     * when cleaning up old installs, or used as a move source.
11032     */
11033    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11034            String resourcePath, String[] instructionSets) {
11035        final boolean isInAsec;
11036        if (installOnExternalAsec(installFlags)) {
11037            /* Apps on SD card are always in ASEC containers. */
11038            isInAsec = true;
11039        } else if (installForwardLocked(installFlags)
11040                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11041            /*
11042             * Forward-locked apps are only in ASEC containers if they're the
11043             * new style
11044             */
11045            isInAsec = true;
11046        } else {
11047            isInAsec = false;
11048        }
11049
11050        if (isInAsec) {
11051            return new AsecInstallArgs(codePath, instructionSets,
11052                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11053        } else {
11054            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11055        }
11056    }
11057
11058    static abstract class InstallArgs {
11059        /** @see InstallParams#origin */
11060        final OriginInfo origin;
11061        /** @see InstallParams#move */
11062        final MoveInfo move;
11063
11064        final IPackageInstallObserver2 observer;
11065        // Always refers to PackageManager flags only
11066        final int installFlags;
11067        final String installerPackageName;
11068        final String volumeUuid;
11069        final ManifestDigest manifestDigest;
11070        final UserHandle user;
11071        final String abiOverride;
11072        final String[] installGrantPermissions;
11073        /** If non-null, drop an async trace when the install completes */
11074        final String traceMethod;
11075        final int traceCookie;
11076
11077        // The list of instruction sets supported by this app. This is currently
11078        // only used during the rmdex() phase to clean up resources. We can get rid of this
11079        // if we move dex files under the common app path.
11080        /* nullable */ String[] instructionSets;
11081
11082        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11083                int installFlags, String installerPackageName, String volumeUuid,
11084                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11085                String abiOverride, String[] installGrantPermissions,
11086                String traceMethod, int traceCookie) {
11087            this.origin = origin;
11088            this.move = move;
11089            this.installFlags = installFlags;
11090            this.observer = observer;
11091            this.installerPackageName = installerPackageName;
11092            this.volumeUuid = volumeUuid;
11093            this.manifestDigest = manifestDigest;
11094            this.user = user;
11095            this.instructionSets = instructionSets;
11096            this.abiOverride = abiOverride;
11097            this.installGrantPermissions = installGrantPermissions;
11098            this.traceMethod = traceMethod;
11099            this.traceCookie = traceCookie;
11100        }
11101
11102        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11103        abstract int doPreInstall(int status);
11104
11105        /**
11106         * Rename package into final resting place. All paths on the given
11107         * scanned package should be updated to reflect the rename.
11108         */
11109        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11110        abstract int doPostInstall(int status, int uid);
11111
11112        /** @see PackageSettingBase#codePathString */
11113        abstract String getCodePath();
11114        /** @see PackageSettingBase#resourcePathString */
11115        abstract String getResourcePath();
11116
11117        // Need installer lock especially for dex file removal.
11118        abstract void cleanUpResourcesLI();
11119        abstract boolean doPostDeleteLI(boolean delete);
11120
11121        /**
11122         * Called before the source arguments are copied. This is used mostly
11123         * for MoveParams when it needs to read the source file to put it in the
11124         * destination.
11125         */
11126        int doPreCopy() {
11127            return PackageManager.INSTALL_SUCCEEDED;
11128        }
11129
11130        /**
11131         * Called after the source arguments are copied. This is used mostly for
11132         * MoveParams when it needs to read the source file to put it in the
11133         * destination.
11134         *
11135         * @return
11136         */
11137        int doPostCopy(int uid) {
11138            return PackageManager.INSTALL_SUCCEEDED;
11139        }
11140
11141        protected boolean isFwdLocked() {
11142            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11143        }
11144
11145        protected boolean isExternalAsec() {
11146            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11147        }
11148
11149        UserHandle getUser() {
11150            return user;
11151        }
11152    }
11153
11154    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11155        if (!allCodePaths.isEmpty()) {
11156            if (instructionSets == null) {
11157                throw new IllegalStateException("instructionSet == null");
11158            }
11159            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11160            for (String codePath : allCodePaths) {
11161                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11162                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11163                    if (retCode < 0) {
11164                        Slog.w(TAG, "Couldn't remove dex file for package: "
11165                                + " at location " + codePath + ", retcode=" + retCode);
11166                        // we don't consider this to be a failure of the core package deletion
11167                    }
11168                }
11169            }
11170        }
11171    }
11172
11173    /**
11174     * Logic to handle installation of non-ASEC applications, including copying
11175     * and renaming logic.
11176     */
11177    class FileInstallArgs extends InstallArgs {
11178        private File codeFile;
11179        private File resourceFile;
11180
11181        // Example topology:
11182        // /data/app/com.example/base.apk
11183        // /data/app/com.example/split_foo.apk
11184        // /data/app/com.example/lib/arm/libfoo.so
11185        // /data/app/com.example/lib/arm64/libfoo.so
11186        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11187
11188        /** New install */
11189        FileInstallArgs(InstallParams params) {
11190            super(params.origin, params.move, params.observer, params.installFlags,
11191                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11192                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11193                    params.grantedRuntimePermissions,
11194                    params.traceMethod, params.traceCookie);
11195            if (isFwdLocked()) {
11196                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11197            }
11198        }
11199
11200        /** Existing install */
11201        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11202            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11203                    null, null, null, 0);
11204            this.codeFile = (codePath != null) ? new File(codePath) : null;
11205            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11206        }
11207
11208        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11209            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11210            try {
11211                return doCopyApk(imcs, temp);
11212            } finally {
11213                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11214            }
11215        }
11216
11217        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11218            if (origin.staged) {
11219                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11220                codeFile = origin.file;
11221                resourceFile = origin.file;
11222                return PackageManager.INSTALL_SUCCEEDED;
11223            }
11224
11225            try {
11226                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11227                codeFile = tempDir;
11228                resourceFile = tempDir;
11229            } catch (IOException e) {
11230                Slog.w(TAG, "Failed to create copy file: " + e);
11231                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11232            }
11233
11234            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11235                @Override
11236                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11237                    if (!FileUtils.isValidExtFilename(name)) {
11238                        throw new IllegalArgumentException("Invalid filename: " + name);
11239                    }
11240                    try {
11241                        final File file = new File(codeFile, name);
11242                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11243                                O_RDWR | O_CREAT, 0644);
11244                        Os.chmod(file.getAbsolutePath(), 0644);
11245                        return new ParcelFileDescriptor(fd);
11246                    } catch (ErrnoException e) {
11247                        throw new RemoteException("Failed to open: " + e.getMessage());
11248                    }
11249                }
11250            };
11251
11252            int ret = PackageManager.INSTALL_SUCCEEDED;
11253            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11254            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11255                Slog.e(TAG, "Failed to copy package");
11256                return ret;
11257            }
11258
11259            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11260            NativeLibraryHelper.Handle handle = null;
11261            try {
11262                handle = NativeLibraryHelper.Handle.create(codeFile);
11263                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11264                        abiOverride);
11265            } catch (IOException e) {
11266                Slog.e(TAG, "Copying native libraries failed", e);
11267                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11268            } finally {
11269                IoUtils.closeQuietly(handle);
11270            }
11271
11272            return ret;
11273        }
11274
11275        int doPreInstall(int status) {
11276            if (status != PackageManager.INSTALL_SUCCEEDED) {
11277                cleanUp();
11278            }
11279            return status;
11280        }
11281
11282        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11283            if (status != PackageManager.INSTALL_SUCCEEDED) {
11284                cleanUp();
11285                return false;
11286            }
11287
11288            final File targetDir = codeFile.getParentFile();
11289            final File beforeCodeFile = codeFile;
11290            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11291
11292            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11293            try {
11294                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11295            } catch (ErrnoException e) {
11296                Slog.w(TAG, "Failed to rename", e);
11297                return false;
11298            }
11299
11300            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11301                Slog.w(TAG, "Failed to restorecon");
11302                return false;
11303            }
11304
11305            // Reflect the rename internally
11306            codeFile = afterCodeFile;
11307            resourceFile = afterCodeFile;
11308
11309            // Reflect the rename in scanned details
11310            pkg.codePath = afterCodeFile.getAbsolutePath();
11311            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11312                    pkg.baseCodePath);
11313            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11314                    pkg.splitCodePaths);
11315
11316            // Reflect the rename in app info
11317            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11318            pkg.applicationInfo.setCodePath(pkg.codePath);
11319            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11320            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11321            pkg.applicationInfo.setResourcePath(pkg.codePath);
11322            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11323            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11324
11325            return true;
11326        }
11327
11328        int doPostInstall(int status, int uid) {
11329            if (status != PackageManager.INSTALL_SUCCEEDED) {
11330                cleanUp();
11331            }
11332            return status;
11333        }
11334
11335        @Override
11336        String getCodePath() {
11337            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11338        }
11339
11340        @Override
11341        String getResourcePath() {
11342            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11343        }
11344
11345        private boolean cleanUp() {
11346            if (codeFile == null || !codeFile.exists()) {
11347                return false;
11348            }
11349
11350            if (codeFile.isDirectory()) {
11351                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11352            } else {
11353                codeFile.delete();
11354            }
11355
11356            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11357                resourceFile.delete();
11358            }
11359
11360            return true;
11361        }
11362
11363        void cleanUpResourcesLI() {
11364            // Try enumerating all code paths before deleting
11365            List<String> allCodePaths = Collections.EMPTY_LIST;
11366            if (codeFile != null && codeFile.exists()) {
11367                try {
11368                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11369                    allCodePaths = pkg.getAllCodePaths();
11370                } catch (PackageParserException e) {
11371                    // Ignored; we tried our best
11372                }
11373            }
11374
11375            cleanUp();
11376            removeDexFiles(allCodePaths, instructionSets);
11377        }
11378
11379        boolean doPostDeleteLI(boolean delete) {
11380            // XXX err, shouldn't we respect the delete flag?
11381            cleanUpResourcesLI();
11382            return true;
11383        }
11384    }
11385
11386    private boolean isAsecExternal(String cid) {
11387        final String asecPath = PackageHelper.getSdFilesystem(cid);
11388        return !asecPath.startsWith(mAsecInternalPath);
11389    }
11390
11391    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11392            PackageManagerException {
11393        if (copyRet < 0) {
11394            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11395                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11396                throw new PackageManagerException(copyRet, message);
11397            }
11398        }
11399    }
11400
11401    /**
11402     * Extract the MountService "container ID" from the full code path of an
11403     * .apk.
11404     */
11405    static String cidFromCodePath(String fullCodePath) {
11406        int eidx = fullCodePath.lastIndexOf("/");
11407        String subStr1 = fullCodePath.substring(0, eidx);
11408        int sidx = subStr1.lastIndexOf("/");
11409        return subStr1.substring(sidx+1, eidx);
11410    }
11411
11412    /**
11413     * Logic to handle installation of ASEC applications, including copying and
11414     * renaming logic.
11415     */
11416    class AsecInstallArgs extends InstallArgs {
11417        static final String RES_FILE_NAME = "pkg.apk";
11418        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11419
11420        String cid;
11421        String packagePath;
11422        String resourcePath;
11423
11424        /** New install */
11425        AsecInstallArgs(InstallParams params) {
11426            super(params.origin, params.move, params.observer, params.installFlags,
11427                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11428                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11429                    params.grantedRuntimePermissions,
11430                    params.traceMethod, params.traceCookie);
11431        }
11432
11433        /** Existing install */
11434        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11435                        boolean isExternal, boolean isForwardLocked) {
11436            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11437                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11438                    instructionSets, null, null, null, 0);
11439            // Hackily pretend we're still looking at a full code path
11440            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11441                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11442            }
11443
11444            // Extract cid from fullCodePath
11445            int eidx = fullCodePath.lastIndexOf("/");
11446            String subStr1 = fullCodePath.substring(0, eidx);
11447            int sidx = subStr1.lastIndexOf("/");
11448            cid = subStr1.substring(sidx+1, eidx);
11449            setMountPath(subStr1);
11450        }
11451
11452        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11453            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11454                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11455                    instructionSets, null, null, null, 0);
11456            this.cid = cid;
11457            setMountPath(PackageHelper.getSdDir(cid));
11458        }
11459
11460        void createCopyFile() {
11461            cid = mInstallerService.allocateExternalStageCidLegacy();
11462        }
11463
11464        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11465            if (origin.staged) {
11466                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11467                cid = origin.cid;
11468                setMountPath(PackageHelper.getSdDir(cid));
11469                return PackageManager.INSTALL_SUCCEEDED;
11470            }
11471
11472            if (temp) {
11473                createCopyFile();
11474            } else {
11475                /*
11476                 * Pre-emptively destroy the container since it's destroyed if
11477                 * copying fails due to it existing anyway.
11478                 */
11479                PackageHelper.destroySdDir(cid);
11480            }
11481
11482            final String newMountPath = imcs.copyPackageToContainer(
11483                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11484                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11485
11486            if (newMountPath != null) {
11487                setMountPath(newMountPath);
11488                return PackageManager.INSTALL_SUCCEEDED;
11489            } else {
11490                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11491            }
11492        }
11493
11494        @Override
11495        String getCodePath() {
11496            return packagePath;
11497        }
11498
11499        @Override
11500        String getResourcePath() {
11501            return resourcePath;
11502        }
11503
11504        int doPreInstall(int status) {
11505            if (status != PackageManager.INSTALL_SUCCEEDED) {
11506                // Destroy container
11507                PackageHelper.destroySdDir(cid);
11508            } else {
11509                boolean mounted = PackageHelper.isContainerMounted(cid);
11510                if (!mounted) {
11511                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11512                            Process.SYSTEM_UID);
11513                    if (newMountPath != null) {
11514                        setMountPath(newMountPath);
11515                    } else {
11516                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11517                    }
11518                }
11519            }
11520            return status;
11521        }
11522
11523        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11524            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11525            String newMountPath = null;
11526            if (PackageHelper.isContainerMounted(cid)) {
11527                // Unmount the container
11528                if (!PackageHelper.unMountSdDir(cid)) {
11529                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11530                    return false;
11531                }
11532            }
11533            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11534                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11535                        " which might be stale. Will try to clean up.");
11536                // Clean up the stale container and proceed to recreate.
11537                if (!PackageHelper.destroySdDir(newCacheId)) {
11538                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11539                    return false;
11540                }
11541                // Successfully cleaned up stale container. Try to rename again.
11542                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11543                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11544                            + " inspite of cleaning it up.");
11545                    return false;
11546                }
11547            }
11548            if (!PackageHelper.isContainerMounted(newCacheId)) {
11549                Slog.w(TAG, "Mounting container " + newCacheId);
11550                newMountPath = PackageHelper.mountSdDir(newCacheId,
11551                        getEncryptKey(), Process.SYSTEM_UID);
11552            } else {
11553                newMountPath = PackageHelper.getSdDir(newCacheId);
11554            }
11555            if (newMountPath == null) {
11556                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11557                return false;
11558            }
11559            Log.i(TAG, "Succesfully renamed " + cid +
11560                    " to " + newCacheId +
11561                    " at new path: " + newMountPath);
11562            cid = newCacheId;
11563
11564            final File beforeCodeFile = new File(packagePath);
11565            setMountPath(newMountPath);
11566            final File afterCodeFile = new File(packagePath);
11567
11568            // Reflect the rename in scanned details
11569            pkg.codePath = afterCodeFile.getAbsolutePath();
11570            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11571                    pkg.baseCodePath);
11572            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11573                    pkg.splitCodePaths);
11574
11575            // Reflect the rename in app info
11576            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11577            pkg.applicationInfo.setCodePath(pkg.codePath);
11578            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11579            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11580            pkg.applicationInfo.setResourcePath(pkg.codePath);
11581            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11582            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11583
11584            return true;
11585        }
11586
11587        private void setMountPath(String mountPath) {
11588            final File mountFile = new File(mountPath);
11589
11590            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11591            if (monolithicFile.exists()) {
11592                packagePath = monolithicFile.getAbsolutePath();
11593                if (isFwdLocked()) {
11594                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11595                } else {
11596                    resourcePath = packagePath;
11597                }
11598            } else {
11599                packagePath = mountFile.getAbsolutePath();
11600                resourcePath = packagePath;
11601            }
11602        }
11603
11604        int doPostInstall(int status, int uid) {
11605            if (status != PackageManager.INSTALL_SUCCEEDED) {
11606                cleanUp();
11607            } else {
11608                final int groupOwner;
11609                final String protectedFile;
11610                if (isFwdLocked()) {
11611                    groupOwner = UserHandle.getSharedAppGid(uid);
11612                    protectedFile = RES_FILE_NAME;
11613                } else {
11614                    groupOwner = -1;
11615                    protectedFile = null;
11616                }
11617
11618                if (uid < Process.FIRST_APPLICATION_UID
11619                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11620                    Slog.e(TAG, "Failed to finalize " + cid);
11621                    PackageHelper.destroySdDir(cid);
11622                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11623                }
11624
11625                boolean mounted = PackageHelper.isContainerMounted(cid);
11626                if (!mounted) {
11627                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11628                }
11629            }
11630            return status;
11631        }
11632
11633        private void cleanUp() {
11634            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11635
11636            // Destroy secure container
11637            PackageHelper.destroySdDir(cid);
11638        }
11639
11640        private List<String> getAllCodePaths() {
11641            final File codeFile = new File(getCodePath());
11642            if (codeFile != null && codeFile.exists()) {
11643                try {
11644                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11645                    return pkg.getAllCodePaths();
11646                } catch (PackageParserException e) {
11647                    // Ignored; we tried our best
11648                }
11649            }
11650            return Collections.EMPTY_LIST;
11651        }
11652
11653        void cleanUpResourcesLI() {
11654            // Enumerate all code paths before deleting
11655            cleanUpResourcesLI(getAllCodePaths());
11656        }
11657
11658        private void cleanUpResourcesLI(List<String> allCodePaths) {
11659            cleanUp();
11660            removeDexFiles(allCodePaths, instructionSets);
11661        }
11662
11663        String getPackageName() {
11664            return getAsecPackageName(cid);
11665        }
11666
11667        boolean doPostDeleteLI(boolean delete) {
11668            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11669            final List<String> allCodePaths = getAllCodePaths();
11670            boolean mounted = PackageHelper.isContainerMounted(cid);
11671            if (mounted) {
11672                // Unmount first
11673                if (PackageHelper.unMountSdDir(cid)) {
11674                    mounted = false;
11675                }
11676            }
11677            if (!mounted && delete) {
11678                cleanUpResourcesLI(allCodePaths);
11679            }
11680            return !mounted;
11681        }
11682
11683        @Override
11684        int doPreCopy() {
11685            if (isFwdLocked()) {
11686                if (!PackageHelper.fixSdPermissions(cid,
11687                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11688                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11689                }
11690            }
11691
11692            return PackageManager.INSTALL_SUCCEEDED;
11693        }
11694
11695        @Override
11696        int doPostCopy(int uid) {
11697            if (isFwdLocked()) {
11698                if (uid < Process.FIRST_APPLICATION_UID
11699                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11700                                RES_FILE_NAME)) {
11701                    Slog.e(TAG, "Failed to finalize " + cid);
11702                    PackageHelper.destroySdDir(cid);
11703                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11704                }
11705            }
11706
11707            return PackageManager.INSTALL_SUCCEEDED;
11708        }
11709    }
11710
11711    /**
11712     * Logic to handle movement of existing installed applications.
11713     */
11714    class MoveInstallArgs extends InstallArgs {
11715        private File codeFile;
11716        private File resourceFile;
11717
11718        /** New install */
11719        MoveInstallArgs(InstallParams params) {
11720            super(params.origin, params.move, params.observer, params.installFlags,
11721                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11722                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11723                    params.grantedRuntimePermissions,
11724                    params.traceMethod, params.traceCookie);
11725        }
11726
11727        int copyApk(IMediaContainerService imcs, boolean temp) {
11728            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11729                    + move.fromUuid + " to " + move.toUuid);
11730            synchronized (mInstaller) {
11731                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11732                        move.dataAppName, move.appId, move.seinfo) != 0) {
11733                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11734                }
11735            }
11736
11737            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11738            resourceFile = codeFile;
11739            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11740
11741            return PackageManager.INSTALL_SUCCEEDED;
11742        }
11743
11744        int doPreInstall(int status) {
11745            if (status != PackageManager.INSTALL_SUCCEEDED) {
11746                cleanUp(move.toUuid);
11747            }
11748            return status;
11749        }
11750
11751        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11752            if (status != PackageManager.INSTALL_SUCCEEDED) {
11753                cleanUp(move.toUuid);
11754                return false;
11755            }
11756
11757            // Reflect the move in app info
11758            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11759            pkg.applicationInfo.setCodePath(pkg.codePath);
11760            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11761            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11762            pkg.applicationInfo.setResourcePath(pkg.codePath);
11763            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11764            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11765
11766            return true;
11767        }
11768
11769        int doPostInstall(int status, int uid) {
11770            if (status == PackageManager.INSTALL_SUCCEEDED) {
11771                cleanUp(move.fromUuid);
11772            } else {
11773                cleanUp(move.toUuid);
11774            }
11775            return status;
11776        }
11777
11778        @Override
11779        String getCodePath() {
11780            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11781        }
11782
11783        @Override
11784        String getResourcePath() {
11785            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11786        }
11787
11788        private boolean cleanUp(String volumeUuid) {
11789            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11790                    move.dataAppName);
11791            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11792            synchronized (mInstallLock) {
11793                // Clean up both app data and code
11794                removeDataDirsLI(volumeUuid, move.packageName);
11795                if (codeFile.isDirectory()) {
11796                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11797                } else {
11798                    codeFile.delete();
11799                }
11800            }
11801            return true;
11802        }
11803
11804        void cleanUpResourcesLI() {
11805            throw new UnsupportedOperationException();
11806        }
11807
11808        boolean doPostDeleteLI(boolean delete) {
11809            throw new UnsupportedOperationException();
11810        }
11811    }
11812
11813    static String getAsecPackageName(String packageCid) {
11814        int idx = packageCid.lastIndexOf("-");
11815        if (idx == -1) {
11816            return packageCid;
11817        }
11818        return packageCid.substring(0, idx);
11819    }
11820
11821    // Utility method used to create code paths based on package name and available index.
11822    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11823        String idxStr = "";
11824        int idx = 1;
11825        // Fall back to default value of idx=1 if prefix is not
11826        // part of oldCodePath
11827        if (oldCodePath != null) {
11828            String subStr = oldCodePath;
11829            // Drop the suffix right away
11830            if (suffix != null && subStr.endsWith(suffix)) {
11831                subStr = subStr.substring(0, subStr.length() - suffix.length());
11832            }
11833            // If oldCodePath already contains prefix find out the
11834            // ending index to either increment or decrement.
11835            int sidx = subStr.lastIndexOf(prefix);
11836            if (sidx != -1) {
11837                subStr = subStr.substring(sidx + prefix.length());
11838                if (subStr != null) {
11839                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11840                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11841                    }
11842                    try {
11843                        idx = Integer.parseInt(subStr);
11844                        if (idx <= 1) {
11845                            idx++;
11846                        } else {
11847                            idx--;
11848                        }
11849                    } catch(NumberFormatException e) {
11850                    }
11851                }
11852            }
11853        }
11854        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11855        return prefix + idxStr;
11856    }
11857
11858    private File getNextCodePath(File targetDir, String packageName) {
11859        int suffix = 1;
11860        File result;
11861        do {
11862            result = new File(targetDir, packageName + "-" + suffix);
11863            suffix++;
11864        } while (result.exists());
11865        return result;
11866    }
11867
11868    // Utility method that returns the relative package path with respect
11869    // to the installation directory. Like say for /data/data/com.test-1.apk
11870    // string com.test-1 is returned.
11871    static String deriveCodePathName(String codePath) {
11872        if (codePath == null) {
11873            return null;
11874        }
11875        final File codeFile = new File(codePath);
11876        final String name = codeFile.getName();
11877        if (codeFile.isDirectory()) {
11878            return name;
11879        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11880            final int lastDot = name.lastIndexOf('.');
11881            return name.substring(0, lastDot);
11882        } else {
11883            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11884            return null;
11885        }
11886    }
11887
11888    class PackageInstalledInfo {
11889        String name;
11890        int uid;
11891        // The set of users that originally had this package installed.
11892        int[] origUsers;
11893        // The set of users that now have this package installed.
11894        int[] newUsers;
11895        PackageParser.Package pkg;
11896        int returnCode;
11897        String returnMsg;
11898        PackageRemovedInfo removedInfo;
11899
11900        public void setError(int code, String msg) {
11901            returnCode = code;
11902            returnMsg = msg;
11903            Slog.w(TAG, msg);
11904        }
11905
11906        public void setError(String msg, PackageParserException e) {
11907            returnCode = e.error;
11908            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11909            Slog.w(TAG, msg, e);
11910        }
11911
11912        public void setError(String msg, PackageManagerException e) {
11913            returnCode = e.error;
11914            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11915            Slog.w(TAG, msg, e);
11916        }
11917
11918        // In some error cases we want to convey more info back to the observer
11919        String origPackage;
11920        String origPermission;
11921    }
11922
11923    /*
11924     * Install a non-existing package.
11925     */
11926    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11927            UserHandle user, String installerPackageName, String volumeUuid,
11928            PackageInstalledInfo res) {
11929        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
11930
11931        // Remember this for later, in case we need to rollback this install
11932        String pkgName = pkg.packageName;
11933
11934        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11935        // TODO: b/23350563
11936        final boolean dataDirExists = Environment
11937                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
11938
11939        synchronized(mPackages) {
11940            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11941                // A package with the same name is already installed, though
11942                // it has been renamed to an older name.  The package we
11943                // are trying to install should be installed as an update to
11944                // the existing one, but that has not been requested, so bail.
11945                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11946                        + " without first uninstalling package running as "
11947                        + mSettings.mRenamedPackages.get(pkgName));
11948                return;
11949            }
11950            if (mPackages.containsKey(pkgName)) {
11951                // Don't allow installation over an existing package with the same name.
11952                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11953                        + " without first uninstalling.");
11954                return;
11955            }
11956        }
11957
11958        try {
11959            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
11960                    System.currentTimeMillis(), user);
11961
11962            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11963            // delete the partially installed application. the data directory will have to be
11964            // restored if it was already existing
11965            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11966                // remove package from internal structures.  Note that we want deletePackageX to
11967                // delete the package data and cache directories that it created in
11968                // scanPackageLocked, unless those directories existed before we even tried to
11969                // install.
11970                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11971                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11972                                res.removedInfo, true);
11973            }
11974
11975        } catch (PackageManagerException e) {
11976            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11977        }
11978
11979        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11980    }
11981
11982    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11983        // Can't rotate keys during boot or if sharedUser.
11984        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11985                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11986            return false;
11987        }
11988        // app is using upgradeKeySets; make sure all are valid
11989        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11990        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11991        for (int i = 0; i < upgradeKeySets.length; i++) {
11992            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11993                Slog.wtf(TAG, "Package "
11994                         + (oldPs.name != null ? oldPs.name : "<null>")
11995                         + " contains upgrade-key-set reference to unknown key-set: "
11996                         + upgradeKeySets[i]
11997                         + " reverting to signatures check.");
11998                return false;
11999            }
12000        }
12001        return true;
12002    }
12003
12004    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12005        // Upgrade keysets are being used.  Determine if new package has a superset of the
12006        // required keys.
12007        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12008        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12009        for (int i = 0; i < upgradeKeySets.length; i++) {
12010            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12011            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12012                return true;
12013            }
12014        }
12015        return false;
12016    }
12017
12018    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12019            UserHandle user, String installerPackageName, String volumeUuid,
12020            PackageInstalledInfo res) {
12021        final PackageParser.Package oldPackage;
12022        final String pkgName = pkg.packageName;
12023        final int[] allUsers;
12024        final boolean[] perUserInstalled;
12025
12026        // First find the old package info and check signatures
12027        synchronized(mPackages) {
12028            oldPackage = mPackages.get(pkgName);
12029            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12030            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12031            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12032                if(!checkUpgradeKeySetLP(ps, pkg)) {
12033                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12034                            "New package not signed by keys specified by upgrade-keysets: "
12035                            + pkgName);
12036                    return;
12037                }
12038            } else {
12039                // default to original signature matching
12040                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12041                    != PackageManager.SIGNATURE_MATCH) {
12042                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12043                            "New package has a different signature: " + pkgName);
12044                    return;
12045                }
12046            }
12047
12048            // In case of rollback, remember per-user/profile install state
12049            allUsers = sUserManager.getUserIds();
12050            perUserInstalled = new boolean[allUsers.length];
12051            for (int i = 0; i < allUsers.length; i++) {
12052                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12053            }
12054        }
12055
12056        boolean sysPkg = (isSystemApp(oldPackage));
12057        if (sysPkg) {
12058            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12059                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12060        } else {
12061            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12062                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12063        }
12064    }
12065
12066    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12067            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12068            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12069            String volumeUuid, PackageInstalledInfo res) {
12070        String pkgName = deletedPackage.packageName;
12071        boolean deletedPkg = true;
12072        boolean updatedSettings = false;
12073
12074        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12075                + deletedPackage);
12076        long origUpdateTime;
12077        if (pkg.mExtras != null) {
12078            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12079        } else {
12080            origUpdateTime = 0;
12081        }
12082
12083        // First delete the existing package while retaining the data directory
12084        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12085                res.removedInfo, true)) {
12086            // If the existing package wasn't successfully deleted
12087            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12088            deletedPkg = false;
12089        } else {
12090            // Successfully deleted the old package; proceed with replace.
12091
12092            // If deleted package lived in a container, give users a chance to
12093            // relinquish resources before killing.
12094            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12095                if (DEBUG_INSTALL) {
12096                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12097                }
12098                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12099                final ArrayList<String> pkgList = new ArrayList<String>(1);
12100                pkgList.add(deletedPackage.applicationInfo.packageName);
12101                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12102            }
12103
12104            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12105            try {
12106                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12107                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12108                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12109                        perUserInstalled, res, user);
12110                updatedSettings = true;
12111            } catch (PackageManagerException e) {
12112                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12113            }
12114        }
12115
12116        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12117            // remove package from internal structures.  Note that we want deletePackageX to
12118            // delete the package data and cache directories that it created in
12119            // scanPackageLocked, unless those directories existed before we even tried to
12120            // install.
12121            if(updatedSettings) {
12122                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12123                deletePackageLI(
12124                        pkgName, null, true, allUsers, perUserInstalled,
12125                        PackageManager.DELETE_KEEP_DATA,
12126                                res.removedInfo, true);
12127            }
12128            // Since we failed to install the new package we need to restore the old
12129            // package that we deleted.
12130            if (deletedPkg) {
12131                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12132                File restoreFile = new File(deletedPackage.codePath);
12133                // Parse old package
12134                boolean oldExternal = isExternal(deletedPackage);
12135                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12136                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12137                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12138                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12139                try {
12140                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
12141                } catch (PackageManagerException e) {
12142                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12143                            + e.getMessage());
12144                    return;
12145                }
12146                // Restore of old package succeeded. Update permissions.
12147                // writer
12148                synchronized (mPackages) {
12149                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12150                            UPDATE_PERMISSIONS_ALL);
12151                    // can downgrade to reader
12152                    mSettings.writeLPr();
12153                }
12154                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12155            }
12156        }
12157    }
12158
12159    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12160            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12161            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12162            String volumeUuid, PackageInstalledInfo res) {
12163        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12164                + ", old=" + deletedPackage);
12165        boolean disabledSystem = false;
12166        boolean updatedSettings = false;
12167        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12168        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12169                != 0) {
12170            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12171        }
12172        String packageName = deletedPackage.packageName;
12173        if (packageName == null) {
12174            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12175                    "Attempt to delete null packageName.");
12176            return;
12177        }
12178        PackageParser.Package oldPkg;
12179        PackageSetting oldPkgSetting;
12180        // reader
12181        synchronized (mPackages) {
12182            oldPkg = mPackages.get(packageName);
12183            oldPkgSetting = mSettings.mPackages.get(packageName);
12184            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12185                    (oldPkgSetting == null)) {
12186                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12187                        "Couldn't find package:" + packageName + " information");
12188                return;
12189            }
12190        }
12191
12192        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12193
12194        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12195        res.removedInfo.removedPackage = packageName;
12196        // Remove existing system package
12197        removePackageLI(oldPkgSetting, true);
12198        // writer
12199        synchronized (mPackages) {
12200            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12201            if (!disabledSystem && deletedPackage != null) {
12202                // We didn't need to disable the .apk as a current system package,
12203                // which means we are replacing another update that is already
12204                // installed.  We need to make sure to delete the older one's .apk.
12205                res.removedInfo.args = createInstallArgsForExisting(0,
12206                        deletedPackage.applicationInfo.getCodePath(),
12207                        deletedPackage.applicationInfo.getResourcePath(),
12208                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12209            } else {
12210                res.removedInfo.args = null;
12211            }
12212        }
12213
12214        // Successfully disabled the old package. Now proceed with re-installation
12215        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12216
12217        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12218        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12219
12220        PackageParser.Package newPackage = null;
12221        try {
12222            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12223            if (newPackage.mExtras != null) {
12224                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12225                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12226                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12227
12228                // is the update attempting to change shared user? that isn't going to work...
12229                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12230                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12231                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12232                            + " to " + newPkgSetting.sharedUser);
12233                    updatedSettings = true;
12234                }
12235            }
12236
12237            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12238                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12239                        perUserInstalled, res, user);
12240                updatedSettings = true;
12241            }
12242
12243        } catch (PackageManagerException e) {
12244            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12245        }
12246
12247        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12248            // Re installation failed. Restore old information
12249            // Remove new pkg information
12250            if (newPackage != null) {
12251                removeInstalledPackageLI(newPackage, true);
12252            }
12253            // Add back the old system package
12254            try {
12255                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12256            } catch (PackageManagerException e) {
12257                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12258            }
12259            // Restore the old system information in Settings
12260            synchronized (mPackages) {
12261                if (disabledSystem) {
12262                    mSettings.enableSystemPackageLPw(packageName);
12263                }
12264                if (updatedSettings) {
12265                    mSettings.setInstallerPackageName(packageName,
12266                            oldPkgSetting.installerPackageName);
12267                }
12268                mSettings.writeLPr();
12269            }
12270        }
12271    }
12272
12273    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12274            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12275            UserHandle user) {
12276        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12277
12278        String pkgName = newPackage.packageName;
12279        synchronized (mPackages) {
12280            //write settings. the installStatus will be incomplete at this stage.
12281            //note that the new package setting would have already been
12282            //added to mPackages. It hasn't been persisted yet.
12283            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12284            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12285            mSettings.writeLPr();
12286            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12287        }
12288
12289        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12290        synchronized (mPackages) {
12291            updatePermissionsLPw(newPackage.packageName, newPackage,
12292                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12293                            ? UPDATE_PERMISSIONS_ALL : 0));
12294            // For system-bundled packages, we assume that installing an upgraded version
12295            // of the package implies that the user actually wants to run that new code,
12296            // so we enable the package.
12297            PackageSetting ps = mSettings.mPackages.get(pkgName);
12298            if (ps != null) {
12299                if (isSystemApp(newPackage)) {
12300                    // NB: implicit assumption that system package upgrades apply to all users
12301                    if (DEBUG_INSTALL) {
12302                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12303                    }
12304                    if (res.origUsers != null) {
12305                        for (int userHandle : res.origUsers) {
12306                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12307                                    userHandle, installerPackageName);
12308                        }
12309                    }
12310                    // Also convey the prior install/uninstall state
12311                    if (allUsers != null && perUserInstalled != null) {
12312                        for (int i = 0; i < allUsers.length; i++) {
12313                            if (DEBUG_INSTALL) {
12314                                Slog.d(TAG, "    user " + allUsers[i]
12315                                        + " => " + perUserInstalled[i]);
12316                            }
12317                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12318                        }
12319                        // these install state changes will be persisted in the
12320                        // upcoming call to mSettings.writeLPr().
12321                    }
12322                }
12323                // It's implied that when a user requests installation, they want the app to be
12324                // installed and enabled.
12325                int userId = user.getIdentifier();
12326                if (userId != UserHandle.USER_ALL) {
12327                    ps.setInstalled(true, userId);
12328                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12329                }
12330            }
12331            res.name = pkgName;
12332            res.uid = newPackage.applicationInfo.uid;
12333            res.pkg = newPackage;
12334            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12335            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12336            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12337            //to update install status
12338            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12339            mSettings.writeLPr();
12340            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12341        }
12342
12343        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12344    }
12345
12346    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12347        try {
12348            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12349            installPackageLI(args, res);
12350        } finally {
12351            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12352        }
12353    }
12354
12355    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12356        final int installFlags = args.installFlags;
12357        final String installerPackageName = args.installerPackageName;
12358        final String volumeUuid = args.volumeUuid;
12359        final File tmpPackageFile = new File(args.getCodePath());
12360        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12361        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12362                || (args.volumeUuid != null));
12363        boolean replace = false;
12364        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12365        if (args.move != null) {
12366            // moving a complete application; perfom an initial scan on the new install location
12367            scanFlags |= SCAN_INITIAL;
12368        }
12369        // Result object to be returned
12370        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12371
12372        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12373
12374        // Retrieve PackageSettings and parse package
12375        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12376                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12377                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12378        PackageParser pp = new PackageParser();
12379        pp.setSeparateProcesses(mSeparateProcesses);
12380        pp.setDisplayMetrics(mMetrics);
12381
12382        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12383        final PackageParser.Package pkg;
12384        try {
12385            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12386        } catch (PackageParserException e) {
12387            res.setError("Failed parse during installPackageLI", e);
12388            return;
12389        } finally {
12390            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12391        }
12392
12393        // Mark that we have an install time CPU ABI override.
12394        pkg.cpuAbiOverride = args.abiOverride;
12395
12396        String pkgName = res.name = pkg.packageName;
12397        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12398            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12399                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12400                return;
12401            }
12402        }
12403
12404        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12405        try {
12406            pp.collectCertificates(pkg, parseFlags);
12407            pp.collectManifestDigest(pkg);
12408        } catch (PackageParserException e) {
12409            res.setError("Failed collect during installPackageLI", e);
12410            return;
12411        } finally {
12412            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12413        }
12414
12415        /* If the installer passed in a manifest digest, compare it now. */
12416        if (args.manifestDigest != null) {
12417            if (DEBUG_INSTALL) {
12418                final String parsedManifest = pkg.manifestDigest == null ? "null"
12419                        : pkg.manifestDigest.toString();
12420                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12421                        + parsedManifest);
12422            }
12423
12424            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12425                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12426                return;
12427            }
12428        } else if (DEBUG_INSTALL) {
12429            final String parsedManifest = pkg.manifestDigest == null
12430                    ? "null" : pkg.manifestDigest.toString();
12431            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12432        }
12433
12434        // Get rid of all references to package scan path via parser.
12435        pp = null;
12436        String oldCodePath = null;
12437        boolean systemApp = false;
12438        synchronized (mPackages) {
12439            // Check if installing already existing package
12440            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12441                String oldName = mSettings.mRenamedPackages.get(pkgName);
12442                if (pkg.mOriginalPackages != null
12443                        && pkg.mOriginalPackages.contains(oldName)
12444                        && mPackages.containsKey(oldName)) {
12445                    // This package is derived from an original package,
12446                    // and this device has been updating from that original
12447                    // name.  We must continue using the original name, so
12448                    // rename the new package here.
12449                    pkg.setPackageName(oldName);
12450                    pkgName = pkg.packageName;
12451                    replace = true;
12452                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12453                            + oldName + " pkgName=" + pkgName);
12454                } else if (mPackages.containsKey(pkgName)) {
12455                    // This package, under its official name, already exists
12456                    // on the device; we should replace it.
12457                    replace = true;
12458                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12459                }
12460
12461                // Prevent apps opting out from runtime permissions
12462                if (replace) {
12463                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12464                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12465                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12466                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12467                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12468                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12469                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12470                                        + " doesn't support runtime permissions but the old"
12471                                        + " target SDK " + oldTargetSdk + " does.");
12472                        return;
12473                    }
12474                }
12475            }
12476
12477            PackageSetting ps = mSettings.mPackages.get(pkgName);
12478            if (ps != null) {
12479                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12480
12481                // Quick sanity check that we're signed correctly if updating;
12482                // we'll check this again later when scanning, but we want to
12483                // bail early here before tripping over redefined permissions.
12484                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12485                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12486                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12487                                + pkg.packageName + " upgrade keys do not match the "
12488                                + "previously installed version");
12489                        return;
12490                    }
12491                } else {
12492                    try {
12493                        verifySignaturesLP(ps, pkg);
12494                    } catch (PackageManagerException e) {
12495                        res.setError(e.error, e.getMessage());
12496                        return;
12497                    }
12498                }
12499
12500                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12501                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12502                    systemApp = (ps.pkg.applicationInfo.flags &
12503                            ApplicationInfo.FLAG_SYSTEM) != 0;
12504                }
12505                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12506            }
12507
12508            // Check whether the newly-scanned package wants to define an already-defined perm
12509            int N = pkg.permissions.size();
12510            for (int i = N-1; i >= 0; i--) {
12511                PackageParser.Permission perm = pkg.permissions.get(i);
12512                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12513                if (bp != null) {
12514                    // If the defining package is signed with our cert, it's okay.  This
12515                    // also includes the "updating the same package" case, of course.
12516                    // "updating same package" could also involve key-rotation.
12517                    final boolean sigsOk;
12518                    if (bp.sourcePackage.equals(pkg.packageName)
12519                            && (bp.packageSetting instanceof PackageSetting)
12520                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12521                                    scanFlags))) {
12522                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12523                    } else {
12524                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12525                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12526                    }
12527                    if (!sigsOk) {
12528                        // If the owning package is the system itself, we log but allow
12529                        // install to proceed; we fail the install on all other permission
12530                        // redefinitions.
12531                        if (!bp.sourcePackage.equals("android")) {
12532                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12533                                    + pkg.packageName + " attempting to redeclare permission "
12534                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12535                            res.origPermission = perm.info.name;
12536                            res.origPackage = bp.sourcePackage;
12537                            return;
12538                        } else {
12539                            Slog.w(TAG, "Package " + pkg.packageName
12540                                    + " attempting to redeclare system permission "
12541                                    + perm.info.name + "; ignoring new declaration");
12542                            pkg.permissions.remove(i);
12543                        }
12544                    }
12545                }
12546            }
12547
12548        }
12549
12550        if (systemApp && onExternal) {
12551            // Disable updates to system apps on sdcard
12552            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12553                    "Cannot install updates to system apps on sdcard");
12554            return;
12555        }
12556
12557        if (args.move != null) {
12558            // We did an in-place move, so dex is ready to roll
12559            scanFlags |= SCAN_NO_DEX;
12560            scanFlags |= SCAN_MOVE;
12561
12562            synchronized (mPackages) {
12563                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12564                if (ps == null) {
12565                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12566                            "Missing settings for moved package " + pkgName);
12567                }
12568
12569                // We moved the entire application as-is, so bring over the
12570                // previously derived ABI information.
12571                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12572                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12573            }
12574
12575        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12576            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12577            scanFlags |= SCAN_NO_DEX;
12578
12579            try {
12580                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12581                        true /* extract libs */);
12582            } catch (PackageManagerException pme) {
12583                Slog.e(TAG, "Error deriving application ABI", pme);
12584                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12585                return;
12586            }
12587
12588            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12589            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
12590
12591            int result = mPackageDexOptimizer
12592                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12593                            false /* defer */, false /* inclDependencies */);
12594
12595            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12596            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12597                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12598                return;
12599            }
12600        }
12601
12602        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12603            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12604            return;
12605        }
12606
12607        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12608
12609        if (replace) {
12610            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12611                    installerPackageName, volumeUuid, res);
12612        } else {
12613            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12614                    args.user, installerPackageName, volumeUuid, res);
12615        }
12616        synchronized (mPackages) {
12617            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12618            if (ps != null) {
12619                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12620            }
12621        }
12622    }
12623
12624    private void startIntentFilterVerifications(int userId, boolean replacing,
12625            PackageParser.Package pkg) {
12626        if (mIntentFilterVerifierComponent == null) {
12627            Slog.w(TAG, "No IntentFilter verification will not be done as "
12628                    + "there is no IntentFilterVerifier available!");
12629            return;
12630        }
12631
12632        final int verifierUid = getPackageUid(
12633                mIntentFilterVerifierComponent.getPackageName(),
12634                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12635
12636        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12637        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12638        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12639        mHandler.sendMessage(msg);
12640    }
12641
12642    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12643            PackageParser.Package pkg) {
12644        int size = pkg.activities.size();
12645        if (size == 0) {
12646            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12647                    "No activity, so no need to verify any IntentFilter!");
12648            return;
12649        }
12650
12651        final boolean hasDomainURLs = hasDomainURLs(pkg);
12652        if (!hasDomainURLs) {
12653            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12654                    "No domain URLs, so no need to verify any IntentFilter!");
12655            return;
12656        }
12657
12658        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12659                + " if any IntentFilter from the " + size
12660                + " Activities needs verification ...");
12661
12662        int count = 0;
12663        final String packageName = pkg.packageName;
12664
12665        synchronized (mPackages) {
12666            // If this is a new install and we see that we've already run verification for this
12667            // package, we have nothing to do: it means the state was restored from backup.
12668            if (!replacing) {
12669                IntentFilterVerificationInfo ivi =
12670                        mSettings.getIntentFilterVerificationLPr(packageName);
12671                if (ivi != null) {
12672                    if (DEBUG_DOMAIN_VERIFICATION) {
12673                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12674                                + ivi.getStatusString());
12675                    }
12676                    return;
12677                }
12678            }
12679
12680            // If any filters need to be verified, then all need to be.
12681            boolean needToVerify = false;
12682            for (PackageParser.Activity a : pkg.activities) {
12683                for (ActivityIntentInfo filter : a.intents) {
12684                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12685                        if (DEBUG_DOMAIN_VERIFICATION) {
12686                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12687                        }
12688                        needToVerify = true;
12689                        break;
12690                    }
12691                }
12692            }
12693
12694            if (needToVerify) {
12695                final int verificationId = mIntentFilterVerificationToken++;
12696                for (PackageParser.Activity a : pkg.activities) {
12697                    for (ActivityIntentInfo filter : a.intents) {
12698                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12699                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12700                                    "Verification needed for IntentFilter:" + filter.toString());
12701                            mIntentFilterVerifier.addOneIntentFilterVerification(
12702                                    verifierUid, userId, verificationId, filter, packageName);
12703                            count++;
12704                        }
12705                    }
12706                }
12707            }
12708        }
12709
12710        if (count > 0) {
12711            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12712                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12713                    +  " for userId:" + userId);
12714            mIntentFilterVerifier.startVerifications(userId);
12715        } else {
12716            if (DEBUG_DOMAIN_VERIFICATION) {
12717                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12718            }
12719        }
12720    }
12721
12722    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12723        final ComponentName cn  = filter.activity.getComponentName();
12724        final String packageName = cn.getPackageName();
12725
12726        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12727                packageName);
12728        if (ivi == null) {
12729            return true;
12730        }
12731        int status = ivi.getStatus();
12732        switch (status) {
12733            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12734            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12735                return true;
12736
12737            default:
12738                // Nothing to do
12739                return false;
12740        }
12741    }
12742
12743    private static boolean isMultiArch(PackageSetting ps) {
12744        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12745    }
12746
12747    private static boolean isMultiArch(ApplicationInfo info) {
12748        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12749    }
12750
12751    private static boolean isExternal(PackageParser.Package pkg) {
12752        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12753    }
12754
12755    private static boolean isExternal(PackageSetting ps) {
12756        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12757    }
12758
12759    private static boolean isExternal(ApplicationInfo info) {
12760        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12761    }
12762
12763    private static boolean isSystemApp(PackageParser.Package pkg) {
12764        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12765    }
12766
12767    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12768        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12769    }
12770
12771    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12772        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12773    }
12774
12775    private static boolean isSystemApp(PackageSetting ps) {
12776        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12777    }
12778
12779    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12780        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12781    }
12782
12783    private int packageFlagsToInstallFlags(PackageSetting ps) {
12784        int installFlags = 0;
12785        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12786            // This existing package was an external ASEC install when we have
12787            // the external flag without a UUID
12788            installFlags |= PackageManager.INSTALL_EXTERNAL;
12789        }
12790        if (ps.isForwardLocked()) {
12791            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12792        }
12793        return installFlags;
12794    }
12795
12796    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12797        if (isExternal(pkg)) {
12798            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12799                return mSettings.getExternalVersion();
12800            } else {
12801                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12802            }
12803        } else {
12804            return mSettings.getInternalVersion();
12805        }
12806    }
12807
12808    private void deleteTempPackageFiles() {
12809        final FilenameFilter filter = new FilenameFilter() {
12810            public boolean accept(File dir, String name) {
12811                return name.startsWith("vmdl") && name.endsWith(".tmp");
12812            }
12813        };
12814        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12815            file.delete();
12816        }
12817    }
12818
12819    @Override
12820    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12821            int flags) {
12822        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12823                flags);
12824    }
12825
12826    @Override
12827    public void deletePackage(final String packageName,
12828            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12829        mContext.enforceCallingOrSelfPermission(
12830                android.Manifest.permission.DELETE_PACKAGES, null);
12831        Preconditions.checkNotNull(packageName);
12832        Preconditions.checkNotNull(observer);
12833        final int uid = Binder.getCallingUid();
12834        if (UserHandle.getUserId(uid) != userId) {
12835            mContext.enforceCallingPermission(
12836                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12837                    "deletePackage for user " + userId);
12838        }
12839        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12840            try {
12841                observer.onPackageDeleted(packageName,
12842                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12843            } catch (RemoteException re) {
12844            }
12845            return;
12846        }
12847
12848        boolean uninstallBlocked = false;
12849        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12850            int[] users = sUserManager.getUserIds();
12851            for (int i = 0; i < users.length; ++i) {
12852                if (getBlockUninstallForUser(packageName, users[i])) {
12853                    uninstallBlocked = true;
12854                    break;
12855                }
12856            }
12857        } else {
12858            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12859        }
12860        if (uninstallBlocked) {
12861            try {
12862                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12863                        null);
12864            } catch (RemoteException re) {
12865            }
12866            return;
12867        }
12868
12869        if (DEBUG_REMOVE) {
12870            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12871        }
12872        // Queue up an async operation since the package deletion may take a little while.
12873        mHandler.post(new Runnable() {
12874            public void run() {
12875                mHandler.removeCallbacks(this);
12876                final int returnCode = deletePackageX(packageName, userId, flags);
12877                if (observer != null) {
12878                    try {
12879                        observer.onPackageDeleted(packageName, returnCode, null);
12880                    } catch (RemoteException e) {
12881                        Log.i(TAG, "Observer no longer exists.");
12882                    } //end catch
12883                } //end if
12884            } //end run
12885        });
12886    }
12887
12888    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12889        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12890                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12891        try {
12892            if (dpm != null) {
12893                if (dpm.isDeviceOwner(packageName)) {
12894                    return true;
12895                }
12896                int[] users;
12897                if (userId == UserHandle.USER_ALL) {
12898                    users = sUserManager.getUserIds();
12899                } else {
12900                    users = new int[]{userId};
12901                }
12902                for (int i = 0; i < users.length; ++i) {
12903                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12904                        return true;
12905                    }
12906                }
12907            }
12908        } catch (RemoteException e) {
12909        }
12910        return false;
12911    }
12912
12913    /**
12914     *  This method is an internal method that could be get invoked either
12915     *  to delete an installed package or to clean up a failed installation.
12916     *  After deleting an installed package, a broadcast is sent to notify any
12917     *  listeners that the package has been installed. For cleaning up a failed
12918     *  installation, the broadcast is not necessary since the package's
12919     *  installation wouldn't have sent the initial broadcast either
12920     *  The key steps in deleting a package are
12921     *  deleting the package information in internal structures like mPackages,
12922     *  deleting the packages base directories through installd
12923     *  updating mSettings to reflect current status
12924     *  persisting settings for later use
12925     *  sending a broadcast if necessary
12926     */
12927    private int deletePackageX(String packageName, int userId, int flags) {
12928        final PackageRemovedInfo info = new PackageRemovedInfo();
12929        final boolean res;
12930
12931        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12932                ? UserHandle.ALL : new UserHandle(userId);
12933
12934        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12935            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12936            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12937        }
12938
12939        boolean removedForAllUsers = false;
12940        boolean systemUpdate = false;
12941
12942        // for the uninstall-updates case and restricted profiles, remember the per-
12943        // userhandle installed state
12944        int[] allUsers;
12945        boolean[] perUserInstalled;
12946        synchronized (mPackages) {
12947            PackageSetting ps = mSettings.mPackages.get(packageName);
12948            allUsers = sUserManager.getUserIds();
12949            perUserInstalled = new boolean[allUsers.length];
12950            for (int i = 0; i < allUsers.length; i++) {
12951                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12952            }
12953        }
12954
12955        synchronized (mInstallLock) {
12956            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12957            res = deletePackageLI(packageName, removeForUser,
12958                    true, allUsers, perUserInstalled,
12959                    flags | REMOVE_CHATTY, info, true);
12960            systemUpdate = info.isRemovedPackageSystemUpdate;
12961            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12962                removedForAllUsers = true;
12963            }
12964            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12965                    + " removedForAllUsers=" + removedForAllUsers);
12966        }
12967
12968        if (res) {
12969            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12970
12971            // If the removed package was a system update, the old system package
12972            // was re-enabled; we need to broadcast this information
12973            if (systemUpdate) {
12974                Bundle extras = new Bundle(1);
12975                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12976                        ? info.removedAppId : info.uid);
12977                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12978
12979                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12980                        extras, null, null, null);
12981                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12982                        extras, null, null, null);
12983                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12984                        null, packageName, null, null);
12985            }
12986        }
12987        // Force a gc here.
12988        Runtime.getRuntime().gc();
12989        // Delete the resources here after sending the broadcast to let
12990        // other processes clean up before deleting resources.
12991        if (info.args != null) {
12992            synchronized (mInstallLock) {
12993                info.args.doPostDeleteLI(true);
12994            }
12995        }
12996
12997        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12998    }
12999
13000    class PackageRemovedInfo {
13001        String removedPackage;
13002        int uid = -1;
13003        int removedAppId = -1;
13004        int[] removedUsers = null;
13005        boolean isRemovedPackageSystemUpdate = false;
13006        // Clean up resources deleted packages.
13007        InstallArgs args = null;
13008
13009        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13010            Bundle extras = new Bundle(1);
13011            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13012            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13013            if (replacing) {
13014                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13015            }
13016            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13017            if (removedPackage != null) {
13018                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13019                        extras, null, null, removedUsers);
13020                if (fullRemove && !replacing) {
13021                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13022                            extras, null, null, removedUsers);
13023                }
13024            }
13025            if (removedAppId >= 0) {
13026                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
13027                        removedUsers);
13028            }
13029        }
13030    }
13031
13032    /*
13033     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13034     * flag is not set, the data directory is removed as well.
13035     * make sure this flag is set for partially installed apps. If not its meaningless to
13036     * delete a partially installed application.
13037     */
13038    private void removePackageDataLI(PackageSetting ps,
13039            int[] allUserHandles, boolean[] perUserInstalled,
13040            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13041        String packageName = ps.name;
13042        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13043        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13044        // Retrieve object to delete permissions for shared user later on
13045        final PackageSetting deletedPs;
13046        // reader
13047        synchronized (mPackages) {
13048            deletedPs = mSettings.mPackages.get(packageName);
13049            if (outInfo != null) {
13050                outInfo.removedPackage = packageName;
13051                outInfo.removedUsers = deletedPs != null
13052                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13053                        : null;
13054            }
13055        }
13056        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13057            removeDataDirsLI(ps.volumeUuid, packageName);
13058            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13059        }
13060        // writer
13061        synchronized (mPackages) {
13062            if (deletedPs != null) {
13063                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13064                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13065                    clearDefaultBrowserIfNeeded(packageName);
13066                    if (outInfo != null) {
13067                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13068                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13069                    }
13070                    updatePermissionsLPw(deletedPs.name, null, 0);
13071                    if (deletedPs.sharedUser != null) {
13072                        // Remove permissions associated with package. Since runtime
13073                        // permissions are per user we have to kill the removed package
13074                        // or packages running under the shared user of the removed
13075                        // package if revoking the permissions requested only by the removed
13076                        // package is successful and this causes a change in gids.
13077                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13078                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13079                                    userId);
13080                            if (userIdToKill == UserHandle.USER_ALL
13081                                    || userIdToKill >= UserHandle.USER_OWNER) {
13082                                // If gids changed for this user, kill all affected packages.
13083                                mHandler.post(new Runnable() {
13084                                    @Override
13085                                    public void run() {
13086                                        // This has to happen with no lock held.
13087                                        killApplication(deletedPs.name, deletedPs.appId,
13088                                                KILL_APP_REASON_GIDS_CHANGED);
13089                                    }
13090                                });
13091                                break;
13092                            }
13093                        }
13094                    }
13095                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13096                }
13097                // make sure to preserve per-user disabled state if this removal was just
13098                // a downgrade of a system app to the factory package
13099                if (allUserHandles != null && perUserInstalled != null) {
13100                    if (DEBUG_REMOVE) {
13101                        Slog.d(TAG, "Propagating install state across downgrade");
13102                    }
13103                    for (int i = 0; i < allUserHandles.length; i++) {
13104                        if (DEBUG_REMOVE) {
13105                            Slog.d(TAG, "    user " + allUserHandles[i]
13106                                    + " => " + perUserInstalled[i]);
13107                        }
13108                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13109                    }
13110                }
13111            }
13112            // can downgrade to reader
13113            if (writeSettings) {
13114                // Save settings now
13115                mSettings.writeLPr();
13116            }
13117        }
13118        if (outInfo != null) {
13119            // A user ID was deleted here. Go through all users and remove it
13120            // from KeyStore.
13121            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13122        }
13123    }
13124
13125    static boolean locationIsPrivileged(File path) {
13126        try {
13127            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13128                    .getCanonicalPath();
13129            return path.getCanonicalPath().startsWith(privilegedAppDir);
13130        } catch (IOException e) {
13131            Slog.e(TAG, "Unable to access code path " + path);
13132        }
13133        return false;
13134    }
13135
13136    /*
13137     * Tries to delete system package.
13138     */
13139    private boolean deleteSystemPackageLI(PackageSetting newPs,
13140            int[] allUserHandles, boolean[] perUserInstalled,
13141            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13142        final boolean applyUserRestrictions
13143                = (allUserHandles != null) && (perUserInstalled != null);
13144        PackageSetting disabledPs = null;
13145        // Confirm if the system package has been updated
13146        // An updated system app can be deleted. This will also have to restore
13147        // the system pkg from system partition
13148        // reader
13149        synchronized (mPackages) {
13150            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13151        }
13152        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13153                + " disabledPs=" + disabledPs);
13154        if (disabledPs == null) {
13155            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13156            return false;
13157        } else if (DEBUG_REMOVE) {
13158            Slog.d(TAG, "Deleting system pkg from data partition");
13159        }
13160        if (DEBUG_REMOVE) {
13161            if (applyUserRestrictions) {
13162                Slog.d(TAG, "Remembering install states:");
13163                for (int i = 0; i < allUserHandles.length; i++) {
13164                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13165                }
13166            }
13167        }
13168        // Delete the updated package
13169        outInfo.isRemovedPackageSystemUpdate = true;
13170        if (disabledPs.versionCode < newPs.versionCode) {
13171            // Delete data for downgrades
13172            flags &= ~PackageManager.DELETE_KEEP_DATA;
13173        } else {
13174            // Preserve data by setting flag
13175            flags |= PackageManager.DELETE_KEEP_DATA;
13176        }
13177        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13178                allUserHandles, perUserInstalled, outInfo, writeSettings);
13179        if (!ret) {
13180            return false;
13181        }
13182        // writer
13183        synchronized (mPackages) {
13184            // Reinstate the old system package
13185            mSettings.enableSystemPackageLPw(newPs.name);
13186            // Remove any native libraries from the upgraded package.
13187            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13188        }
13189        // Install the system package
13190        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13191        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13192        if (locationIsPrivileged(disabledPs.codePath)) {
13193            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13194        }
13195
13196        final PackageParser.Package newPkg;
13197        try {
13198            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13199        } catch (PackageManagerException e) {
13200            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13201            return false;
13202        }
13203
13204        // writer
13205        synchronized (mPackages) {
13206            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13207
13208            // Propagate the permissions state as we do not want to drop on the floor
13209            // runtime permissions. The update permissions method below will take
13210            // care of removing obsolete permissions and grant install permissions.
13211            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13212            updatePermissionsLPw(newPkg.packageName, newPkg,
13213                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13214
13215            if (applyUserRestrictions) {
13216                if (DEBUG_REMOVE) {
13217                    Slog.d(TAG, "Propagating install state across reinstall");
13218                }
13219                for (int i = 0; i < allUserHandles.length; i++) {
13220                    if (DEBUG_REMOVE) {
13221                        Slog.d(TAG, "    user " + allUserHandles[i]
13222                                + " => " + perUserInstalled[i]);
13223                    }
13224                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13225
13226                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13227                }
13228                // Regardless of writeSettings we need to ensure that this restriction
13229                // state propagation is persisted
13230                mSettings.writeAllUsersPackageRestrictionsLPr();
13231            }
13232            // can downgrade to reader here
13233            if (writeSettings) {
13234                mSettings.writeLPr();
13235            }
13236        }
13237        return true;
13238    }
13239
13240    private boolean deleteInstalledPackageLI(PackageSetting ps,
13241            boolean deleteCodeAndResources, int flags,
13242            int[] allUserHandles, boolean[] perUserInstalled,
13243            PackageRemovedInfo outInfo, boolean writeSettings) {
13244        if (outInfo != null) {
13245            outInfo.uid = ps.appId;
13246        }
13247
13248        // Delete package data from internal structures and also remove data if flag is set
13249        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13250
13251        // Delete application code and resources
13252        if (deleteCodeAndResources && (outInfo != null)) {
13253            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13254                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13255            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13256        }
13257        return true;
13258    }
13259
13260    @Override
13261    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13262            int userId) {
13263        mContext.enforceCallingOrSelfPermission(
13264                android.Manifest.permission.DELETE_PACKAGES, null);
13265        synchronized (mPackages) {
13266            PackageSetting ps = mSettings.mPackages.get(packageName);
13267            if (ps == null) {
13268                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13269                return false;
13270            }
13271            if (!ps.getInstalled(userId)) {
13272                // Can't block uninstall for an app that is not installed or enabled.
13273                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13274                return false;
13275            }
13276            ps.setBlockUninstall(blockUninstall, userId);
13277            mSettings.writePackageRestrictionsLPr(userId);
13278        }
13279        return true;
13280    }
13281
13282    @Override
13283    public boolean getBlockUninstallForUser(String packageName, int userId) {
13284        synchronized (mPackages) {
13285            PackageSetting ps = mSettings.mPackages.get(packageName);
13286            if (ps == null) {
13287                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13288                return false;
13289            }
13290            return ps.getBlockUninstall(userId);
13291        }
13292    }
13293
13294    /*
13295     * This method handles package deletion in general
13296     */
13297    private boolean deletePackageLI(String packageName, UserHandle user,
13298            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13299            int flags, PackageRemovedInfo outInfo,
13300            boolean writeSettings) {
13301        if (packageName == null) {
13302            Slog.w(TAG, "Attempt to delete null packageName.");
13303            return false;
13304        }
13305        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13306        PackageSetting ps;
13307        boolean dataOnly = false;
13308        int removeUser = -1;
13309        int appId = -1;
13310        synchronized (mPackages) {
13311            ps = mSettings.mPackages.get(packageName);
13312            if (ps == null) {
13313                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13314                return false;
13315            }
13316            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13317                    && user.getIdentifier() != UserHandle.USER_ALL) {
13318                // The caller is asking that the package only be deleted for a single
13319                // user.  To do this, we just mark its uninstalled state and delete
13320                // its data.  If this is a system app, we only allow this to happen if
13321                // they have set the special DELETE_SYSTEM_APP which requests different
13322                // semantics than normal for uninstalling system apps.
13323                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13324                final int userId = user.getIdentifier();
13325                ps.setUserState(userId,
13326                        COMPONENT_ENABLED_STATE_DEFAULT,
13327                        false, //installed
13328                        true,  //stopped
13329                        true,  //notLaunched
13330                        false, //hidden
13331                        null, null, null,
13332                        false, // blockUninstall
13333                        ps.readUserState(userId).domainVerificationStatus, 0);
13334                if (!isSystemApp(ps)) {
13335                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13336                        // Other user still have this package installed, so all
13337                        // we need to do is clear this user's data and save that
13338                        // it is uninstalled.
13339                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13340                        removeUser = user.getIdentifier();
13341                        appId = ps.appId;
13342                        scheduleWritePackageRestrictionsLocked(removeUser);
13343                    } else {
13344                        // We need to set it back to 'installed' so the uninstall
13345                        // broadcasts will be sent correctly.
13346                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13347                        ps.setInstalled(true, user.getIdentifier());
13348                    }
13349                } else {
13350                    // This is a system app, so we assume that the
13351                    // other users still have this package installed, so all
13352                    // we need to do is clear this user's data and save that
13353                    // it is uninstalled.
13354                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13355                    removeUser = user.getIdentifier();
13356                    appId = ps.appId;
13357                    scheduleWritePackageRestrictionsLocked(removeUser);
13358                }
13359            }
13360        }
13361
13362        if (removeUser >= 0) {
13363            // From above, we determined that we are deleting this only
13364            // for a single user.  Continue the work here.
13365            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13366            if (outInfo != null) {
13367                outInfo.removedPackage = packageName;
13368                outInfo.removedAppId = appId;
13369                outInfo.removedUsers = new int[] {removeUser};
13370            }
13371            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13372            removeKeystoreDataIfNeeded(removeUser, appId);
13373            schedulePackageCleaning(packageName, removeUser, false);
13374            synchronized (mPackages) {
13375                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13376                    scheduleWritePackageRestrictionsLocked(removeUser);
13377                }
13378                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13379            }
13380            return true;
13381        }
13382
13383        if (dataOnly) {
13384            // Delete application data first
13385            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13386            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13387            return true;
13388        }
13389
13390        boolean ret = false;
13391        if (isSystemApp(ps)) {
13392            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13393            // When an updated system application is deleted we delete the existing resources as well and
13394            // fall back to existing code in system partition
13395            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13396                    flags, outInfo, writeSettings);
13397        } else {
13398            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13399            // Kill application pre-emptively especially for apps on sd.
13400            killApplication(packageName, ps.appId, "uninstall pkg");
13401            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13402                    allUserHandles, perUserInstalled,
13403                    outInfo, writeSettings);
13404        }
13405
13406        return ret;
13407    }
13408
13409    private final class ClearStorageConnection implements ServiceConnection {
13410        IMediaContainerService mContainerService;
13411
13412        @Override
13413        public void onServiceConnected(ComponentName name, IBinder service) {
13414            synchronized (this) {
13415                mContainerService = IMediaContainerService.Stub.asInterface(service);
13416                notifyAll();
13417            }
13418        }
13419
13420        @Override
13421        public void onServiceDisconnected(ComponentName name) {
13422        }
13423    }
13424
13425    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13426        final boolean mounted;
13427        if (Environment.isExternalStorageEmulated()) {
13428            mounted = true;
13429        } else {
13430            final String status = Environment.getExternalStorageState();
13431
13432            mounted = status.equals(Environment.MEDIA_MOUNTED)
13433                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13434        }
13435
13436        if (!mounted) {
13437            return;
13438        }
13439
13440        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13441        int[] users;
13442        if (userId == UserHandle.USER_ALL) {
13443            users = sUserManager.getUserIds();
13444        } else {
13445            users = new int[] { userId };
13446        }
13447        final ClearStorageConnection conn = new ClearStorageConnection();
13448        if (mContext.bindServiceAsUser(
13449                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13450            try {
13451                for (int curUser : users) {
13452                    long timeout = SystemClock.uptimeMillis() + 5000;
13453                    synchronized (conn) {
13454                        long now = SystemClock.uptimeMillis();
13455                        while (conn.mContainerService == null && now < timeout) {
13456                            try {
13457                                conn.wait(timeout - now);
13458                            } catch (InterruptedException e) {
13459                            }
13460                        }
13461                    }
13462                    if (conn.mContainerService == null) {
13463                        return;
13464                    }
13465
13466                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13467                    clearDirectory(conn.mContainerService,
13468                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13469                    if (allData) {
13470                        clearDirectory(conn.mContainerService,
13471                                userEnv.buildExternalStorageAppDataDirs(packageName));
13472                        clearDirectory(conn.mContainerService,
13473                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13474                    }
13475                }
13476            } finally {
13477                mContext.unbindService(conn);
13478            }
13479        }
13480    }
13481
13482    @Override
13483    public void clearApplicationUserData(final String packageName,
13484            final IPackageDataObserver observer, final int userId) {
13485        mContext.enforceCallingOrSelfPermission(
13486                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13487        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13488        // Queue up an async operation since the package deletion may take a little while.
13489        mHandler.post(new Runnable() {
13490            public void run() {
13491                mHandler.removeCallbacks(this);
13492                final boolean succeeded;
13493                synchronized (mInstallLock) {
13494                    succeeded = clearApplicationUserDataLI(packageName, userId);
13495                }
13496                clearExternalStorageDataSync(packageName, userId, true);
13497                if (succeeded) {
13498                    // invoke DeviceStorageMonitor's update method to clear any notifications
13499                    DeviceStorageMonitorInternal
13500                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13501                    if (dsm != null) {
13502                        dsm.checkMemory();
13503                    }
13504                }
13505                if(observer != null) {
13506                    try {
13507                        observer.onRemoveCompleted(packageName, succeeded);
13508                    } catch (RemoteException e) {
13509                        Log.i(TAG, "Observer no longer exists.");
13510                    }
13511                } //end if observer
13512            } //end run
13513        });
13514    }
13515
13516    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13517        if (packageName == null) {
13518            Slog.w(TAG, "Attempt to delete null packageName.");
13519            return false;
13520        }
13521
13522        // Try finding details about the requested package
13523        PackageParser.Package pkg;
13524        synchronized (mPackages) {
13525            pkg = mPackages.get(packageName);
13526            if (pkg == null) {
13527                final PackageSetting ps = mSettings.mPackages.get(packageName);
13528                if (ps != null) {
13529                    pkg = ps.pkg;
13530                }
13531            }
13532
13533            if (pkg == null) {
13534                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13535                return false;
13536            }
13537
13538            PackageSetting ps = (PackageSetting) pkg.mExtras;
13539            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13540        }
13541
13542        // Always delete data directories for package, even if we found no other
13543        // record of app. This helps users recover from UID mismatches without
13544        // resorting to a full data wipe.
13545        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13546        if (retCode < 0) {
13547            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13548            return false;
13549        }
13550
13551        final int appId = pkg.applicationInfo.uid;
13552        removeKeystoreDataIfNeeded(userId, appId);
13553
13554        // Create a native library symlink only if we have native libraries
13555        // and if the native libraries are 32 bit libraries. We do not provide
13556        // this symlink for 64 bit libraries.
13557        if (pkg.applicationInfo.primaryCpuAbi != null &&
13558                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13559            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13560            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13561                    nativeLibPath, userId) < 0) {
13562                Slog.w(TAG, "Failed linking native library dir");
13563                return false;
13564            }
13565        }
13566
13567        return true;
13568    }
13569
13570    /**
13571     * Reverts user permission state changes (permissions and flags) in
13572     * all packages for a given user.
13573     *
13574     * @param userId The device user for which to do a reset.
13575     */
13576    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13577        final int packageCount = mPackages.size();
13578        for (int i = 0; i < packageCount; i++) {
13579            PackageParser.Package pkg = mPackages.valueAt(i);
13580            PackageSetting ps = (PackageSetting) pkg.mExtras;
13581            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13582        }
13583    }
13584
13585    /**
13586     * Reverts user permission state changes (permissions and flags).
13587     *
13588     * @param ps The package for which to reset.
13589     * @param userId The device user for which to do a reset.
13590     */
13591    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13592            final PackageSetting ps, final int userId) {
13593        if (ps.pkg == null) {
13594            return;
13595        }
13596
13597        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13598                | FLAG_PERMISSION_USER_FIXED
13599                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13600
13601        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13602                | FLAG_PERMISSION_POLICY_FIXED;
13603
13604        boolean writeInstallPermissions = false;
13605        boolean writeRuntimePermissions = false;
13606
13607        final int permissionCount = ps.pkg.requestedPermissions.size();
13608        for (int i = 0; i < permissionCount; i++) {
13609            String permission = ps.pkg.requestedPermissions.get(i);
13610
13611            BasePermission bp = mSettings.mPermissions.get(permission);
13612            if (bp == null) {
13613                continue;
13614            }
13615
13616            // If shared user we just reset the state to which only this app contributed.
13617            if (ps.sharedUser != null) {
13618                boolean used = false;
13619                final int packageCount = ps.sharedUser.packages.size();
13620                for (int j = 0; j < packageCount; j++) {
13621                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13622                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13623                            && pkg.pkg.requestedPermissions.contains(permission)) {
13624                        used = true;
13625                        break;
13626                    }
13627                }
13628                if (used) {
13629                    continue;
13630                }
13631            }
13632
13633            PermissionsState permissionsState = ps.getPermissionsState();
13634
13635            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13636
13637            // Always clear the user settable flags.
13638            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13639                    bp.name) != null;
13640            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13641                if (hasInstallState) {
13642                    writeInstallPermissions = true;
13643                } else {
13644                    writeRuntimePermissions = true;
13645                }
13646            }
13647
13648            // Below is only runtime permission handling.
13649            if (!bp.isRuntime()) {
13650                continue;
13651            }
13652
13653            // Never clobber system or policy.
13654            if ((oldFlags & policyOrSystemFlags) != 0) {
13655                continue;
13656            }
13657
13658            // If this permission was granted by default, make sure it is.
13659            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13660                if (permissionsState.grantRuntimePermission(bp, userId)
13661                        != PERMISSION_OPERATION_FAILURE) {
13662                    writeRuntimePermissions = true;
13663                }
13664            } else {
13665                // Otherwise, reset the permission.
13666                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13667                switch (revokeResult) {
13668                    case PERMISSION_OPERATION_SUCCESS: {
13669                        writeRuntimePermissions = true;
13670                    } break;
13671
13672                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13673                        writeRuntimePermissions = true;
13674                        final int appId = ps.appId;
13675                        mHandler.post(new Runnable() {
13676                            @Override
13677                            public void run() {
13678                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13679                            }
13680                        });
13681                    } break;
13682                }
13683            }
13684        }
13685
13686        // Synchronously write as we are taking permissions away.
13687        if (writeRuntimePermissions) {
13688            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13689        }
13690
13691        // Synchronously write as we are taking permissions away.
13692        if (writeInstallPermissions) {
13693            mSettings.writeLPr();
13694        }
13695    }
13696
13697    /**
13698     * Remove entries from the keystore daemon. Will only remove it if the
13699     * {@code appId} is valid.
13700     */
13701    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13702        if (appId < 0) {
13703            return;
13704        }
13705
13706        final KeyStore keyStore = KeyStore.getInstance();
13707        if (keyStore != null) {
13708            if (userId == UserHandle.USER_ALL) {
13709                for (final int individual : sUserManager.getUserIds()) {
13710                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13711                }
13712            } else {
13713                keyStore.clearUid(UserHandle.getUid(userId, appId));
13714            }
13715        } else {
13716            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13717        }
13718    }
13719
13720    @Override
13721    public void deleteApplicationCacheFiles(final String packageName,
13722            final IPackageDataObserver observer) {
13723        mContext.enforceCallingOrSelfPermission(
13724                android.Manifest.permission.DELETE_CACHE_FILES, null);
13725        // Queue up an async operation since the package deletion may take a little while.
13726        final int userId = UserHandle.getCallingUserId();
13727        mHandler.post(new Runnable() {
13728            public void run() {
13729                mHandler.removeCallbacks(this);
13730                final boolean succeded;
13731                synchronized (mInstallLock) {
13732                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13733                }
13734                clearExternalStorageDataSync(packageName, userId, false);
13735                if (observer != null) {
13736                    try {
13737                        observer.onRemoveCompleted(packageName, succeded);
13738                    } catch (RemoteException e) {
13739                        Log.i(TAG, "Observer no longer exists.");
13740                    }
13741                } //end if observer
13742            } //end run
13743        });
13744    }
13745
13746    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13747        if (packageName == null) {
13748            Slog.w(TAG, "Attempt to delete null packageName.");
13749            return false;
13750        }
13751        PackageParser.Package p;
13752        synchronized (mPackages) {
13753            p = mPackages.get(packageName);
13754        }
13755        if (p == null) {
13756            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13757            return false;
13758        }
13759        final ApplicationInfo applicationInfo = p.applicationInfo;
13760        if (applicationInfo == null) {
13761            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13762            return false;
13763        }
13764        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13765        if (retCode < 0) {
13766            Slog.w(TAG, "Couldn't remove cache files for package: "
13767                       + packageName + " u" + userId);
13768            return false;
13769        }
13770        return true;
13771    }
13772
13773    @Override
13774    public void getPackageSizeInfo(final String packageName, int userHandle,
13775            final IPackageStatsObserver observer) {
13776        mContext.enforceCallingOrSelfPermission(
13777                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13778        if (packageName == null) {
13779            throw new IllegalArgumentException("Attempt to get size of null packageName");
13780        }
13781
13782        PackageStats stats = new PackageStats(packageName, userHandle);
13783
13784        /*
13785         * Queue up an async operation since the package measurement may take a
13786         * little while.
13787         */
13788        Message msg = mHandler.obtainMessage(INIT_COPY);
13789        msg.obj = new MeasureParams(stats, observer);
13790        mHandler.sendMessage(msg);
13791    }
13792
13793    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13794            PackageStats pStats) {
13795        if (packageName == null) {
13796            Slog.w(TAG, "Attempt to get size of null packageName.");
13797            return false;
13798        }
13799        PackageParser.Package p;
13800        boolean dataOnly = false;
13801        String libDirRoot = null;
13802        String asecPath = null;
13803        PackageSetting ps = null;
13804        synchronized (mPackages) {
13805            p = mPackages.get(packageName);
13806            ps = mSettings.mPackages.get(packageName);
13807            if(p == null) {
13808                dataOnly = true;
13809                if((ps == null) || (ps.pkg == null)) {
13810                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13811                    return false;
13812                }
13813                p = ps.pkg;
13814            }
13815            if (ps != null) {
13816                libDirRoot = ps.legacyNativeLibraryPathString;
13817            }
13818            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13819                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13820                if (secureContainerId != null) {
13821                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13822                }
13823            }
13824        }
13825        String publicSrcDir = null;
13826        if(!dataOnly) {
13827            final ApplicationInfo applicationInfo = p.applicationInfo;
13828            if (applicationInfo == null) {
13829                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13830                return false;
13831            }
13832            if (p.isForwardLocked()) {
13833                publicSrcDir = applicationInfo.getBaseResourcePath();
13834            }
13835        }
13836        // TODO: extend to measure size of split APKs
13837        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13838        // not just the first level.
13839        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13840        // just the primary.
13841        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13842        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13843                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13844        if (res < 0) {
13845            return false;
13846        }
13847
13848        // Fix-up for forward-locked applications in ASEC containers.
13849        if (!isExternal(p)) {
13850            pStats.codeSize += pStats.externalCodeSize;
13851            pStats.externalCodeSize = 0L;
13852        }
13853
13854        return true;
13855    }
13856
13857
13858    @Override
13859    public void addPackageToPreferred(String packageName) {
13860        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13861    }
13862
13863    @Override
13864    public void removePackageFromPreferred(String packageName) {
13865        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13866    }
13867
13868    @Override
13869    public List<PackageInfo> getPreferredPackages(int flags) {
13870        return new ArrayList<PackageInfo>();
13871    }
13872
13873    private int getUidTargetSdkVersionLockedLPr(int uid) {
13874        Object obj = mSettings.getUserIdLPr(uid);
13875        if (obj instanceof SharedUserSetting) {
13876            final SharedUserSetting sus = (SharedUserSetting) obj;
13877            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13878            final Iterator<PackageSetting> it = sus.packages.iterator();
13879            while (it.hasNext()) {
13880                final PackageSetting ps = it.next();
13881                if (ps.pkg != null) {
13882                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13883                    if (v < vers) vers = v;
13884                }
13885            }
13886            return vers;
13887        } else if (obj instanceof PackageSetting) {
13888            final PackageSetting ps = (PackageSetting) obj;
13889            if (ps.pkg != null) {
13890                return ps.pkg.applicationInfo.targetSdkVersion;
13891            }
13892        }
13893        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13894    }
13895
13896    @Override
13897    public void addPreferredActivity(IntentFilter filter, int match,
13898            ComponentName[] set, ComponentName activity, int userId) {
13899        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13900                "Adding preferred");
13901    }
13902
13903    private void addPreferredActivityInternal(IntentFilter filter, int match,
13904            ComponentName[] set, ComponentName activity, boolean always, int userId,
13905            String opname) {
13906        // writer
13907        int callingUid = Binder.getCallingUid();
13908        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13909        if (filter.countActions() == 0) {
13910            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13911            return;
13912        }
13913        synchronized (mPackages) {
13914            if (mContext.checkCallingOrSelfPermission(
13915                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13916                    != PackageManager.PERMISSION_GRANTED) {
13917                if (getUidTargetSdkVersionLockedLPr(callingUid)
13918                        < Build.VERSION_CODES.FROYO) {
13919                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13920                            + callingUid);
13921                    return;
13922                }
13923                mContext.enforceCallingOrSelfPermission(
13924                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13925            }
13926
13927            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13928            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13929                    + userId + ":");
13930            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13931            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13932            scheduleWritePackageRestrictionsLocked(userId);
13933        }
13934    }
13935
13936    @Override
13937    public void replacePreferredActivity(IntentFilter filter, int match,
13938            ComponentName[] set, ComponentName activity, int userId) {
13939        if (filter.countActions() != 1) {
13940            throw new IllegalArgumentException(
13941                    "replacePreferredActivity expects filter to have only 1 action.");
13942        }
13943        if (filter.countDataAuthorities() != 0
13944                || filter.countDataPaths() != 0
13945                || filter.countDataSchemes() > 1
13946                || filter.countDataTypes() != 0) {
13947            throw new IllegalArgumentException(
13948                    "replacePreferredActivity expects filter to have no data authorities, " +
13949                    "paths, or types; and at most one scheme.");
13950        }
13951
13952        final int callingUid = Binder.getCallingUid();
13953        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13954        synchronized (mPackages) {
13955            if (mContext.checkCallingOrSelfPermission(
13956                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13957                    != PackageManager.PERMISSION_GRANTED) {
13958                if (getUidTargetSdkVersionLockedLPr(callingUid)
13959                        < Build.VERSION_CODES.FROYO) {
13960                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13961                            + Binder.getCallingUid());
13962                    return;
13963                }
13964                mContext.enforceCallingOrSelfPermission(
13965                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13966            }
13967
13968            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13969            if (pir != null) {
13970                // Get all of the existing entries that exactly match this filter.
13971                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13972                if (existing != null && existing.size() == 1) {
13973                    PreferredActivity cur = existing.get(0);
13974                    if (DEBUG_PREFERRED) {
13975                        Slog.i(TAG, "Checking replace of preferred:");
13976                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13977                        if (!cur.mPref.mAlways) {
13978                            Slog.i(TAG, "  -- CUR; not mAlways!");
13979                        } else {
13980                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13981                            Slog.i(TAG, "  -- CUR: mSet="
13982                                    + Arrays.toString(cur.mPref.mSetComponents));
13983                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13984                            Slog.i(TAG, "  -- NEW: mMatch="
13985                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13986                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13987                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13988                        }
13989                    }
13990                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13991                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13992                            && cur.mPref.sameSet(set)) {
13993                        // Setting the preferred activity to what it happens to be already
13994                        if (DEBUG_PREFERRED) {
13995                            Slog.i(TAG, "Replacing with same preferred activity "
13996                                    + cur.mPref.mShortComponent + " for user "
13997                                    + userId + ":");
13998                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13999                        }
14000                        return;
14001                    }
14002                }
14003
14004                if (existing != null) {
14005                    if (DEBUG_PREFERRED) {
14006                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14007                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14008                    }
14009                    for (int i = 0; i < existing.size(); i++) {
14010                        PreferredActivity pa = existing.get(i);
14011                        if (DEBUG_PREFERRED) {
14012                            Slog.i(TAG, "Removing existing preferred activity "
14013                                    + pa.mPref.mComponent + ":");
14014                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14015                        }
14016                        pir.removeFilter(pa);
14017                    }
14018                }
14019            }
14020            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14021                    "Replacing preferred");
14022        }
14023    }
14024
14025    @Override
14026    public void clearPackagePreferredActivities(String packageName) {
14027        final int uid = Binder.getCallingUid();
14028        // writer
14029        synchronized (mPackages) {
14030            PackageParser.Package pkg = mPackages.get(packageName);
14031            if (pkg == null || pkg.applicationInfo.uid != uid) {
14032                if (mContext.checkCallingOrSelfPermission(
14033                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14034                        != PackageManager.PERMISSION_GRANTED) {
14035                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14036                            < Build.VERSION_CODES.FROYO) {
14037                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14038                                + Binder.getCallingUid());
14039                        return;
14040                    }
14041                    mContext.enforceCallingOrSelfPermission(
14042                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14043                }
14044            }
14045
14046            int user = UserHandle.getCallingUserId();
14047            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14048                scheduleWritePackageRestrictionsLocked(user);
14049            }
14050        }
14051    }
14052
14053    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14054    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14055        ArrayList<PreferredActivity> removed = null;
14056        boolean changed = false;
14057        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14058            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14059            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14060            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14061                continue;
14062            }
14063            Iterator<PreferredActivity> it = pir.filterIterator();
14064            while (it.hasNext()) {
14065                PreferredActivity pa = it.next();
14066                // Mark entry for removal only if it matches the package name
14067                // and the entry is of type "always".
14068                if (packageName == null ||
14069                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14070                                && pa.mPref.mAlways)) {
14071                    if (removed == null) {
14072                        removed = new ArrayList<PreferredActivity>();
14073                    }
14074                    removed.add(pa);
14075                }
14076            }
14077            if (removed != null) {
14078                for (int j=0; j<removed.size(); j++) {
14079                    PreferredActivity pa = removed.get(j);
14080                    pir.removeFilter(pa);
14081                }
14082                changed = true;
14083            }
14084        }
14085        return changed;
14086    }
14087
14088    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14089    private void clearIntentFilterVerificationsLPw(int userId) {
14090        final int packageCount = mPackages.size();
14091        for (int i = 0; i < packageCount; i++) {
14092            PackageParser.Package pkg = mPackages.valueAt(i);
14093            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14094        }
14095    }
14096
14097    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14098    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14099        if (userId == UserHandle.USER_ALL) {
14100            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14101                    sUserManager.getUserIds())) {
14102                for (int oneUserId : sUserManager.getUserIds()) {
14103                    scheduleWritePackageRestrictionsLocked(oneUserId);
14104                }
14105            }
14106        } else {
14107            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14108                scheduleWritePackageRestrictionsLocked(userId);
14109            }
14110        }
14111    }
14112
14113    void clearDefaultBrowserIfNeeded(String packageName) {
14114        for (int oneUserId : sUserManager.getUserIds()) {
14115            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14116            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14117            if (packageName.equals(defaultBrowserPackageName)) {
14118                setDefaultBrowserPackageName(null, oneUserId);
14119            }
14120        }
14121    }
14122
14123    @Override
14124    public void resetApplicationPreferences(int userId) {
14125        mContext.enforceCallingOrSelfPermission(
14126                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14127        // writer
14128        synchronized (mPackages) {
14129            final long identity = Binder.clearCallingIdentity();
14130            try {
14131                clearPackagePreferredActivitiesLPw(null, userId);
14132                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14133                // TODO: We have to reset the default SMS and Phone. This requires
14134                // significant refactoring to keep all default apps in the package
14135                // manager (cleaner but more work) or have the services provide
14136                // callbacks to the package manager to request a default app reset.
14137                applyFactoryDefaultBrowserLPw(userId);
14138                clearIntentFilterVerificationsLPw(userId);
14139                primeDomainVerificationsLPw(userId);
14140                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14141                scheduleWritePackageRestrictionsLocked(userId);
14142            } finally {
14143                Binder.restoreCallingIdentity(identity);
14144            }
14145        }
14146    }
14147
14148    @Override
14149    public int getPreferredActivities(List<IntentFilter> outFilters,
14150            List<ComponentName> outActivities, String packageName) {
14151
14152        int num = 0;
14153        final int userId = UserHandle.getCallingUserId();
14154        // reader
14155        synchronized (mPackages) {
14156            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14157            if (pir != null) {
14158                final Iterator<PreferredActivity> it = pir.filterIterator();
14159                while (it.hasNext()) {
14160                    final PreferredActivity pa = it.next();
14161                    if (packageName == null
14162                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14163                                    && pa.mPref.mAlways)) {
14164                        if (outFilters != null) {
14165                            outFilters.add(new IntentFilter(pa));
14166                        }
14167                        if (outActivities != null) {
14168                            outActivities.add(pa.mPref.mComponent);
14169                        }
14170                    }
14171                }
14172            }
14173        }
14174
14175        return num;
14176    }
14177
14178    @Override
14179    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14180            int userId) {
14181        int callingUid = Binder.getCallingUid();
14182        if (callingUid != Process.SYSTEM_UID) {
14183            throw new SecurityException(
14184                    "addPersistentPreferredActivity can only be run by the system");
14185        }
14186        if (filter.countActions() == 0) {
14187            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14188            return;
14189        }
14190        synchronized (mPackages) {
14191            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14192                    " :");
14193            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14194            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14195                    new PersistentPreferredActivity(filter, activity));
14196            scheduleWritePackageRestrictionsLocked(userId);
14197        }
14198    }
14199
14200    @Override
14201    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14202        int callingUid = Binder.getCallingUid();
14203        if (callingUid != Process.SYSTEM_UID) {
14204            throw new SecurityException(
14205                    "clearPackagePersistentPreferredActivities can only be run by the system");
14206        }
14207        ArrayList<PersistentPreferredActivity> removed = null;
14208        boolean changed = false;
14209        synchronized (mPackages) {
14210            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14211                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14212                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14213                        .valueAt(i);
14214                if (userId != thisUserId) {
14215                    continue;
14216                }
14217                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14218                while (it.hasNext()) {
14219                    PersistentPreferredActivity ppa = it.next();
14220                    // Mark entry for removal only if it matches the package name.
14221                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14222                        if (removed == null) {
14223                            removed = new ArrayList<PersistentPreferredActivity>();
14224                        }
14225                        removed.add(ppa);
14226                    }
14227                }
14228                if (removed != null) {
14229                    for (int j=0; j<removed.size(); j++) {
14230                        PersistentPreferredActivity ppa = removed.get(j);
14231                        ppir.removeFilter(ppa);
14232                    }
14233                    changed = true;
14234                }
14235            }
14236
14237            if (changed) {
14238                scheduleWritePackageRestrictionsLocked(userId);
14239            }
14240        }
14241    }
14242
14243    /**
14244     * Common machinery for picking apart a restored XML blob and passing
14245     * it to a caller-supplied functor to be applied to the running system.
14246     */
14247    private void restoreFromXml(XmlPullParser parser, int userId,
14248            String expectedStartTag, BlobXmlRestorer functor)
14249            throws IOException, XmlPullParserException {
14250        int type;
14251        while ((type = parser.next()) != XmlPullParser.START_TAG
14252                && type != XmlPullParser.END_DOCUMENT) {
14253        }
14254        if (type != XmlPullParser.START_TAG) {
14255            // oops didn't find a start tag?!
14256            if (DEBUG_BACKUP) {
14257                Slog.e(TAG, "Didn't find start tag during restore");
14258            }
14259            return;
14260        }
14261
14262        // this is supposed to be TAG_PREFERRED_BACKUP
14263        if (!expectedStartTag.equals(parser.getName())) {
14264            if (DEBUG_BACKUP) {
14265                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14266            }
14267            return;
14268        }
14269
14270        // skip interfering stuff, then we're aligned with the backing implementation
14271        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14272        functor.apply(parser, userId);
14273    }
14274
14275    private interface BlobXmlRestorer {
14276        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14277    }
14278
14279    /**
14280     * Non-Binder method, support for the backup/restore mechanism: write the
14281     * full set of preferred activities in its canonical XML format.  Returns the
14282     * XML output as a byte array, or null if there is none.
14283     */
14284    @Override
14285    public byte[] getPreferredActivityBackup(int userId) {
14286        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14287            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14288        }
14289
14290        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14291        try {
14292            final XmlSerializer serializer = new FastXmlSerializer();
14293            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14294            serializer.startDocument(null, true);
14295            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14296
14297            synchronized (mPackages) {
14298                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14299            }
14300
14301            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14302            serializer.endDocument();
14303            serializer.flush();
14304        } catch (Exception e) {
14305            if (DEBUG_BACKUP) {
14306                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14307            }
14308            return null;
14309        }
14310
14311        return dataStream.toByteArray();
14312    }
14313
14314    @Override
14315    public void restorePreferredActivities(byte[] backup, int userId) {
14316        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14317            throw new SecurityException("Only the system may call restorePreferredActivities()");
14318        }
14319
14320        try {
14321            final XmlPullParser parser = Xml.newPullParser();
14322            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14323            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14324                    new BlobXmlRestorer() {
14325                        @Override
14326                        public void apply(XmlPullParser parser, int userId)
14327                                throws XmlPullParserException, IOException {
14328                            synchronized (mPackages) {
14329                                mSettings.readPreferredActivitiesLPw(parser, userId);
14330                            }
14331                        }
14332                    } );
14333        } catch (Exception e) {
14334            if (DEBUG_BACKUP) {
14335                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14336            }
14337        }
14338    }
14339
14340    /**
14341     * Non-Binder method, support for the backup/restore mechanism: write the
14342     * default browser (etc) settings in its canonical XML format.  Returns the default
14343     * browser XML representation as a byte array, or null if there is none.
14344     */
14345    @Override
14346    public byte[] getDefaultAppsBackup(int userId) {
14347        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14348            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14349        }
14350
14351        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14352        try {
14353            final XmlSerializer serializer = new FastXmlSerializer();
14354            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14355            serializer.startDocument(null, true);
14356            serializer.startTag(null, TAG_DEFAULT_APPS);
14357
14358            synchronized (mPackages) {
14359                mSettings.writeDefaultAppsLPr(serializer, userId);
14360            }
14361
14362            serializer.endTag(null, TAG_DEFAULT_APPS);
14363            serializer.endDocument();
14364            serializer.flush();
14365        } catch (Exception e) {
14366            if (DEBUG_BACKUP) {
14367                Slog.e(TAG, "Unable to write default apps for backup", e);
14368            }
14369            return null;
14370        }
14371
14372        return dataStream.toByteArray();
14373    }
14374
14375    @Override
14376    public void restoreDefaultApps(byte[] backup, int userId) {
14377        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14378            throw new SecurityException("Only the system may call restoreDefaultApps()");
14379        }
14380
14381        try {
14382            final XmlPullParser parser = Xml.newPullParser();
14383            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14384            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14385                    new BlobXmlRestorer() {
14386                        @Override
14387                        public void apply(XmlPullParser parser, int userId)
14388                                throws XmlPullParserException, IOException {
14389                            synchronized (mPackages) {
14390                                mSettings.readDefaultAppsLPw(parser, userId);
14391                            }
14392                        }
14393                    } );
14394        } catch (Exception e) {
14395            if (DEBUG_BACKUP) {
14396                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14397            }
14398        }
14399    }
14400
14401    @Override
14402    public byte[] getIntentFilterVerificationBackup(int userId) {
14403        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14404            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14405        }
14406
14407        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14408        try {
14409            final XmlSerializer serializer = new FastXmlSerializer();
14410            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14411            serializer.startDocument(null, true);
14412            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14413
14414            synchronized (mPackages) {
14415                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14416            }
14417
14418            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14419            serializer.endDocument();
14420            serializer.flush();
14421        } catch (Exception e) {
14422            if (DEBUG_BACKUP) {
14423                Slog.e(TAG, "Unable to write default apps for backup", e);
14424            }
14425            return null;
14426        }
14427
14428        return dataStream.toByteArray();
14429    }
14430
14431    @Override
14432    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14433        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14434            throw new SecurityException("Only the system may call restorePreferredActivities()");
14435        }
14436
14437        try {
14438            final XmlPullParser parser = Xml.newPullParser();
14439            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14440            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14441                    new BlobXmlRestorer() {
14442                        @Override
14443                        public void apply(XmlPullParser parser, int userId)
14444                                throws XmlPullParserException, IOException {
14445                            synchronized (mPackages) {
14446                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14447                                mSettings.writeLPr();
14448                            }
14449                        }
14450                    } );
14451        } catch (Exception e) {
14452            if (DEBUG_BACKUP) {
14453                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14454            }
14455        }
14456    }
14457
14458    @Override
14459    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14460            int sourceUserId, int targetUserId, int flags) {
14461        mContext.enforceCallingOrSelfPermission(
14462                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14463        int callingUid = Binder.getCallingUid();
14464        enforceOwnerRights(ownerPackage, callingUid);
14465        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14466        if (intentFilter.countActions() == 0) {
14467            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14468            return;
14469        }
14470        synchronized (mPackages) {
14471            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14472                    ownerPackage, targetUserId, flags);
14473            CrossProfileIntentResolver resolver =
14474                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14475            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14476            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14477            if (existing != null) {
14478                int size = existing.size();
14479                for (int i = 0; i < size; i++) {
14480                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14481                        return;
14482                    }
14483                }
14484            }
14485            resolver.addFilter(newFilter);
14486            scheduleWritePackageRestrictionsLocked(sourceUserId);
14487        }
14488    }
14489
14490    @Override
14491    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14492        mContext.enforceCallingOrSelfPermission(
14493                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14494        int callingUid = Binder.getCallingUid();
14495        enforceOwnerRights(ownerPackage, callingUid);
14496        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14497        synchronized (mPackages) {
14498            CrossProfileIntentResolver resolver =
14499                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14500            ArraySet<CrossProfileIntentFilter> set =
14501                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14502            for (CrossProfileIntentFilter filter : set) {
14503                if (filter.getOwnerPackage().equals(ownerPackage)) {
14504                    resolver.removeFilter(filter);
14505                }
14506            }
14507            scheduleWritePackageRestrictionsLocked(sourceUserId);
14508        }
14509    }
14510
14511    // Enforcing that callingUid is owning pkg on userId
14512    private void enforceOwnerRights(String pkg, int callingUid) {
14513        // The system owns everything.
14514        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14515            return;
14516        }
14517        int callingUserId = UserHandle.getUserId(callingUid);
14518        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14519        if (pi == null) {
14520            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14521                    + callingUserId);
14522        }
14523        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14524            throw new SecurityException("Calling uid " + callingUid
14525                    + " does not own package " + pkg);
14526        }
14527    }
14528
14529    @Override
14530    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14531        Intent intent = new Intent(Intent.ACTION_MAIN);
14532        intent.addCategory(Intent.CATEGORY_HOME);
14533
14534        final int callingUserId = UserHandle.getCallingUserId();
14535        List<ResolveInfo> list = queryIntentActivities(intent, null,
14536                PackageManager.GET_META_DATA, callingUserId);
14537        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14538                true, false, false, callingUserId);
14539
14540        allHomeCandidates.clear();
14541        if (list != null) {
14542            for (ResolveInfo ri : list) {
14543                allHomeCandidates.add(ri);
14544            }
14545        }
14546        return (preferred == null || preferred.activityInfo == null)
14547                ? null
14548                : new ComponentName(preferred.activityInfo.packageName,
14549                        preferred.activityInfo.name);
14550    }
14551
14552    @Override
14553    public void setApplicationEnabledSetting(String appPackageName,
14554            int newState, int flags, int userId, String callingPackage) {
14555        if (!sUserManager.exists(userId)) return;
14556        if (callingPackage == null) {
14557            callingPackage = Integer.toString(Binder.getCallingUid());
14558        }
14559        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14560    }
14561
14562    @Override
14563    public void setComponentEnabledSetting(ComponentName componentName,
14564            int newState, int flags, int userId) {
14565        if (!sUserManager.exists(userId)) return;
14566        setEnabledSetting(componentName.getPackageName(),
14567                componentName.getClassName(), newState, flags, userId, null);
14568    }
14569
14570    private void setEnabledSetting(final String packageName, String className, int newState,
14571            final int flags, int userId, String callingPackage) {
14572        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14573              || newState == COMPONENT_ENABLED_STATE_ENABLED
14574              || newState == COMPONENT_ENABLED_STATE_DISABLED
14575              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14576              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14577            throw new IllegalArgumentException("Invalid new component state: "
14578                    + newState);
14579        }
14580        PackageSetting pkgSetting;
14581        final int uid = Binder.getCallingUid();
14582        final int permission = mContext.checkCallingOrSelfPermission(
14583                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14584        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14585        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14586        boolean sendNow = false;
14587        boolean isApp = (className == null);
14588        String componentName = isApp ? packageName : className;
14589        int packageUid = -1;
14590        ArrayList<String> components;
14591
14592        // writer
14593        synchronized (mPackages) {
14594            pkgSetting = mSettings.mPackages.get(packageName);
14595            if (pkgSetting == null) {
14596                if (className == null) {
14597                    throw new IllegalArgumentException(
14598                            "Unknown package: " + packageName);
14599                }
14600                throw new IllegalArgumentException(
14601                        "Unknown component: " + packageName
14602                        + "/" + className);
14603            }
14604            // Allow root and verify that userId is not being specified by a different user
14605            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14606                throw new SecurityException(
14607                        "Permission Denial: attempt to change component state from pid="
14608                        + Binder.getCallingPid()
14609                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14610            }
14611            if (className == null) {
14612                // We're dealing with an application/package level state change
14613                if (pkgSetting.getEnabled(userId) == newState) {
14614                    // Nothing to do
14615                    return;
14616                }
14617                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14618                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14619                    // Don't care about who enables an app.
14620                    callingPackage = null;
14621                }
14622                pkgSetting.setEnabled(newState, userId, callingPackage);
14623                // pkgSetting.pkg.mSetEnabled = newState;
14624            } else {
14625                // We're dealing with a component level state change
14626                // First, verify that this is a valid class name.
14627                PackageParser.Package pkg = pkgSetting.pkg;
14628                if (pkg == null || !pkg.hasComponentClassName(className)) {
14629                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14630                        throw new IllegalArgumentException("Component class " + className
14631                                + " does not exist in " + packageName);
14632                    } else {
14633                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14634                                + className + " does not exist in " + packageName);
14635                    }
14636                }
14637                switch (newState) {
14638                case COMPONENT_ENABLED_STATE_ENABLED:
14639                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14640                        return;
14641                    }
14642                    break;
14643                case COMPONENT_ENABLED_STATE_DISABLED:
14644                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14645                        return;
14646                    }
14647                    break;
14648                case COMPONENT_ENABLED_STATE_DEFAULT:
14649                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14650                        return;
14651                    }
14652                    break;
14653                default:
14654                    Slog.e(TAG, "Invalid new component state: " + newState);
14655                    return;
14656                }
14657            }
14658            scheduleWritePackageRestrictionsLocked(userId);
14659            components = mPendingBroadcasts.get(userId, packageName);
14660            final boolean newPackage = components == null;
14661            if (newPackage) {
14662                components = new ArrayList<String>();
14663            }
14664            if (!components.contains(componentName)) {
14665                components.add(componentName);
14666            }
14667            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14668                sendNow = true;
14669                // Purge entry from pending broadcast list if another one exists already
14670                // since we are sending one right away.
14671                mPendingBroadcasts.remove(userId, packageName);
14672            } else {
14673                if (newPackage) {
14674                    mPendingBroadcasts.put(userId, packageName, components);
14675                }
14676                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14677                    // Schedule a message
14678                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14679                }
14680            }
14681        }
14682
14683        long callingId = Binder.clearCallingIdentity();
14684        try {
14685            if (sendNow) {
14686                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14687                sendPackageChangedBroadcast(packageName,
14688                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14689            }
14690        } finally {
14691            Binder.restoreCallingIdentity(callingId);
14692        }
14693    }
14694
14695    private void sendPackageChangedBroadcast(String packageName,
14696            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14697        if (DEBUG_INSTALL)
14698            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14699                    + componentNames);
14700        Bundle extras = new Bundle(4);
14701        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14702        String nameList[] = new String[componentNames.size()];
14703        componentNames.toArray(nameList);
14704        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14705        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14706        extras.putInt(Intent.EXTRA_UID, packageUid);
14707        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14708                new int[] {UserHandle.getUserId(packageUid)});
14709    }
14710
14711    @Override
14712    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14713        if (!sUserManager.exists(userId)) return;
14714        final int uid = Binder.getCallingUid();
14715        final int permission = mContext.checkCallingOrSelfPermission(
14716                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14717        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14718        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14719        // writer
14720        synchronized (mPackages) {
14721            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14722                    allowedByPermission, uid, userId)) {
14723                scheduleWritePackageRestrictionsLocked(userId);
14724            }
14725        }
14726    }
14727
14728    @Override
14729    public String getInstallerPackageName(String packageName) {
14730        // reader
14731        synchronized (mPackages) {
14732            return mSettings.getInstallerPackageNameLPr(packageName);
14733        }
14734    }
14735
14736    @Override
14737    public int getApplicationEnabledSetting(String packageName, int userId) {
14738        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14739        int uid = Binder.getCallingUid();
14740        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14741        // reader
14742        synchronized (mPackages) {
14743            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14744        }
14745    }
14746
14747    @Override
14748    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14749        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14750        int uid = Binder.getCallingUid();
14751        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14752        // reader
14753        synchronized (mPackages) {
14754            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14755        }
14756    }
14757
14758    @Override
14759    public void enterSafeMode() {
14760        enforceSystemOrRoot("Only the system can request entering safe mode");
14761
14762        if (!mSystemReady) {
14763            mSafeMode = true;
14764        }
14765    }
14766
14767    @Override
14768    public void systemReady() {
14769        mSystemReady = true;
14770
14771        // Read the compatibilty setting when the system is ready.
14772        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14773                mContext.getContentResolver(),
14774                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14775        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14776        if (DEBUG_SETTINGS) {
14777            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14778        }
14779
14780        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14781
14782        synchronized (mPackages) {
14783            // Verify that all of the preferred activity components actually
14784            // exist.  It is possible for applications to be updated and at
14785            // that point remove a previously declared activity component that
14786            // had been set as a preferred activity.  We try to clean this up
14787            // the next time we encounter that preferred activity, but it is
14788            // possible for the user flow to never be able to return to that
14789            // situation so here we do a sanity check to make sure we haven't
14790            // left any junk around.
14791            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14792            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14793                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14794                removed.clear();
14795                for (PreferredActivity pa : pir.filterSet()) {
14796                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14797                        removed.add(pa);
14798                    }
14799                }
14800                if (removed.size() > 0) {
14801                    for (int r=0; r<removed.size(); r++) {
14802                        PreferredActivity pa = removed.get(r);
14803                        Slog.w(TAG, "Removing dangling preferred activity: "
14804                                + pa.mPref.mComponent);
14805                        pir.removeFilter(pa);
14806                    }
14807                    mSettings.writePackageRestrictionsLPr(
14808                            mSettings.mPreferredActivities.keyAt(i));
14809                }
14810            }
14811
14812            for (int userId : UserManagerService.getInstance().getUserIds()) {
14813                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14814                    grantPermissionsUserIds = ArrayUtils.appendInt(
14815                            grantPermissionsUserIds, userId);
14816                }
14817            }
14818        }
14819        sUserManager.systemReady();
14820
14821        // If we upgraded grant all default permissions before kicking off.
14822        for (int userId : grantPermissionsUserIds) {
14823            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14824        }
14825
14826        // Kick off any messages waiting for system ready
14827        if (mPostSystemReadyMessages != null) {
14828            for (Message msg : mPostSystemReadyMessages) {
14829                msg.sendToTarget();
14830            }
14831            mPostSystemReadyMessages = null;
14832        }
14833
14834        // Watch for external volumes that come and go over time
14835        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14836        storage.registerListener(mStorageListener);
14837
14838        mInstallerService.systemReady();
14839        mPackageDexOptimizer.systemReady();
14840
14841        MountServiceInternal mountServiceInternal = LocalServices.getService(
14842                MountServiceInternal.class);
14843        mountServiceInternal.addExternalStoragePolicy(
14844                new MountServiceInternal.ExternalStorageMountPolicy() {
14845            @Override
14846            public int getMountMode(int uid, String packageName) {
14847                if (Process.isIsolated(uid)) {
14848                    return Zygote.MOUNT_EXTERNAL_NONE;
14849                }
14850                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14851                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14852                }
14853                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14854                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14855                }
14856                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14857                    return Zygote.MOUNT_EXTERNAL_READ;
14858                }
14859                return Zygote.MOUNT_EXTERNAL_WRITE;
14860            }
14861
14862            @Override
14863            public boolean hasExternalStorage(int uid, String packageName) {
14864                return true;
14865            }
14866        });
14867    }
14868
14869    @Override
14870    public boolean isSafeMode() {
14871        return mSafeMode;
14872    }
14873
14874    @Override
14875    public boolean hasSystemUidErrors() {
14876        return mHasSystemUidErrors;
14877    }
14878
14879    static String arrayToString(int[] array) {
14880        StringBuffer buf = new StringBuffer(128);
14881        buf.append('[');
14882        if (array != null) {
14883            for (int i=0; i<array.length; i++) {
14884                if (i > 0) buf.append(", ");
14885                buf.append(array[i]);
14886            }
14887        }
14888        buf.append(']');
14889        return buf.toString();
14890    }
14891
14892    static class DumpState {
14893        public static final int DUMP_LIBS = 1 << 0;
14894        public static final int DUMP_FEATURES = 1 << 1;
14895        public static final int DUMP_RESOLVERS = 1 << 2;
14896        public static final int DUMP_PERMISSIONS = 1 << 3;
14897        public static final int DUMP_PACKAGES = 1 << 4;
14898        public static final int DUMP_SHARED_USERS = 1 << 5;
14899        public static final int DUMP_MESSAGES = 1 << 6;
14900        public static final int DUMP_PROVIDERS = 1 << 7;
14901        public static final int DUMP_VERIFIERS = 1 << 8;
14902        public static final int DUMP_PREFERRED = 1 << 9;
14903        public static final int DUMP_PREFERRED_XML = 1 << 10;
14904        public static final int DUMP_KEYSETS = 1 << 11;
14905        public static final int DUMP_VERSION = 1 << 12;
14906        public static final int DUMP_INSTALLS = 1 << 13;
14907        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14908        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14909
14910        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14911
14912        private int mTypes;
14913
14914        private int mOptions;
14915
14916        private boolean mTitlePrinted;
14917
14918        private SharedUserSetting mSharedUser;
14919
14920        public boolean isDumping(int type) {
14921            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14922                return true;
14923            }
14924
14925            return (mTypes & type) != 0;
14926        }
14927
14928        public void setDump(int type) {
14929            mTypes |= type;
14930        }
14931
14932        public boolean isOptionEnabled(int option) {
14933            return (mOptions & option) != 0;
14934        }
14935
14936        public void setOptionEnabled(int option) {
14937            mOptions |= option;
14938        }
14939
14940        public boolean onTitlePrinted() {
14941            final boolean printed = mTitlePrinted;
14942            mTitlePrinted = true;
14943            return printed;
14944        }
14945
14946        public boolean getTitlePrinted() {
14947            return mTitlePrinted;
14948        }
14949
14950        public void setTitlePrinted(boolean enabled) {
14951            mTitlePrinted = enabled;
14952        }
14953
14954        public SharedUserSetting getSharedUser() {
14955            return mSharedUser;
14956        }
14957
14958        public void setSharedUser(SharedUserSetting user) {
14959            mSharedUser = user;
14960        }
14961    }
14962
14963    @Override
14964    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14965        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14966                != PackageManager.PERMISSION_GRANTED) {
14967            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14968                    + Binder.getCallingPid()
14969                    + ", uid=" + Binder.getCallingUid()
14970                    + " without permission "
14971                    + android.Manifest.permission.DUMP);
14972            return;
14973        }
14974
14975        DumpState dumpState = new DumpState();
14976        boolean fullPreferred = false;
14977        boolean checkin = false;
14978
14979        String packageName = null;
14980        ArraySet<String> permissionNames = null;
14981
14982        int opti = 0;
14983        while (opti < args.length) {
14984            String opt = args[opti];
14985            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14986                break;
14987            }
14988            opti++;
14989
14990            if ("-a".equals(opt)) {
14991                // Right now we only know how to print all.
14992            } else if ("-h".equals(opt)) {
14993                pw.println("Package manager dump options:");
14994                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14995                pw.println("    --checkin: dump for a checkin");
14996                pw.println("    -f: print details of intent filters");
14997                pw.println("    -h: print this help");
14998                pw.println("  cmd may be one of:");
14999                pw.println("    l[ibraries]: list known shared libraries");
15000                pw.println("    f[ibraries]: list device features");
15001                pw.println("    k[eysets]: print known keysets");
15002                pw.println("    r[esolvers]: dump intent resolvers");
15003                pw.println("    perm[issions]: dump permissions");
15004                pw.println("    permission [name ...]: dump declaration and use of given permission");
15005                pw.println("    pref[erred]: print preferred package settings");
15006                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15007                pw.println("    prov[iders]: dump content providers");
15008                pw.println("    p[ackages]: dump installed packages");
15009                pw.println("    s[hared-users]: dump shared user IDs");
15010                pw.println("    m[essages]: print collected runtime messages");
15011                pw.println("    v[erifiers]: print package verifier info");
15012                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15013                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15014                pw.println("    version: print database version info");
15015                pw.println("    write: write current settings now");
15016                pw.println("    installs: details about install sessions");
15017                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15018                pw.println("    <package.name>: info about given package");
15019                return;
15020            } else if ("--checkin".equals(opt)) {
15021                checkin = true;
15022            } else if ("-f".equals(opt)) {
15023                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15024            } else {
15025                pw.println("Unknown argument: " + opt + "; use -h for help");
15026            }
15027        }
15028
15029        // Is the caller requesting to dump a particular piece of data?
15030        if (opti < args.length) {
15031            String cmd = args[opti];
15032            opti++;
15033            // Is this a package name?
15034            if ("android".equals(cmd) || cmd.contains(".")) {
15035                packageName = cmd;
15036                // When dumping a single package, we always dump all of its
15037                // filter information since the amount of data will be reasonable.
15038                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15039            } else if ("check-permission".equals(cmd)) {
15040                if (opti >= args.length) {
15041                    pw.println("Error: check-permission missing permission argument");
15042                    return;
15043                }
15044                String perm = args[opti];
15045                opti++;
15046                if (opti >= args.length) {
15047                    pw.println("Error: check-permission missing package argument");
15048                    return;
15049                }
15050                String pkg = args[opti];
15051                opti++;
15052                int user = UserHandle.getUserId(Binder.getCallingUid());
15053                if (opti < args.length) {
15054                    try {
15055                        user = Integer.parseInt(args[opti]);
15056                    } catch (NumberFormatException e) {
15057                        pw.println("Error: check-permission user argument is not a number: "
15058                                + args[opti]);
15059                        return;
15060                    }
15061                }
15062                pw.println(checkPermission(perm, pkg, user));
15063                return;
15064            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15065                dumpState.setDump(DumpState.DUMP_LIBS);
15066            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15067                dumpState.setDump(DumpState.DUMP_FEATURES);
15068            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15069                dumpState.setDump(DumpState.DUMP_RESOLVERS);
15070            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15071                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15072            } else if ("permission".equals(cmd)) {
15073                if (opti >= args.length) {
15074                    pw.println("Error: permission requires permission name");
15075                    return;
15076                }
15077                permissionNames = new ArraySet<>();
15078                while (opti < args.length) {
15079                    permissionNames.add(args[opti]);
15080                    opti++;
15081                }
15082                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15083                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15084            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15085                dumpState.setDump(DumpState.DUMP_PREFERRED);
15086            } else if ("preferred-xml".equals(cmd)) {
15087                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15088                if (opti < args.length && "--full".equals(args[opti])) {
15089                    fullPreferred = true;
15090                    opti++;
15091                }
15092            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15093                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15094            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15095                dumpState.setDump(DumpState.DUMP_PACKAGES);
15096            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15097                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15098            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15099                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15100            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15101                dumpState.setDump(DumpState.DUMP_MESSAGES);
15102            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15103                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15104            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15105                    || "intent-filter-verifiers".equals(cmd)) {
15106                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15107            } else if ("version".equals(cmd)) {
15108                dumpState.setDump(DumpState.DUMP_VERSION);
15109            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15110                dumpState.setDump(DumpState.DUMP_KEYSETS);
15111            } else if ("installs".equals(cmd)) {
15112                dumpState.setDump(DumpState.DUMP_INSTALLS);
15113            } else if ("write".equals(cmd)) {
15114                synchronized (mPackages) {
15115                    mSettings.writeLPr();
15116                    pw.println("Settings written.");
15117                    return;
15118                }
15119            }
15120        }
15121
15122        if (checkin) {
15123            pw.println("vers,1");
15124        }
15125
15126        // reader
15127        synchronized (mPackages) {
15128            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15129                if (!checkin) {
15130                    if (dumpState.onTitlePrinted())
15131                        pw.println();
15132                    pw.println("Database versions:");
15133                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15134                }
15135            }
15136
15137            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15138                if (!checkin) {
15139                    if (dumpState.onTitlePrinted())
15140                        pw.println();
15141                    pw.println("Verifiers:");
15142                    pw.print("  Required: ");
15143                    pw.print(mRequiredVerifierPackage);
15144                    pw.print(" (uid=");
15145                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15146                    pw.println(")");
15147                } else if (mRequiredVerifierPackage != null) {
15148                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15149                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15150                }
15151            }
15152
15153            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15154                    packageName == null) {
15155                if (mIntentFilterVerifierComponent != null) {
15156                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15157                    if (!checkin) {
15158                        if (dumpState.onTitlePrinted())
15159                            pw.println();
15160                        pw.println("Intent Filter Verifier:");
15161                        pw.print("  Using: ");
15162                        pw.print(verifierPackageName);
15163                        pw.print(" (uid=");
15164                        pw.print(getPackageUid(verifierPackageName, 0));
15165                        pw.println(")");
15166                    } else if (verifierPackageName != null) {
15167                        pw.print("ifv,"); pw.print(verifierPackageName);
15168                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15169                    }
15170                } else {
15171                    pw.println();
15172                    pw.println("No Intent Filter Verifier available!");
15173                }
15174            }
15175
15176            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15177                boolean printedHeader = false;
15178                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15179                while (it.hasNext()) {
15180                    String name = it.next();
15181                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15182                    if (!checkin) {
15183                        if (!printedHeader) {
15184                            if (dumpState.onTitlePrinted())
15185                                pw.println();
15186                            pw.println("Libraries:");
15187                            printedHeader = true;
15188                        }
15189                        pw.print("  ");
15190                    } else {
15191                        pw.print("lib,");
15192                    }
15193                    pw.print(name);
15194                    if (!checkin) {
15195                        pw.print(" -> ");
15196                    }
15197                    if (ent.path != null) {
15198                        if (!checkin) {
15199                            pw.print("(jar) ");
15200                            pw.print(ent.path);
15201                        } else {
15202                            pw.print(",jar,");
15203                            pw.print(ent.path);
15204                        }
15205                    } else {
15206                        if (!checkin) {
15207                            pw.print("(apk) ");
15208                            pw.print(ent.apk);
15209                        } else {
15210                            pw.print(",apk,");
15211                            pw.print(ent.apk);
15212                        }
15213                    }
15214                    pw.println();
15215                }
15216            }
15217
15218            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15219                if (dumpState.onTitlePrinted())
15220                    pw.println();
15221                if (!checkin) {
15222                    pw.println("Features:");
15223                }
15224                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15225                while (it.hasNext()) {
15226                    String name = it.next();
15227                    if (!checkin) {
15228                        pw.print("  ");
15229                    } else {
15230                        pw.print("feat,");
15231                    }
15232                    pw.println(name);
15233                }
15234            }
15235
15236            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
15237                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15238                        : "Activity Resolver Table:", "  ", packageName,
15239                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15240                    dumpState.setTitlePrinted(true);
15241                }
15242                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15243                        : "Receiver Resolver Table:", "  ", packageName,
15244                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15245                    dumpState.setTitlePrinted(true);
15246                }
15247                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15248                        : "Service Resolver Table:", "  ", packageName,
15249                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15250                    dumpState.setTitlePrinted(true);
15251                }
15252                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15253                        : "Provider Resolver Table:", "  ", packageName,
15254                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15255                    dumpState.setTitlePrinted(true);
15256                }
15257            }
15258
15259            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15260                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15261                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15262                    int user = mSettings.mPreferredActivities.keyAt(i);
15263                    if (pir.dump(pw,
15264                            dumpState.getTitlePrinted()
15265                                ? "\nPreferred Activities User " + user + ":"
15266                                : "Preferred Activities User " + user + ":", "  ",
15267                            packageName, true, false)) {
15268                        dumpState.setTitlePrinted(true);
15269                    }
15270                }
15271            }
15272
15273            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15274                pw.flush();
15275                FileOutputStream fout = new FileOutputStream(fd);
15276                BufferedOutputStream str = new BufferedOutputStream(fout);
15277                XmlSerializer serializer = new FastXmlSerializer();
15278                try {
15279                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15280                    serializer.startDocument(null, true);
15281                    serializer.setFeature(
15282                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15283                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15284                    serializer.endDocument();
15285                    serializer.flush();
15286                } catch (IllegalArgumentException e) {
15287                    pw.println("Failed writing: " + e);
15288                } catch (IllegalStateException e) {
15289                    pw.println("Failed writing: " + e);
15290                } catch (IOException e) {
15291                    pw.println("Failed writing: " + e);
15292                }
15293            }
15294
15295            if (!checkin
15296                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15297                    && packageName == null) {
15298                pw.println();
15299                int count = mSettings.mPackages.size();
15300                if (count == 0) {
15301                    pw.println("No applications!");
15302                    pw.println();
15303                } else {
15304                    final String prefix = "  ";
15305                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15306                    if (allPackageSettings.size() == 0) {
15307                        pw.println("No domain preferred apps!");
15308                        pw.println();
15309                    } else {
15310                        pw.println("App verification status:");
15311                        pw.println();
15312                        count = 0;
15313                        for (PackageSetting ps : allPackageSettings) {
15314                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15315                            if (ivi == null || ivi.getPackageName() == null) continue;
15316                            pw.println(prefix + "Package: " + ivi.getPackageName());
15317                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15318                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15319                            pw.println();
15320                            count++;
15321                        }
15322                        if (count == 0) {
15323                            pw.println(prefix + "No app verification established.");
15324                            pw.println();
15325                        }
15326                        for (int userId : sUserManager.getUserIds()) {
15327                            pw.println("App linkages for user " + userId + ":");
15328                            pw.println();
15329                            count = 0;
15330                            for (PackageSetting ps : allPackageSettings) {
15331                                final long status = ps.getDomainVerificationStatusForUser(userId);
15332                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15333                                    continue;
15334                                }
15335                                pw.println(prefix + "Package: " + ps.name);
15336                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15337                                String statusStr = IntentFilterVerificationInfo.
15338                                        getStatusStringFromValue(status);
15339                                pw.println(prefix + "Status:  " + statusStr);
15340                                pw.println();
15341                                count++;
15342                            }
15343                            if (count == 0) {
15344                                pw.println(prefix + "No configured app linkages.");
15345                                pw.println();
15346                            }
15347                        }
15348                    }
15349                }
15350            }
15351
15352            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15353                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15354                if (packageName == null && permissionNames == null) {
15355                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15356                        if (iperm == 0) {
15357                            if (dumpState.onTitlePrinted())
15358                                pw.println();
15359                            pw.println("AppOp Permissions:");
15360                        }
15361                        pw.print("  AppOp Permission ");
15362                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15363                        pw.println(":");
15364                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15365                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15366                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15367                        }
15368                    }
15369                }
15370            }
15371
15372            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15373                boolean printedSomething = false;
15374                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15375                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15376                        continue;
15377                    }
15378                    if (!printedSomething) {
15379                        if (dumpState.onTitlePrinted())
15380                            pw.println();
15381                        pw.println("Registered ContentProviders:");
15382                        printedSomething = true;
15383                    }
15384                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15385                    pw.print("    "); pw.println(p.toString());
15386                }
15387                printedSomething = false;
15388                for (Map.Entry<String, PackageParser.Provider> entry :
15389                        mProvidersByAuthority.entrySet()) {
15390                    PackageParser.Provider p = entry.getValue();
15391                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15392                        continue;
15393                    }
15394                    if (!printedSomething) {
15395                        if (dumpState.onTitlePrinted())
15396                            pw.println();
15397                        pw.println("ContentProvider Authorities:");
15398                        printedSomething = true;
15399                    }
15400                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15401                    pw.print("    "); pw.println(p.toString());
15402                    if (p.info != null && p.info.applicationInfo != null) {
15403                        final String appInfo = p.info.applicationInfo.toString();
15404                        pw.print("      applicationInfo="); pw.println(appInfo);
15405                    }
15406                }
15407            }
15408
15409            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15410                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15411            }
15412
15413            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15414                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15415            }
15416
15417            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15418                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15419            }
15420
15421            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15422                // XXX should handle packageName != null by dumping only install data that
15423                // the given package is involved with.
15424                if (dumpState.onTitlePrinted()) pw.println();
15425                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15426            }
15427
15428            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15429                if (dumpState.onTitlePrinted()) pw.println();
15430                mSettings.dumpReadMessagesLPr(pw, dumpState);
15431
15432                pw.println();
15433                pw.println("Package warning messages:");
15434                BufferedReader in = null;
15435                String line = null;
15436                try {
15437                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15438                    while ((line = in.readLine()) != null) {
15439                        if (line.contains("ignored: updated version")) continue;
15440                        pw.println(line);
15441                    }
15442                } catch (IOException ignored) {
15443                } finally {
15444                    IoUtils.closeQuietly(in);
15445                }
15446            }
15447
15448            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15449                BufferedReader in = null;
15450                String line = null;
15451                try {
15452                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15453                    while ((line = in.readLine()) != null) {
15454                        if (line.contains("ignored: updated version")) continue;
15455                        pw.print("msg,");
15456                        pw.println(line);
15457                    }
15458                } catch (IOException ignored) {
15459                } finally {
15460                    IoUtils.closeQuietly(in);
15461                }
15462            }
15463        }
15464    }
15465
15466    private String dumpDomainString(String packageName) {
15467        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15468        List<IntentFilter> filters = getAllIntentFilters(packageName);
15469
15470        ArraySet<String> result = new ArraySet<>();
15471        if (iviList.size() > 0) {
15472            for (IntentFilterVerificationInfo ivi : iviList) {
15473                for (String host : ivi.getDomains()) {
15474                    result.add(host);
15475                }
15476            }
15477        }
15478        if (filters != null && filters.size() > 0) {
15479            for (IntentFilter filter : filters) {
15480                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15481                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15482                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15483                    result.addAll(filter.getHostsList());
15484                }
15485            }
15486        }
15487
15488        StringBuilder sb = new StringBuilder(result.size() * 16);
15489        for (String domain : result) {
15490            if (sb.length() > 0) sb.append(" ");
15491            sb.append(domain);
15492        }
15493        return sb.toString();
15494    }
15495
15496    // ------- apps on sdcard specific code -------
15497    static final boolean DEBUG_SD_INSTALL = false;
15498
15499    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15500
15501    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15502
15503    private boolean mMediaMounted = false;
15504
15505    static String getEncryptKey() {
15506        try {
15507            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15508                    SD_ENCRYPTION_KEYSTORE_NAME);
15509            if (sdEncKey == null) {
15510                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15511                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15512                if (sdEncKey == null) {
15513                    Slog.e(TAG, "Failed to create encryption keys");
15514                    return null;
15515                }
15516            }
15517            return sdEncKey;
15518        } catch (NoSuchAlgorithmException nsae) {
15519            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15520            return null;
15521        } catch (IOException ioe) {
15522            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15523            return null;
15524        }
15525    }
15526
15527    /*
15528     * Update media status on PackageManager.
15529     */
15530    @Override
15531    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15532        int callingUid = Binder.getCallingUid();
15533        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15534            throw new SecurityException("Media status can only be updated by the system");
15535        }
15536        // reader; this apparently protects mMediaMounted, but should probably
15537        // be a different lock in that case.
15538        synchronized (mPackages) {
15539            Log.i(TAG, "Updating external media status from "
15540                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15541                    + (mediaStatus ? "mounted" : "unmounted"));
15542            if (DEBUG_SD_INSTALL)
15543                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15544                        + ", mMediaMounted=" + mMediaMounted);
15545            if (mediaStatus == mMediaMounted) {
15546                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15547                        : 0, -1);
15548                mHandler.sendMessage(msg);
15549                return;
15550            }
15551            mMediaMounted = mediaStatus;
15552        }
15553        // Queue up an async operation since the package installation may take a
15554        // little while.
15555        mHandler.post(new Runnable() {
15556            public void run() {
15557                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15558            }
15559        });
15560    }
15561
15562    /**
15563     * Called by MountService when the initial ASECs to scan are available.
15564     * Should block until all the ASEC containers are finished being scanned.
15565     */
15566    public void scanAvailableAsecs() {
15567        updateExternalMediaStatusInner(true, false, false);
15568        if (mShouldRestoreconData) {
15569            SELinuxMMAC.setRestoreconDone();
15570            mShouldRestoreconData = false;
15571        }
15572    }
15573
15574    /*
15575     * Collect information of applications on external media, map them against
15576     * existing containers and update information based on current mount status.
15577     * Please note that we always have to report status if reportStatus has been
15578     * set to true especially when unloading packages.
15579     */
15580    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15581            boolean externalStorage) {
15582        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15583        int[] uidArr = EmptyArray.INT;
15584
15585        final String[] list = PackageHelper.getSecureContainerList();
15586        if (ArrayUtils.isEmpty(list)) {
15587            Log.i(TAG, "No secure containers found");
15588        } else {
15589            // Process list of secure containers and categorize them
15590            // as active or stale based on their package internal state.
15591
15592            // reader
15593            synchronized (mPackages) {
15594                for (String cid : list) {
15595                    // Leave stages untouched for now; installer service owns them
15596                    if (PackageInstallerService.isStageName(cid)) continue;
15597
15598                    if (DEBUG_SD_INSTALL)
15599                        Log.i(TAG, "Processing container " + cid);
15600                    String pkgName = getAsecPackageName(cid);
15601                    if (pkgName == null) {
15602                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15603                        continue;
15604                    }
15605                    if (DEBUG_SD_INSTALL)
15606                        Log.i(TAG, "Looking for pkg : " + pkgName);
15607
15608                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15609                    if (ps == null) {
15610                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15611                        continue;
15612                    }
15613
15614                    /*
15615                     * Skip packages that are not external if we're unmounting
15616                     * external storage.
15617                     */
15618                    if (externalStorage && !isMounted && !isExternal(ps)) {
15619                        continue;
15620                    }
15621
15622                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15623                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15624                    // The package status is changed only if the code path
15625                    // matches between settings and the container id.
15626                    if (ps.codePathString != null
15627                            && ps.codePathString.startsWith(args.getCodePath())) {
15628                        if (DEBUG_SD_INSTALL) {
15629                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15630                                    + " at code path: " + ps.codePathString);
15631                        }
15632
15633                        // We do have a valid package installed on sdcard
15634                        processCids.put(args, ps.codePathString);
15635                        final int uid = ps.appId;
15636                        if (uid != -1) {
15637                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15638                        }
15639                    } else {
15640                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15641                                + ps.codePathString);
15642                    }
15643                }
15644            }
15645
15646            Arrays.sort(uidArr);
15647        }
15648
15649        // Process packages with valid entries.
15650        if (isMounted) {
15651            if (DEBUG_SD_INSTALL)
15652                Log.i(TAG, "Loading packages");
15653            loadMediaPackages(processCids, uidArr);
15654            startCleaningPackages();
15655            mInstallerService.onSecureContainersAvailable();
15656        } else {
15657            if (DEBUG_SD_INSTALL)
15658                Log.i(TAG, "Unloading packages");
15659            unloadMediaPackages(processCids, uidArr, reportStatus);
15660        }
15661    }
15662
15663    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15664            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15665        final int size = infos.size();
15666        final String[] packageNames = new String[size];
15667        final int[] packageUids = new int[size];
15668        for (int i = 0; i < size; i++) {
15669            final ApplicationInfo info = infos.get(i);
15670            packageNames[i] = info.packageName;
15671            packageUids[i] = info.uid;
15672        }
15673        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15674                finishedReceiver);
15675    }
15676
15677    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15678            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15679        sendResourcesChangedBroadcast(mediaStatus, replacing,
15680                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15681    }
15682
15683    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15684            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15685        int size = pkgList.length;
15686        if (size > 0) {
15687            // Send broadcasts here
15688            Bundle extras = new Bundle();
15689            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15690            if (uidArr != null) {
15691                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15692            }
15693            if (replacing) {
15694                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15695            }
15696            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15697                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15698            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15699        }
15700    }
15701
15702   /*
15703     * Look at potentially valid container ids from processCids If package
15704     * information doesn't match the one on record or package scanning fails,
15705     * the cid is added to list of removeCids. We currently don't delete stale
15706     * containers.
15707     */
15708    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15709        ArrayList<String> pkgList = new ArrayList<String>();
15710        Set<AsecInstallArgs> keys = processCids.keySet();
15711
15712        for (AsecInstallArgs args : keys) {
15713            String codePath = processCids.get(args);
15714            if (DEBUG_SD_INSTALL)
15715                Log.i(TAG, "Loading container : " + args.cid);
15716            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15717            try {
15718                // Make sure there are no container errors first.
15719                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15720                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15721                            + " when installing from sdcard");
15722                    continue;
15723                }
15724                // Check code path here.
15725                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15726                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15727                            + " does not match one in settings " + codePath);
15728                    continue;
15729                }
15730                // Parse package
15731                int parseFlags = mDefParseFlags;
15732                if (args.isExternalAsec()) {
15733                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15734                }
15735                if (args.isFwdLocked()) {
15736                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15737                }
15738
15739                synchronized (mInstallLock) {
15740                    PackageParser.Package pkg = null;
15741                    try {
15742                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
15743                    } catch (PackageManagerException e) {
15744                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15745                    }
15746                    // Scan the package
15747                    if (pkg != null) {
15748                        /*
15749                         * TODO why is the lock being held? doPostInstall is
15750                         * called in other places without the lock. This needs
15751                         * to be straightened out.
15752                         */
15753                        // writer
15754                        synchronized (mPackages) {
15755                            retCode = PackageManager.INSTALL_SUCCEEDED;
15756                            pkgList.add(pkg.packageName);
15757                            // Post process args
15758                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15759                                    pkg.applicationInfo.uid);
15760                        }
15761                    } else {
15762                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15763                    }
15764                }
15765
15766            } finally {
15767                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15768                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15769                }
15770            }
15771        }
15772        // writer
15773        synchronized (mPackages) {
15774            // If the platform SDK has changed since the last time we booted,
15775            // we need to re-grant app permission to catch any new ones that
15776            // appear. This is really a hack, and means that apps can in some
15777            // cases get permissions that the user didn't initially explicitly
15778            // allow... it would be nice to have some better way to handle
15779            // this situation.
15780            final VersionInfo ver = mSettings.getExternalVersion();
15781
15782            int updateFlags = UPDATE_PERMISSIONS_ALL;
15783            if (ver.sdkVersion != mSdkVersion) {
15784                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15785                        + mSdkVersion + "; regranting permissions for external");
15786                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15787            }
15788            updatePermissionsLPw(null, null, updateFlags);
15789
15790            // Yay, everything is now upgraded
15791            ver.forceCurrent();
15792
15793            // can downgrade to reader
15794            // Persist settings
15795            mSettings.writeLPr();
15796        }
15797        // Send a broadcast to let everyone know we are done processing
15798        if (pkgList.size() > 0) {
15799            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15800        }
15801    }
15802
15803   /*
15804     * Utility method to unload a list of specified containers
15805     */
15806    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15807        // Just unmount all valid containers.
15808        for (AsecInstallArgs arg : cidArgs) {
15809            synchronized (mInstallLock) {
15810                arg.doPostDeleteLI(false);
15811           }
15812       }
15813   }
15814
15815    /*
15816     * Unload packages mounted on external media. This involves deleting package
15817     * data from internal structures, sending broadcasts about diabled packages,
15818     * gc'ing to free up references, unmounting all secure containers
15819     * corresponding to packages on external media, and posting a
15820     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15821     * that we always have to post this message if status has been requested no
15822     * matter what.
15823     */
15824    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15825            final boolean reportStatus) {
15826        if (DEBUG_SD_INSTALL)
15827            Log.i(TAG, "unloading media packages");
15828        ArrayList<String> pkgList = new ArrayList<String>();
15829        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15830        final Set<AsecInstallArgs> keys = processCids.keySet();
15831        for (AsecInstallArgs args : keys) {
15832            String pkgName = args.getPackageName();
15833            if (DEBUG_SD_INSTALL)
15834                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15835            // Delete package internally
15836            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15837            synchronized (mInstallLock) {
15838                boolean res = deletePackageLI(pkgName, null, false, null, null,
15839                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15840                if (res) {
15841                    pkgList.add(pkgName);
15842                } else {
15843                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15844                    failedList.add(args);
15845                }
15846            }
15847        }
15848
15849        // reader
15850        synchronized (mPackages) {
15851            // We didn't update the settings after removing each package;
15852            // write them now for all packages.
15853            mSettings.writeLPr();
15854        }
15855
15856        // We have to absolutely send UPDATED_MEDIA_STATUS only
15857        // after confirming that all the receivers processed the ordered
15858        // broadcast when packages get disabled, force a gc to clean things up.
15859        // and unload all the containers.
15860        if (pkgList.size() > 0) {
15861            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15862                    new IIntentReceiver.Stub() {
15863                public void performReceive(Intent intent, int resultCode, String data,
15864                        Bundle extras, boolean ordered, boolean sticky,
15865                        int sendingUser) throws RemoteException {
15866                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15867                            reportStatus ? 1 : 0, 1, keys);
15868                    mHandler.sendMessage(msg);
15869                }
15870            });
15871        } else {
15872            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15873                    keys);
15874            mHandler.sendMessage(msg);
15875        }
15876    }
15877
15878    private void loadPrivatePackages(VolumeInfo vol) {
15879        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15880        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15881        synchronized (mInstallLock) {
15882        synchronized (mPackages) {
15883            final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid);
15884            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15885            for (PackageSetting ps : packages) {
15886                final PackageParser.Package pkg;
15887                try {
15888                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15889                    loaded.add(pkg.applicationInfo);
15890                } catch (PackageManagerException e) {
15891                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15892                }
15893
15894                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15895                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15896                }
15897            }
15898
15899            int updateFlags = UPDATE_PERMISSIONS_ALL;
15900            if (ver.sdkVersion != mSdkVersion) {
15901                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15902                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15903                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15904            }
15905            updatePermissionsLPw(null, null, updateFlags);
15906
15907            // Yay, everything is now upgraded
15908            ver.forceCurrent();
15909
15910            mSettings.writeLPr();
15911        }
15912        }
15913
15914        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15915        sendResourcesChangedBroadcast(true, false, loaded, null);
15916    }
15917
15918    private void unloadPrivatePackages(VolumeInfo vol) {
15919        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15920        synchronized (mInstallLock) {
15921        synchronized (mPackages) {
15922            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15923            for (PackageSetting ps : packages) {
15924                if (ps.pkg == null) continue;
15925
15926                final ApplicationInfo info = ps.pkg.applicationInfo;
15927                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15928                if (deletePackageLI(ps.name, null, false, null, null,
15929                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15930                    unloaded.add(info);
15931                } else {
15932                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15933                }
15934            }
15935
15936            mSettings.writeLPr();
15937        }
15938        }
15939
15940        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15941        sendResourcesChangedBroadcast(false, false, unloaded, null);
15942    }
15943
15944    /**
15945     * Examine all users present on given mounted volume, and destroy data
15946     * belonging to users that are no longer valid, or whose user ID has been
15947     * recycled.
15948     */
15949    private void reconcileUsers(String volumeUuid) {
15950        final File[] files = FileUtils
15951                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15952        for (File file : files) {
15953            if (!file.isDirectory()) continue;
15954
15955            final int userId;
15956            final UserInfo info;
15957            try {
15958                userId = Integer.parseInt(file.getName());
15959                info = sUserManager.getUserInfo(userId);
15960            } catch (NumberFormatException e) {
15961                Slog.w(TAG, "Invalid user directory " + file);
15962                continue;
15963            }
15964
15965            boolean destroyUser = false;
15966            if (info == null) {
15967                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15968                        + " because no matching user was found");
15969                destroyUser = true;
15970            } else {
15971                try {
15972                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15973                } catch (IOException e) {
15974                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15975                            + " because we failed to enforce serial number: " + e);
15976                    destroyUser = true;
15977                }
15978            }
15979
15980            if (destroyUser) {
15981                synchronized (mInstallLock) {
15982                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15983                }
15984            }
15985        }
15986
15987        final UserManager um = mContext.getSystemService(UserManager.class);
15988        for (UserInfo user : um.getUsers()) {
15989            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15990            if (userDir.exists()) continue;
15991
15992            try {
15993                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15994                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15995            } catch (IOException e) {
15996                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15997            }
15998        }
15999    }
16000
16001    /**
16002     * Examine all apps present on given mounted volume, and destroy apps that
16003     * aren't expected, either due to uninstallation or reinstallation on
16004     * another volume.
16005     */
16006    private void reconcileApps(String volumeUuid) {
16007        final File[] files = FileUtils
16008                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16009        for (File file : files) {
16010            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16011                    && !PackageInstallerService.isStageName(file.getName());
16012            if (!isPackage) {
16013                // Ignore entries which are not packages
16014                continue;
16015            }
16016
16017            boolean destroyApp = false;
16018            String packageName = null;
16019            try {
16020                final PackageLite pkg = PackageParser.parsePackageLite(file,
16021                        PackageParser.PARSE_MUST_BE_APK);
16022                packageName = pkg.packageName;
16023
16024                synchronized (mPackages) {
16025                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16026                    if (ps == null) {
16027                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16028                                + volumeUuid + " because we found no install record");
16029                        destroyApp = true;
16030                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16031                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16032                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16033                        destroyApp = true;
16034                    }
16035                }
16036
16037            } catch (PackageParserException e) {
16038                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16039                destroyApp = true;
16040            }
16041
16042            if (destroyApp) {
16043                synchronized (mInstallLock) {
16044                    if (packageName != null) {
16045                        removeDataDirsLI(volumeUuid, packageName);
16046                    }
16047                    if (file.isDirectory()) {
16048                        mInstaller.rmPackageDir(file.getAbsolutePath());
16049                    } else {
16050                        file.delete();
16051                    }
16052                }
16053            }
16054        }
16055    }
16056
16057    private void unfreezePackage(String packageName) {
16058        synchronized (mPackages) {
16059            final PackageSetting ps = mSettings.mPackages.get(packageName);
16060            if (ps != null) {
16061                ps.frozen = false;
16062            }
16063        }
16064    }
16065
16066    @Override
16067    public int movePackage(final String packageName, final String volumeUuid) {
16068        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16069
16070        final int moveId = mNextMoveId.getAndIncrement();
16071        try {
16072            movePackageInternal(packageName, volumeUuid, moveId);
16073        } catch (PackageManagerException e) {
16074            Slog.w(TAG, "Failed to move " + packageName, e);
16075            mMoveCallbacks.notifyStatusChanged(moveId,
16076                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16077        }
16078        return moveId;
16079    }
16080
16081    private void movePackageInternal(final String packageName, final String volumeUuid,
16082            final int moveId) throws PackageManagerException {
16083        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16084        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16085        final PackageManager pm = mContext.getPackageManager();
16086
16087        final boolean currentAsec;
16088        final String currentVolumeUuid;
16089        final File codeFile;
16090        final String installerPackageName;
16091        final String packageAbiOverride;
16092        final int appId;
16093        final String seinfo;
16094        final String label;
16095
16096        // reader
16097        synchronized (mPackages) {
16098            final PackageParser.Package pkg = mPackages.get(packageName);
16099            final PackageSetting ps = mSettings.mPackages.get(packageName);
16100            if (pkg == null || ps == null) {
16101                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16102            }
16103
16104            if (pkg.applicationInfo.isSystemApp()) {
16105                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16106                        "Cannot move system application");
16107            }
16108
16109            if (pkg.applicationInfo.isExternalAsec()) {
16110                currentAsec = true;
16111                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16112            } else if (pkg.applicationInfo.isForwardLocked()) {
16113                currentAsec = true;
16114                currentVolumeUuid = "forward_locked";
16115            } else {
16116                currentAsec = false;
16117                currentVolumeUuid = ps.volumeUuid;
16118
16119                final File probe = new File(pkg.codePath);
16120                final File probeOat = new File(probe, "oat");
16121                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16122                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16123                            "Move only supported for modern cluster style installs");
16124                }
16125            }
16126
16127            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16128                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16129                        "Package already moved to " + volumeUuid);
16130            }
16131
16132            if (ps.frozen) {
16133                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16134                        "Failed to move already frozen package");
16135            }
16136            ps.frozen = true;
16137
16138            codeFile = new File(pkg.codePath);
16139            installerPackageName = ps.installerPackageName;
16140            packageAbiOverride = ps.cpuAbiOverrideString;
16141            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16142            seinfo = pkg.applicationInfo.seinfo;
16143            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16144        }
16145
16146        // Now that we're guarded by frozen state, kill app during move
16147        final long token = Binder.clearCallingIdentity();
16148        try {
16149            killApplication(packageName, appId, "move pkg");
16150        } finally {
16151            Binder.restoreCallingIdentity(token);
16152        }
16153
16154        final Bundle extras = new Bundle();
16155        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16156        extras.putString(Intent.EXTRA_TITLE, label);
16157        mMoveCallbacks.notifyCreated(moveId, extras);
16158
16159        int installFlags;
16160        final boolean moveCompleteApp;
16161        final File measurePath;
16162
16163        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16164            installFlags = INSTALL_INTERNAL;
16165            moveCompleteApp = !currentAsec;
16166            measurePath = Environment.getDataAppDirectory(volumeUuid);
16167        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16168            installFlags = INSTALL_EXTERNAL;
16169            moveCompleteApp = false;
16170            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16171        } else {
16172            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16173            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16174                    || !volume.isMountedWritable()) {
16175                unfreezePackage(packageName);
16176                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16177                        "Move location not mounted private volume");
16178            }
16179
16180            Preconditions.checkState(!currentAsec);
16181
16182            installFlags = INSTALL_INTERNAL;
16183            moveCompleteApp = true;
16184            measurePath = Environment.getDataAppDirectory(volumeUuid);
16185        }
16186
16187        final PackageStats stats = new PackageStats(null, -1);
16188        synchronized (mInstaller) {
16189            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16190                unfreezePackage(packageName);
16191                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16192                        "Failed to measure package size");
16193            }
16194        }
16195
16196        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16197                + stats.dataSize);
16198
16199        final long startFreeBytes = measurePath.getFreeSpace();
16200        final long sizeBytes;
16201        if (moveCompleteApp) {
16202            sizeBytes = stats.codeSize + stats.dataSize;
16203        } else {
16204            sizeBytes = stats.codeSize;
16205        }
16206
16207        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16208            unfreezePackage(packageName);
16209            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16210                    "Not enough free space to move");
16211        }
16212
16213        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16214
16215        final CountDownLatch installedLatch = new CountDownLatch(1);
16216        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16217            @Override
16218            public void onUserActionRequired(Intent intent) throws RemoteException {
16219                throw new IllegalStateException();
16220            }
16221
16222            @Override
16223            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16224                    Bundle extras) throws RemoteException {
16225                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16226                        + PackageManager.installStatusToString(returnCode, msg));
16227
16228                installedLatch.countDown();
16229
16230                // Regardless of success or failure of the move operation,
16231                // always unfreeze the package
16232                unfreezePackage(packageName);
16233
16234                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16235                switch (status) {
16236                    case PackageInstaller.STATUS_SUCCESS:
16237                        mMoveCallbacks.notifyStatusChanged(moveId,
16238                                PackageManager.MOVE_SUCCEEDED);
16239                        break;
16240                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16241                        mMoveCallbacks.notifyStatusChanged(moveId,
16242                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16243                        break;
16244                    default:
16245                        mMoveCallbacks.notifyStatusChanged(moveId,
16246                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16247                        break;
16248                }
16249            }
16250        };
16251
16252        final MoveInfo move;
16253        if (moveCompleteApp) {
16254            // Kick off a thread to report progress estimates
16255            new Thread() {
16256                @Override
16257                public void run() {
16258                    while (true) {
16259                        try {
16260                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16261                                break;
16262                            }
16263                        } catch (InterruptedException ignored) {
16264                        }
16265
16266                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16267                        final int progress = 10 + (int) MathUtils.constrain(
16268                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16269                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16270                    }
16271                }
16272            }.start();
16273
16274            final String dataAppName = codeFile.getName();
16275            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16276                    dataAppName, appId, seinfo);
16277        } else {
16278            move = null;
16279        }
16280
16281        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16282
16283        final Message msg = mHandler.obtainMessage(INIT_COPY);
16284        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16285        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16286                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16287        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16288        msg.obj = params;
16289
16290        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16291                System.identityHashCode(msg.obj));
16292        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16293                System.identityHashCode(msg.obj));
16294
16295        mHandler.sendMessage(msg);
16296    }
16297
16298    @Override
16299    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16300        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16301
16302        final int realMoveId = mNextMoveId.getAndIncrement();
16303        final Bundle extras = new Bundle();
16304        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16305        mMoveCallbacks.notifyCreated(realMoveId, extras);
16306
16307        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16308            @Override
16309            public void onCreated(int moveId, Bundle extras) {
16310                // Ignored
16311            }
16312
16313            @Override
16314            public void onStatusChanged(int moveId, int status, long estMillis) {
16315                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16316            }
16317        };
16318
16319        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16320        storage.setPrimaryStorageUuid(volumeUuid, callback);
16321        return realMoveId;
16322    }
16323
16324    @Override
16325    public int getMoveStatus(int moveId) {
16326        mContext.enforceCallingOrSelfPermission(
16327                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16328        return mMoveCallbacks.mLastStatus.get(moveId);
16329    }
16330
16331    @Override
16332    public void registerMoveCallback(IPackageMoveObserver callback) {
16333        mContext.enforceCallingOrSelfPermission(
16334                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16335        mMoveCallbacks.register(callback);
16336    }
16337
16338    @Override
16339    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16340        mContext.enforceCallingOrSelfPermission(
16341                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16342        mMoveCallbacks.unregister(callback);
16343    }
16344
16345    @Override
16346    public boolean setInstallLocation(int loc) {
16347        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16348                null);
16349        if (getInstallLocation() == loc) {
16350            return true;
16351        }
16352        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16353                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16354            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16355                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16356            return true;
16357        }
16358        return false;
16359   }
16360
16361    @Override
16362    public int getInstallLocation() {
16363        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16364                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16365                PackageHelper.APP_INSTALL_AUTO);
16366    }
16367
16368    /** Called by UserManagerService */
16369    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16370        mDirtyUsers.remove(userHandle);
16371        mSettings.removeUserLPw(userHandle);
16372        mPendingBroadcasts.remove(userHandle);
16373        if (mInstaller != null) {
16374            // Technically, we shouldn't be doing this with the package lock
16375            // held.  However, this is very rare, and there is already so much
16376            // other disk I/O going on, that we'll let it slide for now.
16377            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16378            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16379                final String volumeUuid = vol.getFsUuid();
16380                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16381                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16382            }
16383        }
16384        mUserNeedsBadging.delete(userHandle);
16385        removeUnusedPackagesLILPw(userManager, userHandle);
16386    }
16387
16388    /**
16389     * We're removing userHandle and would like to remove any downloaded packages
16390     * that are no longer in use by any other user.
16391     * @param userHandle the user being removed
16392     */
16393    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16394        final boolean DEBUG_CLEAN_APKS = false;
16395        int [] users = userManager.getUserIdsLPr();
16396        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16397        while (psit.hasNext()) {
16398            PackageSetting ps = psit.next();
16399            if (ps.pkg == null) {
16400                continue;
16401            }
16402            final String packageName = ps.pkg.packageName;
16403            // Skip over if system app
16404            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16405                continue;
16406            }
16407            if (DEBUG_CLEAN_APKS) {
16408                Slog.i(TAG, "Checking package " + packageName);
16409            }
16410            boolean keep = false;
16411            for (int i = 0; i < users.length; i++) {
16412                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16413                    keep = true;
16414                    if (DEBUG_CLEAN_APKS) {
16415                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16416                                + users[i]);
16417                    }
16418                    break;
16419                }
16420            }
16421            if (!keep) {
16422                if (DEBUG_CLEAN_APKS) {
16423                    Slog.i(TAG, "  Removing package " + packageName);
16424                }
16425                mHandler.post(new Runnable() {
16426                    public void run() {
16427                        deletePackageX(packageName, userHandle, 0);
16428                    } //end run
16429                });
16430            }
16431        }
16432    }
16433
16434    /** Called by UserManagerService */
16435    void createNewUserLILPw(int userHandle) {
16436        if (mInstaller != null) {
16437            mInstaller.createUserConfig(userHandle);
16438            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16439            applyFactoryDefaultBrowserLPw(userHandle);
16440            primeDomainVerificationsLPw(userHandle);
16441        }
16442    }
16443
16444    void newUserCreated(final int userHandle) {
16445        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16446    }
16447
16448    @Override
16449    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16450        mContext.enforceCallingOrSelfPermission(
16451                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16452                "Only package verification agents can read the verifier device identity");
16453
16454        synchronized (mPackages) {
16455            return mSettings.getVerifierDeviceIdentityLPw();
16456        }
16457    }
16458
16459    @Override
16460    public void setPermissionEnforced(String permission, boolean enforced) {
16461        // TODO: Now that we no longer change GID for storage, this should to away.
16462        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16463                "setPermissionEnforced");
16464        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16465            synchronized (mPackages) {
16466                if (mSettings.mReadExternalStorageEnforced == null
16467                        || mSettings.mReadExternalStorageEnforced != enforced) {
16468                    mSettings.mReadExternalStorageEnforced = enforced;
16469                    mSettings.writeLPr();
16470                }
16471            }
16472            // kill any non-foreground processes so we restart them and
16473            // grant/revoke the GID.
16474            final IActivityManager am = ActivityManagerNative.getDefault();
16475            if (am != null) {
16476                final long token = Binder.clearCallingIdentity();
16477                try {
16478                    am.killProcessesBelowForeground("setPermissionEnforcement");
16479                } catch (RemoteException e) {
16480                } finally {
16481                    Binder.restoreCallingIdentity(token);
16482                }
16483            }
16484        } else {
16485            throw new IllegalArgumentException("No selective enforcement for " + permission);
16486        }
16487    }
16488
16489    @Override
16490    @Deprecated
16491    public boolean isPermissionEnforced(String permission) {
16492        return true;
16493    }
16494
16495    @Override
16496    public boolean isStorageLow() {
16497        final long token = Binder.clearCallingIdentity();
16498        try {
16499            final DeviceStorageMonitorInternal
16500                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16501            if (dsm != null) {
16502                return dsm.isMemoryLow();
16503            } else {
16504                return false;
16505            }
16506        } finally {
16507            Binder.restoreCallingIdentity(token);
16508        }
16509    }
16510
16511    @Override
16512    public IPackageInstaller getPackageInstaller() {
16513        return mInstallerService;
16514    }
16515
16516    private boolean userNeedsBadging(int userId) {
16517        int index = mUserNeedsBadging.indexOfKey(userId);
16518        if (index < 0) {
16519            final UserInfo userInfo;
16520            final long token = Binder.clearCallingIdentity();
16521            try {
16522                userInfo = sUserManager.getUserInfo(userId);
16523            } finally {
16524                Binder.restoreCallingIdentity(token);
16525            }
16526            final boolean b;
16527            if (userInfo != null && userInfo.isManagedProfile()) {
16528                b = true;
16529            } else {
16530                b = false;
16531            }
16532            mUserNeedsBadging.put(userId, b);
16533            return b;
16534        }
16535        return mUserNeedsBadging.valueAt(index);
16536    }
16537
16538    @Override
16539    public KeySet getKeySetByAlias(String packageName, String alias) {
16540        if (packageName == null || alias == null) {
16541            return null;
16542        }
16543        synchronized(mPackages) {
16544            final PackageParser.Package pkg = mPackages.get(packageName);
16545            if (pkg == null) {
16546                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16547                throw new IllegalArgumentException("Unknown package: " + packageName);
16548            }
16549            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16550            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16551        }
16552    }
16553
16554    @Override
16555    public KeySet getSigningKeySet(String packageName) {
16556        if (packageName == null) {
16557            return null;
16558        }
16559        synchronized(mPackages) {
16560            final PackageParser.Package pkg = mPackages.get(packageName);
16561            if (pkg == null) {
16562                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16563                throw new IllegalArgumentException("Unknown package: " + packageName);
16564            }
16565            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16566                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16567                throw new SecurityException("May not access signing KeySet of other apps.");
16568            }
16569            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16570            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16571        }
16572    }
16573
16574    @Override
16575    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16576        if (packageName == null || ks == null) {
16577            return false;
16578        }
16579        synchronized(mPackages) {
16580            final PackageParser.Package pkg = mPackages.get(packageName);
16581            if (pkg == null) {
16582                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16583                throw new IllegalArgumentException("Unknown package: " + packageName);
16584            }
16585            IBinder ksh = ks.getToken();
16586            if (ksh instanceof KeySetHandle) {
16587                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16588                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16589            }
16590            return false;
16591        }
16592    }
16593
16594    @Override
16595    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16596        if (packageName == null || ks == null) {
16597            return false;
16598        }
16599        synchronized(mPackages) {
16600            final PackageParser.Package pkg = mPackages.get(packageName);
16601            if (pkg == null) {
16602                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16603                throw new IllegalArgumentException("Unknown package: " + packageName);
16604            }
16605            IBinder ksh = ks.getToken();
16606            if (ksh instanceof KeySetHandle) {
16607                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16608                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16609            }
16610            return false;
16611        }
16612    }
16613
16614    public void getUsageStatsIfNoPackageUsageInfo() {
16615        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16616            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16617            if (usm == null) {
16618                throw new IllegalStateException("UsageStatsManager must be initialized");
16619            }
16620            long now = System.currentTimeMillis();
16621            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16622            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16623                String packageName = entry.getKey();
16624                PackageParser.Package pkg = mPackages.get(packageName);
16625                if (pkg == null) {
16626                    continue;
16627                }
16628                UsageStats usage = entry.getValue();
16629                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16630                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16631            }
16632        }
16633    }
16634
16635    /**
16636     * Check and throw if the given before/after packages would be considered a
16637     * downgrade.
16638     */
16639    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16640            throws PackageManagerException {
16641        if (after.versionCode < before.mVersionCode) {
16642            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16643                    "Update version code " + after.versionCode + " is older than current "
16644                    + before.mVersionCode);
16645        } else if (after.versionCode == before.mVersionCode) {
16646            if (after.baseRevisionCode < before.baseRevisionCode) {
16647                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16648                        "Update base revision code " + after.baseRevisionCode
16649                        + " is older than current " + before.baseRevisionCode);
16650            }
16651
16652            if (!ArrayUtils.isEmpty(after.splitNames)) {
16653                for (int i = 0; i < after.splitNames.length; i++) {
16654                    final String splitName = after.splitNames[i];
16655                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16656                    if (j != -1) {
16657                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16658                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16659                                    "Update split " + splitName + " revision code "
16660                                    + after.splitRevisionCodes[i] + " is older than current "
16661                                    + before.splitRevisionCodes[j]);
16662                        }
16663                    }
16664                }
16665            }
16666        }
16667    }
16668
16669    private static class MoveCallbacks extends Handler {
16670        private static final int MSG_CREATED = 1;
16671        private static final int MSG_STATUS_CHANGED = 2;
16672
16673        private final RemoteCallbackList<IPackageMoveObserver>
16674                mCallbacks = new RemoteCallbackList<>();
16675
16676        private final SparseIntArray mLastStatus = new SparseIntArray();
16677
16678        public MoveCallbacks(Looper looper) {
16679            super(looper);
16680        }
16681
16682        public void register(IPackageMoveObserver callback) {
16683            mCallbacks.register(callback);
16684        }
16685
16686        public void unregister(IPackageMoveObserver callback) {
16687            mCallbacks.unregister(callback);
16688        }
16689
16690        @Override
16691        public void handleMessage(Message msg) {
16692            final SomeArgs args = (SomeArgs) msg.obj;
16693            final int n = mCallbacks.beginBroadcast();
16694            for (int i = 0; i < n; i++) {
16695                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16696                try {
16697                    invokeCallback(callback, msg.what, args);
16698                } catch (RemoteException ignored) {
16699                }
16700            }
16701            mCallbacks.finishBroadcast();
16702            args.recycle();
16703        }
16704
16705        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16706                throws RemoteException {
16707            switch (what) {
16708                case MSG_CREATED: {
16709                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16710                    break;
16711                }
16712                case MSG_STATUS_CHANGED: {
16713                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16714                    break;
16715                }
16716            }
16717        }
16718
16719        private void notifyCreated(int moveId, Bundle extras) {
16720            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16721
16722            final SomeArgs args = SomeArgs.obtain();
16723            args.argi1 = moveId;
16724            args.arg2 = extras;
16725            obtainMessage(MSG_CREATED, args).sendToTarget();
16726        }
16727
16728        private void notifyStatusChanged(int moveId, int status) {
16729            notifyStatusChanged(moveId, status, -1);
16730        }
16731
16732        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16733            Slog.v(TAG, "Move " + moveId + " status " + status);
16734
16735            final SomeArgs args = SomeArgs.obtain();
16736            args.argi1 = moveId;
16737            args.argi2 = status;
16738            args.arg3 = estMillis;
16739            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16740
16741            synchronized (mLastStatus) {
16742                mLastStatus.put(moveId, status);
16743            }
16744        }
16745    }
16746
16747    private final class OnPermissionChangeListeners extends Handler {
16748        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16749
16750        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16751                new RemoteCallbackList<>();
16752
16753        public OnPermissionChangeListeners(Looper looper) {
16754            super(looper);
16755        }
16756
16757        @Override
16758        public void handleMessage(Message msg) {
16759            switch (msg.what) {
16760                case MSG_ON_PERMISSIONS_CHANGED: {
16761                    final int uid = msg.arg1;
16762                    handleOnPermissionsChanged(uid);
16763                } break;
16764            }
16765        }
16766
16767        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16768            mPermissionListeners.register(listener);
16769
16770        }
16771
16772        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16773            mPermissionListeners.unregister(listener);
16774        }
16775
16776        public void onPermissionsChanged(int uid) {
16777            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16778                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16779            }
16780        }
16781
16782        private void handleOnPermissionsChanged(int uid) {
16783            final int count = mPermissionListeners.beginBroadcast();
16784            try {
16785                for (int i = 0; i < count; i++) {
16786                    IOnPermissionsChangeListener callback = mPermissionListeners
16787                            .getBroadcastItem(i);
16788                    try {
16789                        callback.onPermissionsChanged(uid);
16790                    } catch (RemoteException e) {
16791                        Log.e(TAG, "Permission listener is dead", e);
16792                    }
16793                }
16794            } finally {
16795                mPermissionListeners.finishBroadcast();
16796            }
16797        }
16798    }
16799
16800    private class PackageManagerInternalImpl extends PackageManagerInternal {
16801        @Override
16802        public void setLocationPackagesProvider(PackagesProvider provider) {
16803            synchronized (mPackages) {
16804                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16805            }
16806        }
16807
16808        @Override
16809        public void setImePackagesProvider(PackagesProvider provider) {
16810            synchronized (mPackages) {
16811                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16812            }
16813        }
16814
16815        @Override
16816        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16817            synchronized (mPackages) {
16818                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16819            }
16820        }
16821
16822        @Override
16823        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16824            synchronized (mPackages) {
16825                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16826            }
16827        }
16828
16829        @Override
16830        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16831            synchronized (mPackages) {
16832                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16833            }
16834        }
16835
16836        @Override
16837        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16838            synchronized (mPackages) {
16839                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16840            }
16841        }
16842
16843        @Override
16844        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16845            synchronized (mPackages) {
16846                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16847            }
16848        }
16849
16850        @Override
16851        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16852            synchronized (mPackages) {
16853                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16854                        packageName, userId);
16855            }
16856        }
16857
16858        @Override
16859        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16860            synchronized (mPackages) {
16861                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16862                        packageName, userId);
16863            }
16864        }
16865        @Override
16866        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16867            synchronized (mPackages) {
16868                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16869                        packageName, userId);
16870            }
16871        }
16872    }
16873
16874    @Override
16875    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16876        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16877        synchronized (mPackages) {
16878            final long identity = Binder.clearCallingIdentity();
16879            try {
16880                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16881                        packageNames, userId);
16882            } finally {
16883                Binder.restoreCallingIdentity(identity);
16884            }
16885        }
16886    }
16887
16888    private static void enforceSystemOrPhoneCaller(String tag) {
16889        int callingUid = Binder.getCallingUid();
16890        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16891            throw new SecurityException(
16892                    "Cannot call " + tag + " from UID " + callingUid);
16893        }
16894    }
16895}
16896