PackageManagerService.java revision b18d084f4bb8e2f69732a014b78f6378481d9906
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, false);
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, false);
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                        false /* boot complete */);
2297            }
2298
2299            // Now that we know all the packages we are keeping,
2300            // read and update their last usage times.
2301            mPackageUsage.readLP();
2302
2303            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2304                    SystemClock.uptimeMillis());
2305            Slog.i(TAG, "Time to scan packages: "
2306                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2307                    + " seconds");
2308
2309            // If the platform SDK has changed since the last time we booted,
2310            // we need to re-grant app permission to catch any new ones that
2311            // appear.  This is really a hack, and means that apps can in some
2312            // cases get permissions that the user didn't initially explicitly
2313            // allow...  it would be nice to have some better way to handle
2314            // this situation.
2315            int updateFlags = UPDATE_PERMISSIONS_ALL;
2316            if (ver.sdkVersion != mSdkVersion) {
2317                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2318                        + mSdkVersion + "; regranting permissions for internal storage");
2319                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2320            }
2321            updatePermissionsLPw(null, null, updateFlags);
2322            ver.sdkVersion = mSdkVersion;
2323
2324            // If this is the first boot or an update from pre-M, and it is a normal
2325            // boot, then we need to initialize the default preferred apps across
2326            // all defined users.
2327            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2328                for (UserInfo user : sUserManager.getUsers(true)) {
2329                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2330                    applyFactoryDefaultBrowserLPw(user.id);
2331                    primeDomainVerificationsLPw(user.id);
2332                }
2333            }
2334
2335            // If this is first boot after an OTA, and a normal boot, then
2336            // we need to clear code cache directories.
2337            if (mIsUpgrade && !onlyCore) {
2338                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2339                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2340                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2341                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2342                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2343                    }
2344                }
2345                ver.fingerprint = Build.FINGERPRINT;
2346            }
2347
2348            checkDefaultBrowser();
2349
2350            // clear only after permissions and other defaults have been updated
2351            mExistingSystemPackages.clear();
2352            mPromoteSystemApps = false;
2353
2354            // All the changes are done during package scanning.
2355            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2356
2357            // can downgrade to reader
2358            mSettings.writeLPr();
2359
2360            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2361                    SystemClock.uptimeMillis());
2362
2363            mRequiredVerifierPackage = getRequiredVerifierLPr();
2364            mRequiredInstallerPackage = getRequiredInstallerLPr();
2365
2366            mInstallerService = new PackageInstallerService(context, this);
2367
2368            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2369            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2370                    mIntentFilterVerifierComponent);
2371
2372        } // synchronized (mPackages)
2373        } // synchronized (mInstallLock)
2374
2375        // Now after opening every single application zip, make sure they
2376        // are all flushed.  Not really needed, but keeps things nice and
2377        // tidy.
2378        Runtime.getRuntime().gc();
2379
2380        // Expose private service for system components to use.
2381        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2382    }
2383
2384    @Override
2385    public boolean isFirstBoot() {
2386        return !mRestoredSettings;
2387    }
2388
2389    @Override
2390    public boolean isOnlyCoreApps() {
2391        return mOnlyCore;
2392    }
2393
2394    @Override
2395    public boolean isUpgrade() {
2396        return mIsUpgrade;
2397    }
2398
2399    private String getRequiredVerifierLPr() {
2400        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2401        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2402                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2403
2404        String requiredVerifier = null;
2405
2406        final int N = receivers.size();
2407        for (int i = 0; i < N; i++) {
2408            final ResolveInfo info = receivers.get(i);
2409
2410            if (info.activityInfo == null) {
2411                continue;
2412            }
2413
2414            final String packageName = info.activityInfo.packageName;
2415
2416            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2417                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2418                continue;
2419            }
2420
2421            if (requiredVerifier != null) {
2422                throw new RuntimeException("There can be only one required verifier");
2423            }
2424
2425            requiredVerifier = packageName;
2426        }
2427
2428        return requiredVerifier;
2429    }
2430
2431    private String getRequiredInstallerLPr() {
2432        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2433        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2434        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2435
2436        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2437                PACKAGE_MIME_TYPE, 0, 0);
2438
2439        String requiredInstaller = null;
2440
2441        final int N = installers.size();
2442        for (int i = 0; i < N; i++) {
2443            final ResolveInfo info = installers.get(i);
2444            final String packageName = info.activityInfo.packageName;
2445
2446            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2447                continue;
2448            }
2449
2450            if (requiredInstaller != null) {
2451                throw new RuntimeException("There must be one required installer");
2452            }
2453
2454            requiredInstaller = packageName;
2455        }
2456
2457        if (requiredInstaller == null) {
2458            throw new RuntimeException("There must be one required installer");
2459        }
2460
2461        return requiredInstaller;
2462    }
2463
2464    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2465        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2466        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2467                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2468
2469        ComponentName verifierComponentName = null;
2470
2471        int priority = -1000;
2472        final int N = receivers.size();
2473        for (int i = 0; i < N; i++) {
2474            final ResolveInfo info = receivers.get(i);
2475
2476            if (info.activityInfo == null) {
2477                continue;
2478            }
2479
2480            final String packageName = info.activityInfo.packageName;
2481
2482            final PackageSetting ps = mSettings.mPackages.get(packageName);
2483            if (ps == null) {
2484                continue;
2485            }
2486
2487            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2488                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2489                continue;
2490            }
2491
2492            // Select the IntentFilterVerifier with the highest priority
2493            if (priority < info.priority) {
2494                priority = info.priority;
2495                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2496                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2497                        + verifierComponentName + " with priority: " + info.priority);
2498            }
2499        }
2500
2501        return verifierComponentName;
2502    }
2503
2504    private void primeDomainVerificationsLPw(int userId) {
2505        if (DEBUG_DOMAIN_VERIFICATION) {
2506            Slog.d(TAG, "Priming domain verifications in user " + userId);
2507        }
2508
2509        SystemConfig systemConfig = SystemConfig.getInstance();
2510        ArraySet<String> packages = systemConfig.getLinkedApps();
2511        ArraySet<String> domains = new ArraySet<String>();
2512
2513        for (String packageName : packages) {
2514            PackageParser.Package pkg = mPackages.get(packageName);
2515            if (pkg != null) {
2516                if (!pkg.isSystemApp()) {
2517                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2518                    continue;
2519                }
2520
2521                domains.clear();
2522                for (PackageParser.Activity a : pkg.activities) {
2523                    for (ActivityIntentInfo filter : a.intents) {
2524                        if (hasValidDomains(filter)) {
2525                            domains.addAll(filter.getHostsList());
2526                        }
2527                    }
2528                }
2529
2530                if (domains.size() > 0) {
2531                    if (DEBUG_DOMAIN_VERIFICATION) {
2532                        Slog.v(TAG, "      + " + packageName);
2533                    }
2534                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2535                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2536                    // and then 'always' in the per-user state actually used for intent resolution.
2537                    final IntentFilterVerificationInfo ivi;
2538                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2539                            new ArrayList<String>(domains));
2540                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2541                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2542                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2543                } else {
2544                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2545                            + "' does not handle web links");
2546                }
2547            } else {
2548                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2549            }
2550        }
2551
2552        scheduleWritePackageRestrictionsLocked(userId);
2553        scheduleWriteSettingsLocked();
2554    }
2555
2556    private void applyFactoryDefaultBrowserLPw(int userId) {
2557        // The default browser app's package name is stored in a string resource,
2558        // with a product-specific overlay used for vendor customization.
2559        String browserPkg = mContext.getResources().getString(
2560                com.android.internal.R.string.default_browser);
2561        if (!TextUtils.isEmpty(browserPkg)) {
2562            // non-empty string => required to be a known package
2563            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2564            if (ps == null) {
2565                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2566                browserPkg = null;
2567            } else {
2568                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2569            }
2570        }
2571
2572        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2573        // default.  If there's more than one, just leave everything alone.
2574        if (browserPkg == null) {
2575            calculateDefaultBrowserLPw(userId);
2576        }
2577    }
2578
2579    private void calculateDefaultBrowserLPw(int userId) {
2580        List<String> allBrowsers = resolveAllBrowserApps(userId);
2581        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2582        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2583    }
2584
2585    private List<String> resolveAllBrowserApps(int userId) {
2586        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2587        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2588                PackageManager.MATCH_ALL, userId);
2589
2590        final int count = list.size();
2591        List<String> result = new ArrayList<String>(count);
2592        for (int i=0; i<count; i++) {
2593            ResolveInfo info = list.get(i);
2594            if (info.activityInfo == null
2595                    || !info.handleAllWebDataURI
2596                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2597                    || result.contains(info.activityInfo.packageName)) {
2598                continue;
2599            }
2600            result.add(info.activityInfo.packageName);
2601        }
2602
2603        return result;
2604    }
2605
2606    private boolean packageIsBrowser(String packageName, int userId) {
2607        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2608                PackageManager.MATCH_ALL, userId);
2609        final int N = list.size();
2610        for (int i = 0; i < N; i++) {
2611            ResolveInfo info = list.get(i);
2612            if (packageName.equals(info.activityInfo.packageName)) {
2613                return true;
2614            }
2615        }
2616        return false;
2617    }
2618
2619    private void checkDefaultBrowser() {
2620        final int myUserId = UserHandle.myUserId();
2621        final String packageName = getDefaultBrowserPackageName(myUserId);
2622        if (packageName != null) {
2623            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2624            if (info == null) {
2625                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2626                synchronized (mPackages) {
2627                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2628                }
2629            }
2630        }
2631    }
2632
2633    @Override
2634    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2635            throws RemoteException {
2636        try {
2637            return super.onTransact(code, data, reply, flags);
2638        } catch (RuntimeException e) {
2639            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2640                Slog.wtf(TAG, "Package Manager Crash", e);
2641            }
2642            throw e;
2643        }
2644    }
2645
2646    void cleanupInstallFailedPackage(PackageSetting ps) {
2647        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2648
2649        removeDataDirsLI(ps.volumeUuid, ps.name);
2650        if (ps.codePath != null) {
2651            if (ps.codePath.isDirectory()) {
2652                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2653            } else {
2654                ps.codePath.delete();
2655            }
2656        }
2657        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2658            if (ps.resourcePath.isDirectory()) {
2659                FileUtils.deleteContents(ps.resourcePath);
2660            }
2661            ps.resourcePath.delete();
2662        }
2663        mSettings.removePackageLPw(ps.name);
2664    }
2665
2666    static int[] appendInts(int[] cur, int[] add) {
2667        if (add == null) return cur;
2668        if (cur == null) return add;
2669        final int N = add.length;
2670        for (int i=0; i<N; i++) {
2671            cur = appendInt(cur, add[i]);
2672        }
2673        return cur;
2674    }
2675
2676    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2677        if (!sUserManager.exists(userId)) return null;
2678        final PackageSetting ps = (PackageSetting) p.mExtras;
2679        if (ps == null) {
2680            return null;
2681        }
2682
2683        final PermissionsState permissionsState = ps.getPermissionsState();
2684
2685        final int[] gids = permissionsState.computeGids(userId);
2686        final Set<String> permissions = permissionsState.getPermissions(userId);
2687        final PackageUserState state = ps.readUserState(userId);
2688
2689        return PackageParser.generatePackageInfo(p, gids, flags,
2690                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2691    }
2692
2693    @Override
2694    public boolean isPackageFrozen(String packageName) {
2695        synchronized (mPackages) {
2696            final PackageSetting ps = mSettings.mPackages.get(packageName);
2697            if (ps != null) {
2698                return ps.frozen;
2699            }
2700        }
2701        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2702        return true;
2703    }
2704
2705    @Override
2706    public boolean isPackageAvailable(String packageName, int userId) {
2707        if (!sUserManager.exists(userId)) return false;
2708        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2709        synchronized (mPackages) {
2710            PackageParser.Package p = mPackages.get(packageName);
2711            if (p != null) {
2712                final PackageSetting ps = (PackageSetting) p.mExtras;
2713                if (ps != null) {
2714                    final PackageUserState state = ps.readUserState(userId);
2715                    if (state != null) {
2716                        return PackageParser.isAvailable(state);
2717                    }
2718                }
2719            }
2720        }
2721        return false;
2722    }
2723
2724    @Override
2725    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2726        if (!sUserManager.exists(userId)) return null;
2727        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2728        // reader
2729        synchronized (mPackages) {
2730            PackageParser.Package p = mPackages.get(packageName);
2731            if (DEBUG_PACKAGE_INFO)
2732                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2733            if (p != null) {
2734                return generatePackageInfo(p, flags, userId);
2735            }
2736            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2737                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2738            }
2739        }
2740        return null;
2741    }
2742
2743    @Override
2744    public String[] currentToCanonicalPackageNames(String[] names) {
2745        String[] out = new String[names.length];
2746        // reader
2747        synchronized (mPackages) {
2748            for (int i=names.length-1; i>=0; i--) {
2749                PackageSetting ps = mSettings.mPackages.get(names[i]);
2750                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2751            }
2752        }
2753        return out;
2754    }
2755
2756    @Override
2757    public String[] canonicalToCurrentPackageNames(String[] names) {
2758        String[] out = new String[names.length];
2759        // reader
2760        synchronized (mPackages) {
2761            for (int i=names.length-1; i>=0; i--) {
2762                String cur = mSettings.mRenamedPackages.get(names[i]);
2763                out[i] = cur != null ? cur : names[i];
2764            }
2765        }
2766        return out;
2767    }
2768
2769    @Override
2770    public int getPackageUid(String packageName, int userId) {
2771        if (!sUserManager.exists(userId)) return -1;
2772        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2773
2774        // reader
2775        synchronized (mPackages) {
2776            PackageParser.Package p = mPackages.get(packageName);
2777            if(p != null) {
2778                return UserHandle.getUid(userId, p.applicationInfo.uid);
2779            }
2780            PackageSetting ps = mSettings.mPackages.get(packageName);
2781            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2782                return -1;
2783            }
2784            p = ps.pkg;
2785            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2786        }
2787    }
2788
2789    @Override
2790    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2791        if (!sUserManager.exists(userId)) {
2792            return null;
2793        }
2794
2795        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2796                "getPackageGids");
2797
2798        // reader
2799        synchronized (mPackages) {
2800            PackageParser.Package p = mPackages.get(packageName);
2801            if (DEBUG_PACKAGE_INFO) {
2802                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2803            }
2804            if (p != null) {
2805                PackageSetting ps = (PackageSetting) p.mExtras;
2806                return ps.getPermissionsState().computeGids(userId);
2807            }
2808        }
2809
2810        return null;
2811    }
2812
2813    static PermissionInfo generatePermissionInfo(
2814            BasePermission bp, int flags) {
2815        if (bp.perm != null) {
2816            return PackageParser.generatePermissionInfo(bp.perm, flags);
2817        }
2818        PermissionInfo pi = new PermissionInfo();
2819        pi.name = bp.name;
2820        pi.packageName = bp.sourcePackage;
2821        pi.nonLocalizedLabel = bp.name;
2822        pi.protectionLevel = bp.protectionLevel;
2823        return pi;
2824    }
2825
2826    @Override
2827    public PermissionInfo getPermissionInfo(String name, int flags) {
2828        // reader
2829        synchronized (mPackages) {
2830            final BasePermission p = mSettings.mPermissions.get(name);
2831            if (p != null) {
2832                return generatePermissionInfo(p, flags);
2833            }
2834            return null;
2835        }
2836    }
2837
2838    @Override
2839    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2840        // reader
2841        synchronized (mPackages) {
2842            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2843            for (BasePermission p : mSettings.mPermissions.values()) {
2844                if (group == null) {
2845                    if (p.perm == null || p.perm.info.group == null) {
2846                        out.add(generatePermissionInfo(p, flags));
2847                    }
2848                } else {
2849                    if (p.perm != null && group.equals(p.perm.info.group)) {
2850                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2851                    }
2852                }
2853            }
2854
2855            if (out.size() > 0) {
2856                return out;
2857            }
2858            return mPermissionGroups.containsKey(group) ? out : null;
2859        }
2860    }
2861
2862    @Override
2863    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2864        // reader
2865        synchronized (mPackages) {
2866            return PackageParser.generatePermissionGroupInfo(
2867                    mPermissionGroups.get(name), flags);
2868        }
2869    }
2870
2871    @Override
2872    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2873        // reader
2874        synchronized (mPackages) {
2875            final int N = mPermissionGroups.size();
2876            ArrayList<PermissionGroupInfo> out
2877                    = new ArrayList<PermissionGroupInfo>(N);
2878            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2879                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2880            }
2881            return out;
2882        }
2883    }
2884
2885    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2886            int userId) {
2887        if (!sUserManager.exists(userId)) return null;
2888        PackageSetting ps = mSettings.mPackages.get(packageName);
2889        if (ps != null) {
2890            if (ps.pkg == null) {
2891                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2892                        flags, userId);
2893                if (pInfo != null) {
2894                    return pInfo.applicationInfo;
2895                }
2896                return null;
2897            }
2898            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2899                    ps.readUserState(userId), userId);
2900        }
2901        return null;
2902    }
2903
2904    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2905            int userId) {
2906        if (!sUserManager.exists(userId)) return null;
2907        PackageSetting ps = mSettings.mPackages.get(packageName);
2908        if (ps != null) {
2909            PackageParser.Package pkg = ps.pkg;
2910            if (pkg == null) {
2911                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2912                    return null;
2913                }
2914                // Only data remains, so we aren't worried about code paths
2915                pkg = new PackageParser.Package(packageName);
2916                pkg.applicationInfo.packageName = packageName;
2917                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2918                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2919                pkg.applicationInfo.dataDir = Environment
2920                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2921                        .getAbsolutePath();
2922                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2923                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2924            }
2925            return generatePackageInfo(pkg, flags, userId);
2926        }
2927        return null;
2928    }
2929
2930    @Override
2931    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2932        if (!sUserManager.exists(userId)) return null;
2933        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2934        // writer
2935        synchronized (mPackages) {
2936            PackageParser.Package p = mPackages.get(packageName);
2937            if (DEBUG_PACKAGE_INFO) Log.v(
2938                    TAG, "getApplicationInfo " + packageName
2939                    + ": " + p);
2940            if (p != null) {
2941                PackageSetting ps = mSettings.mPackages.get(packageName);
2942                if (ps == null) return null;
2943                // Note: isEnabledLP() does not apply here - always return info
2944                return PackageParser.generateApplicationInfo(
2945                        p, flags, ps.readUserState(userId), userId);
2946            }
2947            if ("android".equals(packageName)||"system".equals(packageName)) {
2948                return mAndroidApplication;
2949            }
2950            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2951                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2952            }
2953        }
2954        return null;
2955    }
2956
2957    @Override
2958    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2959            final IPackageDataObserver observer) {
2960        mContext.enforceCallingOrSelfPermission(
2961                android.Manifest.permission.CLEAR_APP_CACHE, null);
2962        // Queue up an async operation since clearing cache may take a little while.
2963        mHandler.post(new Runnable() {
2964            public void run() {
2965                mHandler.removeCallbacks(this);
2966                int retCode = -1;
2967                synchronized (mInstallLock) {
2968                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2969                    if (retCode < 0) {
2970                        Slog.w(TAG, "Couldn't clear application caches");
2971                    }
2972                }
2973                if (observer != null) {
2974                    try {
2975                        observer.onRemoveCompleted(null, (retCode >= 0));
2976                    } catch (RemoteException e) {
2977                        Slog.w(TAG, "RemoveException when invoking call back");
2978                    }
2979                }
2980            }
2981        });
2982    }
2983
2984    @Override
2985    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2986            final IntentSender pi) {
2987        mContext.enforceCallingOrSelfPermission(
2988                android.Manifest.permission.CLEAR_APP_CACHE, null);
2989        // Queue up an async operation since clearing cache may take a little while.
2990        mHandler.post(new Runnable() {
2991            public void run() {
2992                mHandler.removeCallbacks(this);
2993                int retCode = -1;
2994                synchronized (mInstallLock) {
2995                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2996                    if (retCode < 0) {
2997                        Slog.w(TAG, "Couldn't clear application caches");
2998                    }
2999                }
3000                if(pi != null) {
3001                    try {
3002                        // Callback via pending intent
3003                        int code = (retCode >= 0) ? 1 : 0;
3004                        pi.sendIntent(null, code, null,
3005                                null, null);
3006                    } catch (SendIntentException e1) {
3007                        Slog.i(TAG, "Failed to send pending intent");
3008                    }
3009                }
3010            }
3011        });
3012    }
3013
3014    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3015        synchronized (mInstallLock) {
3016            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3017                throw new IOException("Failed to free enough space");
3018            }
3019        }
3020    }
3021
3022    @Override
3023    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3024        if (!sUserManager.exists(userId)) return null;
3025        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3026        synchronized (mPackages) {
3027            PackageParser.Activity a = mActivities.mActivities.get(component);
3028
3029            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3030            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3031                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3032                if (ps == null) return null;
3033                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3034                        userId);
3035            }
3036            if (mResolveComponentName.equals(component)) {
3037                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3038                        new PackageUserState(), userId);
3039            }
3040        }
3041        return null;
3042    }
3043
3044    @Override
3045    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3046            String resolvedType) {
3047        synchronized (mPackages) {
3048            if (component.equals(mResolveComponentName)) {
3049                // The resolver supports EVERYTHING!
3050                return true;
3051            }
3052            PackageParser.Activity a = mActivities.mActivities.get(component);
3053            if (a == null) {
3054                return false;
3055            }
3056            for (int i=0; i<a.intents.size(); i++) {
3057                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3058                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3059                    return true;
3060                }
3061            }
3062            return false;
3063        }
3064    }
3065
3066    @Override
3067    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3068        if (!sUserManager.exists(userId)) return null;
3069        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3070        synchronized (mPackages) {
3071            PackageParser.Activity a = mReceivers.mActivities.get(component);
3072            if (DEBUG_PACKAGE_INFO) Log.v(
3073                TAG, "getReceiverInfo " + component + ": " + a);
3074            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3075                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3076                if (ps == null) return null;
3077                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3078                        userId);
3079            }
3080        }
3081        return null;
3082    }
3083
3084    @Override
3085    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3086        if (!sUserManager.exists(userId)) return null;
3087        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3088        synchronized (mPackages) {
3089            PackageParser.Service s = mServices.mServices.get(component);
3090            if (DEBUG_PACKAGE_INFO) Log.v(
3091                TAG, "getServiceInfo " + component + ": " + s);
3092            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3093                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3094                if (ps == null) return null;
3095                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3096                        userId);
3097            }
3098        }
3099        return null;
3100    }
3101
3102    @Override
3103    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3104        if (!sUserManager.exists(userId)) return null;
3105        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3106        synchronized (mPackages) {
3107            PackageParser.Provider p = mProviders.mProviders.get(component);
3108            if (DEBUG_PACKAGE_INFO) Log.v(
3109                TAG, "getProviderInfo " + component + ": " + p);
3110            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3111                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3112                if (ps == null) return null;
3113                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3114                        userId);
3115            }
3116        }
3117        return null;
3118    }
3119
3120    @Override
3121    public String[] getSystemSharedLibraryNames() {
3122        Set<String> libSet;
3123        synchronized (mPackages) {
3124            libSet = mSharedLibraries.keySet();
3125            int size = libSet.size();
3126            if (size > 0) {
3127                String[] libs = new String[size];
3128                libSet.toArray(libs);
3129                return libs;
3130            }
3131        }
3132        return null;
3133    }
3134
3135    /**
3136     * @hide
3137     */
3138    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3139        synchronized (mPackages) {
3140            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3141            if (lib != null && lib.apk != null) {
3142                return mPackages.get(lib.apk);
3143            }
3144        }
3145        return null;
3146    }
3147
3148    @Override
3149    public FeatureInfo[] getSystemAvailableFeatures() {
3150        Collection<FeatureInfo> featSet;
3151        synchronized (mPackages) {
3152            featSet = mAvailableFeatures.values();
3153            int size = featSet.size();
3154            if (size > 0) {
3155                FeatureInfo[] features = new FeatureInfo[size+1];
3156                featSet.toArray(features);
3157                FeatureInfo fi = new FeatureInfo();
3158                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3159                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3160                features[size] = fi;
3161                return features;
3162            }
3163        }
3164        return null;
3165    }
3166
3167    @Override
3168    public boolean hasSystemFeature(String name) {
3169        synchronized (mPackages) {
3170            return mAvailableFeatures.containsKey(name);
3171        }
3172    }
3173
3174    private void checkValidCaller(int uid, int userId) {
3175        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3176            return;
3177
3178        throw new SecurityException("Caller uid=" + uid
3179                + " is not privileged to communicate with user=" + userId);
3180    }
3181
3182    @Override
3183    public int checkPermission(String permName, String pkgName, int userId) {
3184        if (!sUserManager.exists(userId)) {
3185            return PackageManager.PERMISSION_DENIED;
3186        }
3187
3188        synchronized (mPackages) {
3189            final PackageParser.Package p = mPackages.get(pkgName);
3190            if (p != null && p.mExtras != null) {
3191                final PackageSetting ps = (PackageSetting) p.mExtras;
3192                final PermissionsState permissionsState = ps.getPermissionsState();
3193                if (permissionsState.hasPermission(permName, userId)) {
3194                    return PackageManager.PERMISSION_GRANTED;
3195                }
3196                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3197                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3198                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3199                    return PackageManager.PERMISSION_GRANTED;
3200                }
3201            }
3202        }
3203
3204        return PackageManager.PERMISSION_DENIED;
3205    }
3206
3207    @Override
3208    public int checkUidPermission(String permName, int uid) {
3209        final int userId = UserHandle.getUserId(uid);
3210
3211        if (!sUserManager.exists(userId)) {
3212            return PackageManager.PERMISSION_DENIED;
3213        }
3214
3215        synchronized (mPackages) {
3216            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3217            if (obj != null) {
3218                final SettingBase ps = (SettingBase) obj;
3219                final PermissionsState permissionsState = ps.getPermissionsState();
3220                if (permissionsState.hasPermission(permName, userId)) {
3221                    return PackageManager.PERMISSION_GRANTED;
3222                }
3223                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3224                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3225                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3226                    return PackageManager.PERMISSION_GRANTED;
3227                }
3228            } else {
3229                ArraySet<String> perms = mSystemPermissions.get(uid);
3230                if (perms != null) {
3231                    if (perms.contains(permName)) {
3232                        return PackageManager.PERMISSION_GRANTED;
3233                    }
3234                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3235                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3236                        return PackageManager.PERMISSION_GRANTED;
3237                    }
3238                }
3239            }
3240        }
3241
3242        return PackageManager.PERMISSION_DENIED;
3243    }
3244
3245    @Override
3246    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3247        if (UserHandle.getCallingUserId() != userId) {
3248            mContext.enforceCallingPermission(
3249                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3250                    "isPermissionRevokedByPolicy for user " + userId);
3251        }
3252
3253        if (checkPermission(permission, packageName, userId)
3254                == PackageManager.PERMISSION_GRANTED) {
3255            return false;
3256        }
3257
3258        final long identity = Binder.clearCallingIdentity();
3259        try {
3260            final int flags = getPermissionFlags(permission, packageName, userId);
3261            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3262        } finally {
3263            Binder.restoreCallingIdentity(identity);
3264        }
3265    }
3266
3267    @Override
3268    public String getPermissionControllerPackageName() {
3269        synchronized (mPackages) {
3270            return mRequiredInstallerPackage;
3271        }
3272    }
3273
3274    /**
3275     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3276     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3277     * @param checkShell TODO(yamasani):
3278     * @param message the message to log on security exception
3279     */
3280    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3281            boolean checkShell, String message) {
3282        if (userId < 0) {
3283            throw new IllegalArgumentException("Invalid userId " + userId);
3284        }
3285        if (checkShell) {
3286            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3287        }
3288        if (userId == UserHandle.getUserId(callingUid)) return;
3289        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3290            if (requireFullPermission) {
3291                mContext.enforceCallingOrSelfPermission(
3292                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3293            } else {
3294                try {
3295                    mContext.enforceCallingOrSelfPermission(
3296                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3297                } catch (SecurityException se) {
3298                    mContext.enforceCallingOrSelfPermission(
3299                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3300                }
3301            }
3302        }
3303    }
3304
3305    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3306        if (callingUid == Process.SHELL_UID) {
3307            if (userHandle >= 0
3308                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3309                throw new SecurityException("Shell does not have permission to access user "
3310                        + userHandle);
3311            } else if (userHandle < 0) {
3312                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3313                        + Debug.getCallers(3));
3314            }
3315        }
3316    }
3317
3318    private BasePermission findPermissionTreeLP(String permName) {
3319        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3320            if (permName.startsWith(bp.name) &&
3321                    permName.length() > bp.name.length() &&
3322                    permName.charAt(bp.name.length()) == '.') {
3323                return bp;
3324            }
3325        }
3326        return null;
3327    }
3328
3329    private BasePermission checkPermissionTreeLP(String permName) {
3330        if (permName != null) {
3331            BasePermission bp = findPermissionTreeLP(permName);
3332            if (bp != null) {
3333                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3334                    return bp;
3335                }
3336                throw new SecurityException("Calling uid "
3337                        + Binder.getCallingUid()
3338                        + " is not allowed to add to permission tree "
3339                        + bp.name + " owned by uid " + bp.uid);
3340            }
3341        }
3342        throw new SecurityException("No permission tree found for " + permName);
3343    }
3344
3345    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3346        if (s1 == null) {
3347            return s2 == null;
3348        }
3349        if (s2 == null) {
3350            return false;
3351        }
3352        if (s1.getClass() != s2.getClass()) {
3353            return false;
3354        }
3355        return s1.equals(s2);
3356    }
3357
3358    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3359        if (pi1.icon != pi2.icon) return false;
3360        if (pi1.logo != pi2.logo) return false;
3361        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3362        if (!compareStrings(pi1.name, pi2.name)) return false;
3363        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3364        // We'll take care of setting this one.
3365        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3366        // These are not currently stored in settings.
3367        //if (!compareStrings(pi1.group, pi2.group)) return false;
3368        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3369        //if (pi1.labelRes != pi2.labelRes) return false;
3370        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3371        return true;
3372    }
3373
3374    int permissionInfoFootprint(PermissionInfo info) {
3375        int size = info.name.length();
3376        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3377        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3378        return size;
3379    }
3380
3381    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3382        int size = 0;
3383        for (BasePermission perm : mSettings.mPermissions.values()) {
3384            if (perm.uid == tree.uid) {
3385                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3386            }
3387        }
3388        return size;
3389    }
3390
3391    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3392        // We calculate the max size of permissions defined by this uid and throw
3393        // if that plus the size of 'info' would exceed our stated maximum.
3394        if (tree.uid != Process.SYSTEM_UID) {
3395            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3396            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3397                throw new SecurityException("Permission tree size cap exceeded");
3398            }
3399        }
3400    }
3401
3402    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3403        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3404            throw new SecurityException("Label must be specified in permission");
3405        }
3406        BasePermission tree = checkPermissionTreeLP(info.name);
3407        BasePermission bp = mSettings.mPermissions.get(info.name);
3408        boolean added = bp == null;
3409        boolean changed = true;
3410        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3411        if (added) {
3412            enforcePermissionCapLocked(info, tree);
3413            bp = new BasePermission(info.name, tree.sourcePackage,
3414                    BasePermission.TYPE_DYNAMIC);
3415        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3416            throw new SecurityException(
3417                    "Not allowed to modify non-dynamic permission "
3418                    + info.name);
3419        } else {
3420            if (bp.protectionLevel == fixedLevel
3421                    && bp.perm.owner.equals(tree.perm.owner)
3422                    && bp.uid == tree.uid
3423                    && comparePermissionInfos(bp.perm.info, info)) {
3424                changed = false;
3425            }
3426        }
3427        bp.protectionLevel = fixedLevel;
3428        info = new PermissionInfo(info);
3429        info.protectionLevel = fixedLevel;
3430        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3431        bp.perm.info.packageName = tree.perm.info.packageName;
3432        bp.uid = tree.uid;
3433        if (added) {
3434            mSettings.mPermissions.put(info.name, bp);
3435        }
3436        if (changed) {
3437            if (!async) {
3438                mSettings.writeLPr();
3439            } else {
3440                scheduleWriteSettingsLocked();
3441            }
3442        }
3443        return added;
3444    }
3445
3446    @Override
3447    public boolean addPermission(PermissionInfo info) {
3448        synchronized (mPackages) {
3449            return addPermissionLocked(info, false);
3450        }
3451    }
3452
3453    @Override
3454    public boolean addPermissionAsync(PermissionInfo info) {
3455        synchronized (mPackages) {
3456            return addPermissionLocked(info, true);
3457        }
3458    }
3459
3460    @Override
3461    public void removePermission(String name) {
3462        synchronized (mPackages) {
3463            checkPermissionTreeLP(name);
3464            BasePermission bp = mSettings.mPermissions.get(name);
3465            if (bp != null) {
3466                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3467                    throw new SecurityException(
3468                            "Not allowed to modify non-dynamic permission "
3469                            + name);
3470                }
3471                mSettings.mPermissions.remove(name);
3472                mSettings.writeLPr();
3473            }
3474        }
3475    }
3476
3477    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3478            BasePermission bp) {
3479        int index = pkg.requestedPermissions.indexOf(bp.name);
3480        if (index == -1) {
3481            throw new SecurityException("Package " + pkg.packageName
3482                    + " has not requested permission " + bp.name);
3483        }
3484        if (!bp.isRuntime() && !bp.isDevelopment()) {
3485            throw new SecurityException("Permission " + bp.name
3486                    + " is not a changeable permission type");
3487        }
3488    }
3489
3490    @Override
3491    public void grantRuntimePermission(String packageName, String name, final int userId) {
3492        if (!sUserManager.exists(userId)) {
3493            Log.e(TAG, "No such user:" + userId);
3494            return;
3495        }
3496
3497        mContext.enforceCallingOrSelfPermission(
3498                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3499                "grantRuntimePermission");
3500
3501        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3502                "grantRuntimePermission");
3503
3504        final int uid;
3505        final SettingBase sb;
3506
3507        synchronized (mPackages) {
3508            final PackageParser.Package pkg = mPackages.get(packageName);
3509            if (pkg == null) {
3510                throw new IllegalArgumentException("Unknown package: " + packageName);
3511            }
3512
3513            final BasePermission bp = mSettings.mPermissions.get(name);
3514            if (bp == null) {
3515                throw new IllegalArgumentException("Unknown permission: " + name);
3516            }
3517
3518            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3519
3520            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3521            sb = (SettingBase) pkg.mExtras;
3522            if (sb == null) {
3523                throw new IllegalArgumentException("Unknown package: " + packageName);
3524            }
3525
3526            final PermissionsState permissionsState = sb.getPermissionsState();
3527
3528            final int flags = permissionsState.getPermissionFlags(name, userId);
3529            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3530                throw new SecurityException("Cannot grant system fixed permission: "
3531                        + name + " for package: " + packageName);
3532            }
3533
3534            if (bp.isDevelopment()) {
3535                // Development permissions must be handled specially, since they are not
3536                // normal runtime permissions.  For now they apply to all users.
3537                if (permissionsState.grantInstallPermission(bp) !=
3538                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3539                    scheduleWriteSettingsLocked();
3540                }
3541                return;
3542            }
3543
3544            final int result = permissionsState.grantRuntimePermission(bp, userId);
3545            switch (result) {
3546                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3547                    return;
3548                }
3549
3550                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3551                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3552                    mHandler.post(new Runnable() {
3553                        @Override
3554                        public void run() {
3555                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3556                        }
3557                    });
3558                } break;
3559            }
3560
3561            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3562
3563            // Not critical if that is lost - app has to request again.
3564            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3565        }
3566
3567        // Only need to do this if user is initialized. Otherwise it's a new user
3568        // and there are no processes running as the user yet and there's no need
3569        // to make an expensive call to remount processes for the changed permissions.
3570        if (READ_EXTERNAL_STORAGE.equals(name)
3571                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3572            final long token = Binder.clearCallingIdentity();
3573            try {
3574                if (sUserManager.isInitialized(userId)) {
3575                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3576                            MountServiceInternal.class);
3577                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3578                }
3579            } finally {
3580                Binder.restoreCallingIdentity(token);
3581            }
3582        }
3583    }
3584
3585    @Override
3586    public void revokeRuntimePermission(String packageName, String name, int userId) {
3587        if (!sUserManager.exists(userId)) {
3588            Log.e(TAG, "No such user:" + userId);
3589            return;
3590        }
3591
3592        mContext.enforceCallingOrSelfPermission(
3593                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3594                "revokeRuntimePermission");
3595
3596        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3597                "revokeRuntimePermission");
3598
3599        final int appId;
3600
3601        synchronized (mPackages) {
3602            final PackageParser.Package pkg = mPackages.get(packageName);
3603            if (pkg == null) {
3604                throw new IllegalArgumentException("Unknown package: " + packageName);
3605            }
3606
3607            final BasePermission bp = mSettings.mPermissions.get(name);
3608            if (bp == null) {
3609                throw new IllegalArgumentException("Unknown permission: " + name);
3610            }
3611
3612            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3613
3614            SettingBase sb = (SettingBase) pkg.mExtras;
3615            if (sb == null) {
3616                throw new IllegalArgumentException("Unknown package: " + packageName);
3617            }
3618
3619            final PermissionsState permissionsState = sb.getPermissionsState();
3620
3621            final int flags = permissionsState.getPermissionFlags(name, userId);
3622            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3623                throw new SecurityException("Cannot revoke system fixed permission: "
3624                        + name + " for package: " + packageName);
3625            }
3626
3627            if (bp.isDevelopment()) {
3628                // Development permissions must be handled specially, since they are not
3629                // normal runtime permissions.  For now they apply to all users.
3630                if (permissionsState.revokeInstallPermission(bp) !=
3631                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3632                    scheduleWriteSettingsLocked();
3633                }
3634                return;
3635            }
3636
3637            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3638                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3639                return;
3640            }
3641
3642            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3643
3644            // Critical, after this call app should never have the permission.
3645            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3646
3647            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3648        }
3649
3650        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3651    }
3652
3653    @Override
3654    public void resetRuntimePermissions() {
3655        mContext.enforceCallingOrSelfPermission(
3656                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3657                "revokeRuntimePermission");
3658
3659        int callingUid = Binder.getCallingUid();
3660        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3661            mContext.enforceCallingOrSelfPermission(
3662                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3663                    "resetRuntimePermissions");
3664        }
3665
3666        synchronized (mPackages) {
3667            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3668            for (int userId : UserManagerService.getInstance().getUserIds()) {
3669                final int packageCount = mPackages.size();
3670                for (int i = 0; i < packageCount; i++) {
3671                    PackageParser.Package pkg = mPackages.valueAt(i);
3672                    if (!(pkg.mExtras instanceof PackageSetting)) {
3673                        continue;
3674                    }
3675                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3676                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3677                }
3678            }
3679        }
3680    }
3681
3682    @Override
3683    public int getPermissionFlags(String name, String packageName, int userId) {
3684        if (!sUserManager.exists(userId)) {
3685            return 0;
3686        }
3687
3688        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3689
3690        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3691                "getPermissionFlags");
3692
3693        synchronized (mPackages) {
3694            final PackageParser.Package pkg = mPackages.get(packageName);
3695            if (pkg == null) {
3696                throw new IllegalArgumentException("Unknown package: " + packageName);
3697            }
3698
3699            final BasePermission bp = mSettings.mPermissions.get(name);
3700            if (bp == null) {
3701                throw new IllegalArgumentException("Unknown permission: " + name);
3702            }
3703
3704            SettingBase sb = (SettingBase) pkg.mExtras;
3705            if (sb == null) {
3706                throw new IllegalArgumentException("Unknown package: " + packageName);
3707            }
3708
3709            PermissionsState permissionsState = sb.getPermissionsState();
3710            return permissionsState.getPermissionFlags(name, userId);
3711        }
3712    }
3713
3714    @Override
3715    public void updatePermissionFlags(String name, String packageName, int flagMask,
3716            int flagValues, int userId) {
3717        if (!sUserManager.exists(userId)) {
3718            return;
3719        }
3720
3721        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3722
3723        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3724                "updatePermissionFlags");
3725
3726        // Only the system can change these flags and nothing else.
3727        if (getCallingUid() != Process.SYSTEM_UID) {
3728            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3729            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3730            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3731            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3732        }
3733
3734        synchronized (mPackages) {
3735            final PackageParser.Package pkg = mPackages.get(packageName);
3736            if (pkg == null) {
3737                throw new IllegalArgumentException("Unknown package: " + packageName);
3738            }
3739
3740            final BasePermission bp = mSettings.mPermissions.get(name);
3741            if (bp == null) {
3742                throw new IllegalArgumentException("Unknown permission: " + name);
3743            }
3744
3745            SettingBase sb = (SettingBase) pkg.mExtras;
3746            if (sb == null) {
3747                throw new IllegalArgumentException("Unknown package: " + packageName);
3748            }
3749
3750            PermissionsState permissionsState = sb.getPermissionsState();
3751
3752            // Only the package manager can change flags for system component permissions.
3753            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3754            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3755                return;
3756            }
3757
3758            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3759
3760            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3761                // Install and runtime permissions are stored in different places,
3762                // so figure out what permission changed and persist the change.
3763                if (permissionsState.getInstallPermissionState(name) != null) {
3764                    scheduleWriteSettingsLocked();
3765                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3766                        || hadState) {
3767                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3768                }
3769            }
3770        }
3771    }
3772
3773    /**
3774     * Update the permission flags for all packages and runtime permissions of a user in order
3775     * to allow device or profile owner to remove POLICY_FIXED.
3776     */
3777    @Override
3778    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3779        if (!sUserManager.exists(userId)) {
3780            return;
3781        }
3782
3783        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3784
3785        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3786                "updatePermissionFlagsForAllApps");
3787
3788        // Only the system can change system fixed flags.
3789        if (getCallingUid() != Process.SYSTEM_UID) {
3790            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3791            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3792        }
3793
3794        synchronized (mPackages) {
3795            boolean changed = false;
3796            final int packageCount = mPackages.size();
3797            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3798                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3799                SettingBase sb = (SettingBase) pkg.mExtras;
3800                if (sb == null) {
3801                    continue;
3802                }
3803                PermissionsState permissionsState = sb.getPermissionsState();
3804                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3805                        userId, flagMask, flagValues);
3806            }
3807            if (changed) {
3808                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3809            }
3810        }
3811    }
3812
3813    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3814        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3815                != PackageManager.PERMISSION_GRANTED
3816            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3817                != PackageManager.PERMISSION_GRANTED) {
3818            throw new SecurityException(message + " requires "
3819                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3820                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3821        }
3822    }
3823
3824    @Override
3825    public boolean shouldShowRequestPermissionRationale(String permissionName,
3826            String packageName, int userId) {
3827        if (UserHandle.getCallingUserId() != userId) {
3828            mContext.enforceCallingPermission(
3829                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3830                    "canShowRequestPermissionRationale for user " + userId);
3831        }
3832
3833        final int uid = getPackageUid(packageName, userId);
3834        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3835            return false;
3836        }
3837
3838        if (checkPermission(permissionName, packageName, userId)
3839                == PackageManager.PERMISSION_GRANTED) {
3840            return false;
3841        }
3842
3843        final int flags;
3844
3845        final long identity = Binder.clearCallingIdentity();
3846        try {
3847            flags = getPermissionFlags(permissionName,
3848                    packageName, userId);
3849        } finally {
3850            Binder.restoreCallingIdentity(identity);
3851        }
3852
3853        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3854                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3855                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3856
3857        if ((flags & fixedFlags) != 0) {
3858            return false;
3859        }
3860
3861        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3862    }
3863
3864    @Override
3865    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3866        mContext.enforceCallingOrSelfPermission(
3867                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3868                "addOnPermissionsChangeListener");
3869
3870        synchronized (mPackages) {
3871            mOnPermissionChangeListeners.addListenerLocked(listener);
3872        }
3873    }
3874
3875    @Override
3876    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3877        synchronized (mPackages) {
3878            mOnPermissionChangeListeners.removeListenerLocked(listener);
3879        }
3880    }
3881
3882    @Override
3883    public boolean isProtectedBroadcast(String actionName) {
3884        synchronized (mPackages) {
3885            return mProtectedBroadcasts.contains(actionName);
3886        }
3887    }
3888
3889    @Override
3890    public int checkSignatures(String pkg1, String pkg2) {
3891        synchronized (mPackages) {
3892            final PackageParser.Package p1 = mPackages.get(pkg1);
3893            final PackageParser.Package p2 = mPackages.get(pkg2);
3894            if (p1 == null || p1.mExtras == null
3895                    || p2 == null || p2.mExtras == null) {
3896                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3897            }
3898            return compareSignatures(p1.mSignatures, p2.mSignatures);
3899        }
3900    }
3901
3902    @Override
3903    public int checkUidSignatures(int uid1, int uid2) {
3904        // Map to base uids.
3905        uid1 = UserHandle.getAppId(uid1);
3906        uid2 = UserHandle.getAppId(uid2);
3907        // reader
3908        synchronized (mPackages) {
3909            Signature[] s1;
3910            Signature[] s2;
3911            Object obj = mSettings.getUserIdLPr(uid1);
3912            if (obj != null) {
3913                if (obj instanceof SharedUserSetting) {
3914                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3915                } else if (obj instanceof PackageSetting) {
3916                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3917                } else {
3918                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3919                }
3920            } else {
3921                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3922            }
3923            obj = mSettings.getUserIdLPr(uid2);
3924            if (obj != null) {
3925                if (obj instanceof SharedUserSetting) {
3926                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3927                } else if (obj instanceof PackageSetting) {
3928                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3929                } else {
3930                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3931                }
3932            } else {
3933                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3934            }
3935            return compareSignatures(s1, s2);
3936        }
3937    }
3938
3939    private void killUid(int appId, int userId, String reason) {
3940        final long identity = Binder.clearCallingIdentity();
3941        try {
3942            IActivityManager am = ActivityManagerNative.getDefault();
3943            if (am != null) {
3944                try {
3945                    am.killUid(appId, userId, reason);
3946                } catch (RemoteException e) {
3947                    /* ignore - same process */
3948                }
3949            }
3950        } finally {
3951            Binder.restoreCallingIdentity(identity);
3952        }
3953    }
3954
3955    /**
3956     * Compares two sets of signatures. Returns:
3957     * <br />
3958     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3959     * <br />
3960     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3961     * <br />
3962     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3963     * <br />
3964     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3965     * <br />
3966     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3967     */
3968    static int compareSignatures(Signature[] s1, Signature[] s2) {
3969        if (s1 == null) {
3970            return s2 == null
3971                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3972                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3973        }
3974
3975        if (s2 == null) {
3976            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3977        }
3978
3979        if (s1.length != s2.length) {
3980            return PackageManager.SIGNATURE_NO_MATCH;
3981        }
3982
3983        // Since both signature sets are of size 1, we can compare without HashSets.
3984        if (s1.length == 1) {
3985            return s1[0].equals(s2[0]) ?
3986                    PackageManager.SIGNATURE_MATCH :
3987                    PackageManager.SIGNATURE_NO_MATCH;
3988        }
3989
3990        ArraySet<Signature> set1 = new ArraySet<Signature>();
3991        for (Signature sig : s1) {
3992            set1.add(sig);
3993        }
3994        ArraySet<Signature> set2 = new ArraySet<Signature>();
3995        for (Signature sig : s2) {
3996            set2.add(sig);
3997        }
3998        // Make sure s2 contains all signatures in s1.
3999        if (set1.equals(set2)) {
4000            return PackageManager.SIGNATURE_MATCH;
4001        }
4002        return PackageManager.SIGNATURE_NO_MATCH;
4003    }
4004
4005    /**
4006     * If the database version for this type of package (internal storage or
4007     * external storage) is less than the version where package signatures
4008     * were updated, return true.
4009     */
4010    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4011        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4012        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4013    }
4014
4015    /**
4016     * Used for backward compatibility to make sure any packages with
4017     * certificate chains get upgraded to the new style. {@code existingSigs}
4018     * will be in the old format (since they were stored on disk from before the
4019     * system upgrade) and {@code scannedSigs} will be in the newer format.
4020     */
4021    private int compareSignaturesCompat(PackageSignatures existingSigs,
4022            PackageParser.Package scannedPkg) {
4023        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4024            return PackageManager.SIGNATURE_NO_MATCH;
4025        }
4026
4027        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4028        for (Signature sig : existingSigs.mSignatures) {
4029            existingSet.add(sig);
4030        }
4031        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4032        for (Signature sig : scannedPkg.mSignatures) {
4033            try {
4034                Signature[] chainSignatures = sig.getChainSignatures();
4035                for (Signature chainSig : chainSignatures) {
4036                    scannedCompatSet.add(chainSig);
4037                }
4038            } catch (CertificateEncodingException e) {
4039                scannedCompatSet.add(sig);
4040            }
4041        }
4042        /*
4043         * Make sure the expanded scanned set contains all signatures in the
4044         * existing one.
4045         */
4046        if (scannedCompatSet.equals(existingSet)) {
4047            // Migrate the old signatures to the new scheme.
4048            existingSigs.assignSignatures(scannedPkg.mSignatures);
4049            // The new KeySets will be re-added later in the scanning process.
4050            synchronized (mPackages) {
4051                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4052            }
4053            return PackageManager.SIGNATURE_MATCH;
4054        }
4055        return PackageManager.SIGNATURE_NO_MATCH;
4056    }
4057
4058    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4059        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4060        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4061    }
4062
4063    private int compareSignaturesRecover(PackageSignatures existingSigs,
4064            PackageParser.Package scannedPkg) {
4065        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4066            return PackageManager.SIGNATURE_NO_MATCH;
4067        }
4068
4069        String msg = null;
4070        try {
4071            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4072                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4073                        + scannedPkg.packageName);
4074                return PackageManager.SIGNATURE_MATCH;
4075            }
4076        } catch (CertificateException e) {
4077            msg = e.getMessage();
4078        }
4079
4080        logCriticalInfo(Log.INFO,
4081                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4082        return PackageManager.SIGNATURE_NO_MATCH;
4083    }
4084
4085    @Override
4086    public String[] getPackagesForUid(int uid) {
4087        uid = UserHandle.getAppId(uid);
4088        // reader
4089        synchronized (mPackages) {
4090            Object obj = mSettings.getUserIdLPr(uid);
4091            if (obj instanceof SharedUserSetting) {
4092                final SharedUserSetting sus = (SharedUserSetting) obj;
4093                final int N = sus.packages.size();
4094                final String[] res = new String[N];
4095                final Iterator<PackageSetting> it = sus.packages.iterator();
4096                int i = 0;
4097                while (it.hasNext()) {
4098                    res[i++] = it.next().name;
4099                }
4100                return res;
4101            } else if (obj instanceof PackageSetting) {
4102                final PackageSetting ps = (PackageSetting) obj;
4103                return new String[] { ps.name };
4104            }
4105        }
4106        return null;
4107    }
4108
4109    @Override
4110    public String getNameForUid(int uid) {
4111        // reader
4112        synchronized (mPackages) {
4113            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4114            if (obj instanceof SharedUserSetting) {
4115                final SharedUserSetting sus = (SharedUserSetting) obj;
4116                return sus.name + ":" + sus.userId;
4117            } else if (obj instanceof PackageSetting) {
4118                final PackageSetting ps = (PackageSetting) obj;
4119                return ps.name;
4120            }
4121        }
4122        return null;
4123    }
4124
4125    @Override
4126    public int getUidForSharedUser(String sharedUserName) {
4127        if(sharedUserName == null) {
4128            return -1;
4129        }
4130        // reader
4131        synchronized (mPackages) {
4132            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4133            if (suid == null) {
4134                return -1;
4135            }
4136            return suid.userId;
4137        }
4138    }
4139
4140    @Override
4141    public int getFlagsForUid(int uid) {
4142        synchronized (mPackages) {
4143            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4144            if (obj instanceof SharedUserSetting) {
4145                final SharedUserSetting sus = (SharedUserSetting) obj;
4146                return sus.pkgFlags;
4147            } else if (obj instanceof PackageSetting) {
4148                final PackageSetting ps = (PackageSetting) obj;
4149                return ps.pkgFlags;
4150            }
4151        }
4152        return 0;
4153    }
4154
4155    @Override
4156    public int getPrivateFlagsForUid(int uid) {
4157        synchronized (mPackages) {
4158            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4159            if (obj instanceof SharedUserSetting) {
4160                final SharedUserSetting sus = (SharedUserSetting) obj;
4161                return sus.pkgPrivateFlags;
4162            } else if (obj instanceof PackageSetting) {
4163                final PackageSetting ps = (PackageSetting) obj;
4164                return ps.pkgPrivateFlags;
4165            }
4166        }
4167        return 0;
4168    }
4169
4170    @Override
4171    public boolean isUidPrivileged(int uid) {
4172        uid = UserHandle.getAppId(uid);
4173        // reader
4174        synchronized (mPackages) {
4175            Object obj = mSettings.getUserIdLPr(uid);
4176            if (obj instanceof SharedUserSetting) {
4177                final SharedUserSetting sus = (SharedUserSetting) obj;
4178                final Iterator<PackageSetting> it = sus.packages.iterator();
4179                while (it.hasNext()) {
4180                    if (it.next().isPrivileged()) {
4181                        return true;
4182                    }
4183                }
4184            } else if (obj instanceof PackageSetting) {
4185                final PackageSetting ps = (PackageSetting) obj;
4186                return ps.isPrivileged();
4187            }
4188        }
4189        return false;
4190    }
4191
4192    @Override
4193    public String[] getAppOpPermissionPackages(String permissionName) {
4194        synchronized (mPackages) {
4195            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4196            if (pkgs == null) {
4197                return null;
4198            }
4199            return pkgs.toArray(new String[pkgs.size()]);
4200        }
4201    }
4202
4203    @Override
4204    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4205            int flags, int userId) {
4206        if (!sUserManager.exists(userId)) return null;
4207        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4208        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4209        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4210    }
4211
4212    @Override
4213    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4214            IntentFilter filter, int match, ComponentName activity) {
4215        final int userId = UserHandle.getCallingUserId();
4216        if (DEBUG_PREFERRED) {
4217            Log.v(TAG, "setLastChosenActivity intent=" + intent
4218                + " resolvedType=" + resolvedType
4219                + " flags=" + flags
4220                + " filter=" + filter
4221                + " match=" + match
4222                + " activity=" + activity);
4223            filter.dump(new PrintStreamPrinter(System.out), "    ");
4224        }
4225        intent.setComponent(null);
4226        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4227        // Find any earlier preferred or last chosen entries and nuke them
4228        findPreferredActivity(intent, resolvedType,
4229                flags, query, 0, false, true, false, userId);
4230        // Add the new activity as the last chosen for this filter
4231        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4232                "Setting last chosen");
4233    }
4234
4235    @Override
4236    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4237        final int userId = UserHandle.getCallingUserId();
4238        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4239        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4240        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4241                false, false, false, userId);
4242    }
4243
4244    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4245            int flags, List<ResolveInfo> query, int userId) {
4246        if (query != null) {
4247            final int N = query.size();
4248            if (N == 1) {
4249                return query.get(0);
4250            } else if (N > 1) {
4251                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4252                // If there is more than one activity with the same priority,
4253                // then let the user decide between them.
4254                ResolveInfo r0 = query.get(0);
4255                ResolveInfo r1 = query.get(1);
4256                if (DEBUG_INTENT_MATCHING || debug) {
4257                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4258                            + r1.activityInfo.name + "=" + r1.priority);
4259                }
4260                // If the first activity has a higher priority, or a different
4261                // default, then it is always desireable to pick it.
4262                if (r0.priority != r1.priority
4263                        || r0.preferredOrder != r1.preferredOrder
4264                        || r0.isDefault != r1.isDefault) {
4265                    return query.get(0);
4266                }
4267                // If we have saved a preference for a preferred activity for
4268                // this Intent, use that.
4269                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4270                        flags, query, r0.priority, true, false, debug, userId);
4271                if (ri != null) {
4272                    return ri;
4273                }
4274                ri = new ResolveInfo(mResolveInfo);
4275                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4276                ri.activityInfo.applicationInfo = new ApplicationInfo(
4277                        ri.activityInfo.applicationInfo);
4278                if (userId != 0) {
4279                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4280                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4281                }
4282                // Make sure that the resolver is displayable in car mode
4283                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4284                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4285                return ri;
4286            }
4287        }
4288        return null;
4289    }
4290
4291    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4292            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4293        final int N = query.size();
4294        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4295                .get(userId);
4296        // Get the list of persistent preferred activities that handle the intent
4297        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4298        List<PersistentPreferredActivity> pprefs = ppir != null
4299                ? ppir.queryIntent(intent, resolvedType,
4300                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4301                : null;
4302        if (pprefs != null && pprefs.size() > 0) {
4303            final int M = pprefs.size();
4304            for (int i=0; i<M; i++) {
4305                final PersistentPreferredActivity ppa = pprefs.get(i);
4306                if (DEBUG_PREFERRED || debug) {
4307                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4308                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4309                            + "\n  component=" + ppa.mComponent);
4310                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4311                }
4312                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4313                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4314                if (DEBUG_PREFERRED || debug) {
4315                    Slog.v(TAG, "Found persistent preferred activity:");
4316                    if (ai != null) {
4317                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4318                    } else {
4319                        Slog.v(TAG, "  null");
4320                    }
4321                }
4322                if (ai == null) {
4323                    // This previously registered persistent preferred activity
4324                    // component is no longer known. Ignore it and do NOT remove it.
4325                    continue;
4326                }
4327                for (int j=0; j<N; j++) {
4328                    final ResolveInfo ri = query.get(j);
4329                    if (!ri.activityInfo.applicationInfo.packageName
4330                            .equals(ai.applicationInfo.packageName)) {
4331                        continue;
4332                    }
4333                    if (!ri.activityInfo.name.equals(ai.name)) {
4334                        continue;
4335                    }
4336                    //  Found a persistent preference that can handle the intent.
4337                    if (DEBUG_PREFERRED || debug) {
4338                        Slog.v(TAG, "Returning persistent preferred activity: " +
4339                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4340                    }
4341                    return ri;
4342                }
4343            }
4344        }
4345        return null;
4346    }
4347
4348    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4349            List<ResolveInfo> query, int priority, boolean always,
4350            boolean removeMatches, boolean debug, int userId) {
4351        if (!sUserManager.exists(userId)) return null;
4352        // writer
4353        synchronized (mPackages) {
4354            if (intent.getSelector() != null) {
4355                intent = intent.getSelector();
4356            }
4357            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4358
4359            // Try to find a matching persistent preferred activity.
4360            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4361                    debug, userId);
4362
4363            // If a persistent preferred activity matched, use it.
4364            if (pri != null) {
4365                return pri;
4366            }
4367
4368            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4369            // Get the list of preferred activities that handle the intent
4370            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4371            List<PreferredActivity> prefs = pir != null
4372                    ? pir.queryIntent(intent, resolvedType,
4373                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4374                    : null;
4375            if (prefs != null && prefs.size() > 0) {
4376                boolean changed = false;
4377                try {
4378                    // First figure out how good the original match set is.
4379                    // We will only allow preferred activities that came
4380                    // from the same match quality.
4381                    int match = 0;
4382
4383                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4384
4385                    final int N = query.size();
4386                    for (int j=0; j<N; j++) {
4387                        final ResolveInfo ri = query.get(j);
4388                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4389                                + ": 0x" + Integer.toHexString(match));
4390                        if (ri.match > match) {
4391                            match = ri.match;
4392                        }
4393                    }
4394
4395                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4396                            + Integer.toHexString(match));
4397
4398                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4399                    final int M = prefs.size();
4400                    for (int i=0; i<M; i++) {
4401                        final PreferredActivity pa = prefs.get(i);
4402                        if (DEBUG_PREFERRED || debug) {
4403                            Slog.v(TAG, "Checking PreferredActivity ds="
4404                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4405                                    + "\n  component=" + pa.mPref.mComponent);
4406                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4407                        }
4408                        if (pa.mPref.mMatch != match) {
4409                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4410                                    + Integer.toHexString(pa.mPref.mMatch));
4411                            continue;
4412                        }
4413                        // If it's not an "always" type preferred activity and that's what we're
4414                        // looking for, skip it.
4415                        if (always && !pa.mPref.mAlways) {
4416                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4417                            continue;
4418                        }
4419                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4420                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4421                        if (DEBUG_PREFERRED || debug) {
4422                            Slog.v(TAG, "Found preferred activity:");
4423                            if (ai != null) {
4424                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4425                            } else {
4426                                Slog.v(TAG, "  null");
4427                            }
4428                        }
4429                        if (ai == null) {
4430                            // This previously registered preferred activity
4431                            // component is no longer known.  Most likely an update
4432                            // to the app was installed and in the new version this
4433                            // component no longer exists.  Clean it up by removing
4434                            // it from the preferred activities list, and skip it.
4435                            Slog.w(TAG, "Removing dangling preferred activity: "
4436                                    + pa.mPref.mComponent);
4437                            pir.removeFilter(pa);
4438                            changed = true;
4439                            continue;
4440                        }
4441                        for (int j=0; j<N; j++) {
4442                            final ResolveInfo ri = query.get(j);
4443                            if (!ri.activityInfo.applicationInfo.packageName
4444                                    .equals(ai.applicationInfo.packageName)) {
4445                                continue;
4446                            }
4447                            if (!ri.activityInfo.name.equals(ai.name)) {
4448                                continue;
4449                            }
4450
4451                            if (removeMatches) {
4452                                pir.removeFilter(pa);
4453                                changed = true;
4454                                if (DEBUG_PREFERRED) {
4455                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4456                                }
4457                                break;
4458                            }
4459
4460                            // Okay we found a previously set preferred or last chosen app.
4461                            // If the result set is different from when this
4462                            // was created, we need to clear it and re-ask the
4463                            // user their preference, if we're looking for an "always" type entry.
4464                            if (always && !pa.mPref.sameSet(query)) {
4465                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4466                                        + intent + " type " + resolvedType);
4467                                if (DEBUG_PREFERRED) {
4468                                    Slog.v(TAG, "Removing preferred activity since set changed "
4469                                            + pa.mPref.mComponent);
4470                                }
4471                                pir.removeFilter(pa);
4472                                // Re-add the filter as a "last chosen" entry (!always)
4473                                PreferredActivity lastChosen = new PreferredActivity(
4474                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4475                                pir.addFilter(lastChosen);
4476                                changed = true;
4477                                return null;
4478                            }
4479
4480                            // Yay! Either the set matched or we're looking for the last chosen
4481                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4482                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4483                            return ri;
4484                        }
4485                    }
4486                } finally {
4487                    if (changed) {
4488                        if (DEBUG_PREFERRED) {
4489                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4490                        }
4491                        scheduleWritePackageRestrictionsLocked(userId);
4492                    }
4493                }
4494            }
4495        }
4496        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4497        return null;
4498    }
4499
4500    /*
4501     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4502     */
4503    @Override
4504    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4505            int targetUserId) {
4506        mContext.enforceCallingOrSelfPermission(
4507                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4508        List<CrossProfileIntentFilter> matches =
4509                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4510        if (matches != null) {
4511            int size = matches.size();
4512            for (int i = 0; i < size; i++) {
4513                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4514            }
4515        }
4516        if (hasWebURI(intent)) {
4517            // cross-profile app linking works only towards the parent.
4518            final UserInfo parent = getProfileParent(sourceUserId);
4519            synchronized(mPackages) {
4520                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4521                        intent, resolvedType, 0, sourceUserId, parent.id);
4522                return xpDomainInfo != null;
4523            }
4524        }
4525        return false;
4526    }
4527
4528    private UserInfo getProfileParent(int userId) {
4529        final long identity = Binder.clearCallingIdentity();
4530        try {
4531            return sUserManager.getProfileParent(userId);
4532        } finally {
4533            Binder.restoreCallingIdentity(identity);
4534        }
4535    }
4536
4537    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4538            String resolvedType, int userId) {
4539        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4540        if (resolver != null) {
4541            return resolver.queryIntent(intent, resolvedType, false, userId);
4542        }
4543        return null;
4544    }
4545
4546    @Override
4547    public List<ResolveInfo> queryIntentActivities(Intent intent,
4548            String resolvedType, int flags, int userId) {
4549        if (!sUserManager.exists(userId)) return Collections.emptyList();
4550        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4551        ComponentName comp = intent.getComponent();
4552        if (comp == null) {
4553            if (intent.getSelector() != null) {
4554                intent = intent.getSelector();
4555                comp = intent.getComponent();
4556            }
4557        }
4558
4559        if (comp != null) {
4560            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4561            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4562            if (ai != null) {
4563                final ResolveInfo ri = new ResolveInfo();
4564                ri.activityInfo = ai;
4565                list.add(ri);
4566            }
4567            return list;
4568        }
4569
4570        // reader
4571        synchronized (mPackages) {
4572            final String pkgName = intent.getPackage();
4573            if (pkgName == null) {
4574                List<CrossProfileIntentFilter> matchingFilters =
4575                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4576                // Check for results that need to skip the current profile.
4577                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4578                        resolvedType, flags, userId);
4579                if (xpResolveInfo != null) {
4580                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4581                    result.add(xpResolveInfo);
4582                    return filterIfNotSystemUser(result, userId);
4583                }
4584
4585                // Check for results in the current profile.
4586                List<ResolveInfo> result = mActivities.queryIntent(
4587                        intent, resolvedType, flags, userId);
4588
4589                // Check for cross profile results.
4590                xpResolveInfo = queryCrossProfileIntents(
4591                        matchingFilters, intent, resolvedType, flags, userId);
4592                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4593                    result.add(xpResolveInfo);
4594                    Collections.sort(result, mResolvePrioritySorter);
4595                }
4596                result = filterIfNotSystemUser(result, userId);
4597                if (hasWebURI(intent)) {
4598                    CrossProfileDomainInfo xpDomainInfo = null;
4599                    final UserInfo parent = getProfileParent(userId);
4600                    if (parent != null) {
4601                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4602                                flags, userId, parent.id);
4603                    }
4604                    if (xpDomainInfo != null) {
4605                        if (xpResolveInfo != null) {
4606                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4607                            // in the result.
4608                            result.remove(xpResolveInfo);
4609                        }
4610                        if (result.size() == 0) {
4611                            result.add(xpDomainInfo.resolveInfo);
4612                            return result;
4613                        }
4614                    } else if (result.size() <= 1) {
4615                        return result;
4616                    }
4617                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4618                            xpDomainInfo, userId);
4619                    Collections.sort(result, mResolvePrioritySorter);
4620                }
4621                return result;
4622            }
4623            final PackageParser.Package pkg = mPackages.get(pkgName);
4624            if (pkg != null) {
4625                return filterIfNotSystemUser(
4626                        mActivities.queryIntentForPackage(
4627                                intent, resolvedType, flags, pkg.activities, userId),
4628                        userId);
4629            }
4630            return new ArrayList<ResolveInfo>();
4631        }
4632    }
4633
4634    private static class CrossProfileDomainInfo {
4635        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4636        ResolveInfo resolveInfo;
4637        /* Best domain verification status of the activities found in the other profile */
4638        int bestDomainVerificationStatus;
4639    }
4640
4641    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4642            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4643        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4644                sourceUserId)) {
4645            return null;
4646        }
4647        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4648                resolvedType, flags, parentUserId);
4649
4650        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4651            return null;
4652        }
4653        CrossProfileDomainInfo result = null;
4654        int size = resultTargetUser.size();
4655        for (int i = 0; i < size; i++) {
4656            ResolveInfo riTargetUser = resultTargetUser.get(i);
4657            // Intent filter verification is only for filters that specify a host. So don't return
4658            // those that handle all web uris.
4659            if (riTargetUser.handleAllWebDataURI) {
4660                continue;
4661            }
4662            String packageName = riTargetUser.activityInfo.packageName;
4663            PackageSetting ps = mSettings.mPackages.get(packageName);
4664            if (ps == null) {
4665                continue;
4666            }
4667            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4668            int status = (int)(verificationState >> 32);
4669            if (result == null) {
4670                result = new CrossProfileDomainInfo();
4671                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
4672                        sourceUserId, parentUserId);
4673                result.bestDomainVerificationStatus = status;
4674            } else {
4675                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4676                        result.bestDomainVerificationStatus);
4677            }
4678        }
4679        // Don't consider matches with status NEVER across profiles.
4680        if (result != null && result.bestDomainVerificationStatus
4681                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4682            return null;
4683        }
4684        return result;
4685    }
4686
4687    /**
4688     * Verification statuses are ordered from the worse to the best, except for
4689     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4690     */
4691    private int bestDomainVerificationStatus(int status1, int status2) {
4692        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4693            return status2;
4694        }
4695        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4696            return status1;
4697        }
4698        return (int) MathUtils.max(status1, status2);
4699    }
4700
4701    private boolean isUserEnabled(int userId) {
4702        long callingId = Binder.clearCallingIdentity();
4703        try {
4704            UserInfo userInfo = sUserManager.getUserInfo(userId);
4705            return userInfo != null && userInfo.isEnabled();
4706        } finally {
4707            Binder.restoreCallingIdentity(callingId);
4708        }
4709    }
4710
4711    /**
4712     * Filter out activities with systemUserOnly flag set, when current user is not System.
4713     *
4714     * @return filtered list
4715     */
4716    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
4717        if (userId == UserHandle.USER_SYSTEM) {
4718            return resolveInfos;
4719        }
4720        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4721            ResolveInfo info = resolveInfos.get(i);
4722            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
4723                resolveInfos.remove(i);
4724            }
4725        }
4726        return resolveInfos;
4727    }
4728
4729    private static boolean hasWebURI(Intent intent) {
4730        if (intent.getData() == null) {
4731            return false;
4732        }
4733        final String scheme = intent.getScheme();
4734        if (TextUtils.isEmpty(scheme)) {
4735            return false;
4736        }
4737        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4738    }
4739
4740    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4741            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4742            int userId) {
4743        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4744
4745        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4746            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4747                    candidates.size());
4748        }
4749
4750        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4751        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4752        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4753        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
4754        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4755        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4756
4757        synchronized (mPackages) {
4758            final int count = candidates.size();
4759            // First, try to use linked apps. Partition the candidates into four lists:
4760            // one for the final results, one for the "do not use ever", one for "undefined status"
4761            // and finally one for "browser app type".
4762            for (int n=0; n<count; n++) {
4763                ResolveInfo info = candidates.get(n);
4764                String packageName = info.activityInfo.packageName;
4765                PackageSetting ps = mSettings.mPackages.get(packageName);
4766                if (ps != null) {
4767                    // Add to the special match all list (Browser use case)
4768                    if (info.handleAllWebDataURI) {
4769                        matchAllList.add(info);
4770                        continue;
4771                    }
4772                    // Try to get the status from User settings first
4773                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4774                    int status = (int)(packedStatus >> 32);
4775                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4776                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4777                        if (DEBUG_DOMAIN_VERIFICATION) {
4778                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4779                                    + " : linkgen=" + linkGeneration);
4780                        }
4781                        // Use link-enabled generation as preferredOrder, i.e.
4782                        // prefer newly-enabled over earlier-enabled.
4783                        info.preferredOrder = linkGeneration;
4784                        alwaysList.add(info);
4785                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4786                        if (DEBUG_DOMAIN_VERIFICATION) {
4787                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4788                        }
4789                        neverList.add(info);
4790                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4791                        if (DEBUG_DOMAIN_VERIFICATION) {
4792                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
4793                        }
4794                        alwaysAskList.add(info);
4795                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4796                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4797                        if (DEBUG_DOMAIN_VERIFICATION) {
4798                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4799                        }
4800                        undefinedList.add(info);
4801                    }
4802                }
4803            }
4804
4805            // We'll want to include browser possibilities in a few cases
4806            boolean includeBrowser = false;
4807
4808            // First try to add the "always" resolution(s) for the current user, if any
4809            if (alwaysList.size() > 0) {
4810                result.addAll(alwaysList);
4811            // if there is an "always" for the parent user, add it.
4812            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4813                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4814                result.add(xpDomainInfo.resolveInfo);
4815            } else {
4816                // Add all undefined apps as we want them to appear in the disambiguation dialog.
4817                result.addAll(undefinedList);
4818                if (xpDomainInfo != null && (
4819                        xpDomainInfo.bestDomainVerificationStatus
4820                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4821                        || xpDomainInfo.bestDomainVerificationStatus
4822                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4823                    result.add(xpDomainInfo.resolveInfo);
4824                }
4825                includeBrowser = true;
4826            }
4827
4828            // The presence of any 'always ask' alternatives means we'll also offer browsers.
4829            // If there were 'always' entries their preferred order has been set, so we also
4830            // back that off to make the alternatives equivalent
4831            if (alwaysAskList.size() > 0) {
4832                for (ResolveInfo i : result) {
4833                    i.preferredOrder = 0;
4834                }
4835                result.addAll(alwaysAskList);
4836                includeBrowser = true;
4837            }
4838
4839            if (includeBrowser) {
4840                // Also add browsers (all of them or only the default one)
4841                if (DEBUG_DOMAIN_VERIFICATION) {
4842                    Slog.v(TAG, "   ...including browsers in candidate set");
4843                }
4844                if ((matchFlags & MATCH_ALL) != 0) {
4845                    result.addAll(matchAllList);
4846                } else {
4847                    // Browser/generic handling case.  If there's a default browser, go straight
4848                    // to that (but only if there is no other higher-priority match).
4849                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4850                    int maxMatchPrio = 0;
4851                    ResolveInfo defaultBrowserMatch = null;
4852                    final int numCandidates = matchAllList.size();
4853                    for (int n = 0; n < numCandidates; n++) {
4854                        ResolveInfo info = matchAllList.get(n);
4855                        // track the highest overall match priority...
4856                        if (info.priority > maxMatchPrio) {
4857                            maxMatchPrio = info.priority;
4858                        }
4859                        // ...and the highest-priority default browser match
4860                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4861                            if (defaultBrowserMatch == null
4862                                    || (defaultBrowserMatch.priority < info.priority)) {
4863                                if (debug) {
4864                                    Slog.v(TAG, "Considering default browser match " + info);
4865                                }
4866                                defaultBrowserMatch = info;
4867                            }
4868                        }
4869                    }
4870                    if (defaultBrowserMatch != null
4871                            && defaultBrowserMatch.priority >= maxMatchPrio
4872                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4873                    {
4874                        if (debug) {
4875                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4876                        }
4877                        result.add(defaultBrowserMatch);
4878                    } else {
4879                        result.addAll(matchAllList);
4880                    }
4881                }
4882
4883                // If there is nothing selected, add all candidates and remove the ones that the user
4884                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4885                if (result.size() == 0) {
4886                    result.addAll(candidates);
4887                    result.removeAll(neverList);
4888                }
4889            }
4890        }
4891        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4892            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4893                    result.size());
4894            for (ResolveInfo info : result) {
4895                Slog.v(TAG, "  + " + info.activityInfo);
4896            }
4897        }
4898        return result;
4899    }
4900
4901    // Returns a packed value as a long:
4902    //
4903    // high 'int'-sized word: link status: undefined/ask/never/always.
4904    // low 'int'-sized word: relative priority among 'always' results.
4905    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4906        long result = ps.getDomainVerificationStatusForUser(userId);
4907        // if none available, get the master status
4908        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4909            if (ps.getIntentFilterVerificationInfo() != null) {
4910                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4911            }
4912        }
4913        return result;
4914    }
4915
4916    private ResolveInfo querySkipCurrentProfileIntents(
4917            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4918            int flags, int sourceUserId) {
4919        if (matchingFilters != null) {
4920            int size = matchingFilters.size();
4921            for (int i = 0; i < size; i ++) {
4922                CrossProfileIntentFilter filter = matchingFilters.get(i);
4923                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4924                    // Checking if there are activities in the target user that can handle the
4925                    // intent.
4926                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
4927                            resolvedType, flags, sourceUserId);
4928                    if (resolveInfo != null) {
4929                        return resolveInfo;
4930                    }
4931                }
4932            }
4933        }
4934        return null;
4935    }
4936
4937    // Return matching ResolveInfo if any for skip current profile intent filters.
4938    private ResolveInfo queryCrossProfileIntents(
4939            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4940            int flags, int sourceUserId) {
4941        if (matchingFilters != null) {
4942            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4943            // match the same intent. For performance reasons, it is better not to
4944            // run queryIntent twice for the same userId
4945            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4946            int size = matchingFilters.size();
4947            for (int i = 0; i < size; i++) {
4948                CrossProfileIntentFilter filter = matchingFilters.get(i);
4949                int targetUserId = filter.getTargetUserId();
4950                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4951                        && !alreadyTriedUserIds.get(targetUserId)) {
4952                    // Checking if there are activities in the target user that can handle the
4953                    // intent.
4954                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
4955                            resolvedType, flags, sourceUserId);
4956                    if (resolveInfo != null) return resolveInfo;
4957                    alreadyTriedUserIds.put(targetUserId, true);
4958                }
4959            }
4960        }
4961        return null;
4962    }
4963
4964    /**
4965     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
4966     * will forward the intent to the filter's target user.
4967     * Otherwise, returns null.
4968     */
4969    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
4970            String resolvedType, int flags, int sourceUserId) {
4971        int targetUserId = filter.getTargetUserId();
4972        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4973                resolvedType, flags, targetUserId);
4974        if (resultTargetUser != null && !resultTargetUser.isEmpty()
4975                && isUserEnabled(targetUserId)) {
4976            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
4977        }
4978        return null;
4979    }
4980
4981    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
4982            int sourceUserId, int targetUserId) {
4983        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4984        long ident = Binder.clearCallingIdentity();
4985        boolean targetIsProfile;
4986        try {
4987            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
4988        } finally {
4989            Binder.restoreCallingIdentity(ident);
4990        }
4991        String className;
4992        if (targetIsProfile) {
4993            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4994        } else {
4995            className = FORWARD_INTENT_TO_PARENT;
4996        }
4997        ComponentName forwardingActivityComponentName = new ComponentName(
4998                mAndroidApplication.packageName, className);
4999        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5000                sourceUserId);
5001        if (!targetIsProfile) {
5002            forwardingActivityInfo.showUserIcon = targetUserId;
5003            forwardingResolveInfo.noResourceId = true;
5004        }
5005        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5006        forwardingResolveInfo.priority = 0;
5007        forwardingResolveInfo.preferredOrder = 0;
5008        forwardingResolveInfo.match = 0;
5009        forwardingResolveInfo.isDefault = true;
5010        forwardingResolveInfo.filter = filter;
5011        forwardingResolveInfo.targetUserId = targetUserId;
5012        return forwardingResolveInfo;
5013    }
5014
5015    @Override
5016    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5017            Intent[] specifics, String[] specificTypes, Intent intent,
5018            String resolvedType, int flags, int userId) {
5019        if (!sUserManager.exists(userId)) return Collections.emptyList();
5020        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5021                false, "query intent activity options");
5022        final String resultsAction = intent.getAction();
5023
5024        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5025                | PackageManager.GET_RESOLVED_FILTER, userId);
5026
5027        if (DEBUG_INTENT_MATCHING) {
5028            Log.v(TAG, "Query " + intent + ": " + results);
5029        }
5030
5031        int specificsPos = 0;
5032        int N;
5033
5034        // todo: note that the algorithm used here is O(N^2).  This
5035        // isn't a problem in our current environment, but if we start running
5036        // into situations where we have more than 5 or 10 matches then this
5037        // should probably be changed to something smarter...
5038
5039        // First we go through and resolve each of the specific items
5040        // that were supplied, taking care of removing any corresponding
5041        // duplicate items in the generic resolve list.
5042        if (specifics != null) {
5043            for (int i=0; i<specifics.length; i++) {
5044                final Intent sintent = specifics[i];
5045                if (sintent == null) {
5046                    continue;
5047                }
5048
5049                if (DEBUG_INTENT_MATCHING) {
5050                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5051                }
5052
5053                String action = sintent.getAction();
5054                if (resultsAction != null && resultsAction.equals(action)) {
5055                    // If this action was explicitly requested, then don't
5056                    // remove things that have it.
5057                    action = null;
5058                }
5059
5060                ResolveInfo ri = null;
5061                ActivityInfo ai = null;
5062
5063                ComponentName comp = sintent.getComponent();
5064                if (comp == null) {
5065                    ri = resolveIntent(
5066                        sintent,
5067                        specificTypes != null ? specificTypes[i] : null,
5068                            flags, userId);
5069                    if (ri == null) {
5070                        continue;
5071                    }
5072                    if (ri == mResolveInfo) {
5073                        // ACK!  Must do something better with this.
5074                    }
5075                    ai = ri.activityInfo;
5076                    comp = new ComponentName(ai.applicationInfo.packageName,
5077                            ai.name);
5078                } else {
5079                    ai = getActivityInfo(comp, flags, userId);
5080                    if (ai == null) {
5081                        continue;
5082                    }
5083                }
5084
5085                // Look for any generic query activities that are duplicates
5086                // of this specific one, and remove them from the results.
5087                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5088                N = results.size();
5089                int j;
5090                for (j=specificsPos; j<N; j++) {
5091                    ResolveInfo sri = results.get(j);
5092                    if ((sri.activityInfo.name.equals(comp.getClassName())
5093                            && sri.activityInfo.applicationInfo.packageName.equals(
5094                                    comp.getPackageName()))
5095                        || (action != null && sri.filter.matchAction(action))) {
5096                        results.remove(j);
5097                        if (DEBUG_INTENT_MATCHING) Log.v(
5098                            TAG, "Removing duplicate item from " + j
5099                            + " due to specific " + specificsPos);
5100                        if (ri == null) {
5101                            ri = sri;
5102                        }
5103                        j--;
5104                        N--;
5105                    }
5106                }
5107
5108                // Add this specific item to its proper place.
5109                if (ri == null) {
5110                    ri = new ResolveInfo();
5111                    ri.activityInfo = ai;
5112                }
5113                results.add(specificsPos, ri);
5114                ri.specificIndex = i;
5115                specificsPos++;
5116            }
5117        }
5118
5119        // Now we go through the remaining generic results and remove any
5120        // duplicate actions that are found here.
5121        N = results.size();
5122        for (int i=specificsPos; i<N-1; i++) {
5123            final ResolveInfo rii = results.get(i);
5124            if (rii.filter == null) {
5125                continue;
5126            }
5127
5128            // Iterate over all of the actions of this result's intent
5129            // filter...  typically this should be just one.
5130            final Iterator<String> it = rii.filter.actionsIterator();
5131            if (it == null) {
5132                continue;
5133            }
5134            while (it.hasNext()) {
5135                final String action = it.next();
5136                if (resultsAction != null && resultsAction.equals(action)) {
5137                    // If this action was explicitly requested, then don't
5138                    // remove things that have it.
5139                    continue;
5140                }
5141                for (int j=i+1; j<N; j++) {
5142                    final ResolveInfo rij = results.get(j);
5143                    if (rij.filter != null && rij.filter.hasAction(action)) {
5144                        results.remove(j);
5145                        if (DEBUG_INTENT_MATCHING) Log.v(
5146                            TAG, "Removing duplicate item from " + j
5147                            + " due to action " + action + " at " + i);
5148                        j--;
5149                        N--;
5150                    }
5151                }
5152            }
5153
5154            // If the caller didn't request filter information, drop it now
5155            // so we don't have to marshall/unmarshall it.
5156            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5157                rii.filter = null;
5158            }
5159        }
5160
5161        // Filter out the caller activity if so requested.
5162        if (caller != null) {
5163            N = results.size();
5164            for (int i=0; i<N; i++) {
5165                ActivityInfo ainfo = results.get(i).activityInfo;
5166                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5167                        && caller.getClassName().equals(ainfo.name)) {
5168                    results.remove(i);
5169                    break;
5170                }
5171            }
5172        }
5173
5174        // If the caller didn't request filter information,
5175        // drop them now so we don't have to
5176        // marshall/unmarshall it.
5177        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5178            N = results.size();
5179            for (int i=0; i<N; i++) {
5180                results.get(i).filter = null;
5181            }
5182        }
5183
5184        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5185        return results;
5186    }
5187
5188    @Override
5189    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5190            int userId) {
5191        if (!sUserManager.exists(userId)) return Collections.emptyList();
5192        ComponentName comp = intent.getComponent();
5193        if (comp == null) {
5194            if (intent.getSelector() != null) {
5195                intent = intent.getSelector();
5196                comp = intent.getComponent();
5197            }
5198        }
5199        if (comp != null) {
5200            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5201            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5202            if (ai != null) {
5203                ResolveInfo ri = new ResolveInfo();
5204                ri.activityInfo = ai;
5205                list.add(ri);
5206            }
5207            return list;
5208        }
5209
5210        // reader
5211        synchronized (mPackages) {
5212            String pkgName = intent.getPackage();
5213            if (pkgName == null) {
5214                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5215            }
5216            final PackageParser.Package pkg = mPackages.get(pkgName);
5217            if (pkg != null) {
5218                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5219                        userId);
5220            }
5221            return null;
5222        }
5223    }
5224
5225    @Override
5226    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5227        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5228        if (!sUserManager.exists(userId)) return null;
5229        if (query != null) {
5230            if (query.size() >= 1) {
5231                // If there is more than one service with the same priority,
5232                // just arbitrarily pick the first one.
5233                return query.get(0);
5234            }
5235        }
5236        return null;
5237    }
5238
5239    @Override
5240    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5241            int userId) {
5242        if (!sUserManager.exists(userId)) return Collections.emptyList();
5243        ComponentName comp = intent.getComponent();
5244        if (comp == null) {
5245            if (intent.getSelector() != null) {
5246                intent = intent.getSelector();
5247                comp = intent.getComponent();
5248            }
5249        }
5250        if (comp != null) {
5251            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5252            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5253            if (si != null) {
5254                final ResolveInfo ri = new ResolveInfo();
5255                ri.serviceInfo = si;
5256                list.add(ri);
5257            }
5258            return list;
5259        }
5260
5261        // reader
5262        synchronized (mPackages) {
5263            String pkgName = intent.getPackage();
5264            if (pkgName == null) {
5265                return mServices.queryIntent(intent, resolvedType, flags, userId);
5266            }
5267            final PackageParser.Package pkg = mPackages.get(pkgName);
5268            if (pkg != null) {
5269                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5270                        userId);
5271            }
5272            return null;
5273        }
5274    }
5275
5276    @Override
5277    public List<ResolveInfo> queryIntentContentProviders(
5278            Intent intent, String resolvedType, int flags, int userId) {
5279        if (!sUserManager.exists(userId)) return Collections.emptyList();
5280        ComponentName comp = intent.getComponent();
5281        if (comp == null) {
5282            if (intent.getSelector() != null) {
5283                intent = intent.getSelector();
5284                comp = intent.getComponent();
5285            }
5286        }
5287        if (comp != null) {
5288            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5289            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5290            if (pi != null) {
5291                final ResolveInfo ri = new ResolveInfo();
5292                ri.providerInfo = pi;
5293                list.add(ri);
5294            }
5295            return list;
5296        }
5297
5298        // reader
5299        synchronized (mPackages) {
5300            String pkgName = intent.getPackage();
5301            if (pkgName == null) {
5302                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5303            }
5304            final PackageParser.Package pkg = mPackages.get(pkgName);
5305            if (pkg != null) {
5306                return mProviders.queryIntentForPackage(
5307                        intent, resolvedType, flags, pkg.providers, userId);
5308            }
5309            return null;
5310        }
5311    }
5312
5313    @Override
5314    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5315        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5316
5317        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5318
5319        // writer
5320        synchronized (mPackages) {
5321            ArrayList<PackageInfo> list;
5322            if (listUninstalled) {
5323                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5324                for (PackageSetting ps : mSettings.mPackages.values()) {
5325                    PackageInfo pi;
5326                    if (ps.pkg != null) {
5327                        pi = generatePackageInfo(ps.pkg, flags, userId);
5328                    } else {
5329                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5330                    }
5331                    if (pi != null) {
5332                        list.add(pi);
5333                    }
5334                }
5335            } else {
5336                list = new ArrayList<PackageInfo>(mPackages.size());
5337                for (PackageParser.Package p : mPackages.values()) {
5338                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5339                    if (pi != null) {
5340                        list.add(pi);
5341                    }
5342                }
5343            }
5344
5345            return new ParceledListSlice<PackageInfo>(list);
5346        }
5347    }
5348
5349    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5350            String[] permissions, boolean[] tmp, int flags, int userId) {
5351        int numMatch = 0;
5352        final PermissionsState permissionsState = ps.getPermissionsState();
5353        for (int i=0; i<permissions.length; i++) {
5354            final String permission = permissions[i];
5355            if (permissionsState.hasPermission(permission, userId)) {
5356                tmp[i] = true;
5357                numMatch++;
5358            } else {
5359                tmp[i] = false;
5360            }
5361        }
5362        if (numMatch == 0) {
5363            return;
5364        }
5365        PackageInfo pi;
5366        if (ps.pkg != null) {
5367            pi = generatePackageInfo(ps.pkg, flags, userId);
5368        } else {
5369            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5370        }
5371        // The above might return null in cases of uninstalled apps or install-state
5372        // skew across users/profiles.
5373        if (pi != null) {
5374            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5375                if (numMatch == permissions.length) {
5376                    pi.requestedPermissions = permissions;
5377                } else {
5378                    pi.requestedPermissions = new String[numMatch];
5379                    numMatch = 0;
5380                    for (int i=0; i<permissions.length; i++) {
5381                        if (tmp[i]) {
5382                            pi.requestedPermissions[numMatch] = permissions[i];
5383                            numMatch++;
5384                        }
5385                    }
5386                }
5387            }
5388            list.add(pi);
5389        }
5390    }
5391
5392    @Override
5393    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5394            String[] permissions, int flags, int userId) {
5395        if (!sUserManager.exists(userId)) return null;
5396        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5397
5398        // writer
5399        synchronized (mPackages) {
5400            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5401            boolean[] tmpBools = new boolean[permissions.length];
5402            if (listUninstalled) {
5403                for (PackageSetting ps : mSettings.mPackages.values()) {
5404                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5405                }
5406            } else {
5407                for (PackageParser.Package pkg : mPackages.values()) {
5408                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5409                    if (ps != null) {
5410                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5411                                userId);
5412                    }
5413                }
5414            }
5415
5416            return new ParceledListSlice<PackageInfo>(list);
5417        }
5418    }
5419
5420    @Override
5421    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5422        if (!sUserManager.exists(userId)) return null;
5423        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5424
5425        // writer
5426        synchronized (mPackages) {
5427            ArrayList<ApplicationInfo> list;
5428            if (listUninstalled) {
5429                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5430                for (PackageSetting ps : mSettings.mPackages.values()) {
5431                    ApplicationInfo ai;
5432                    if (ps.pkg != null) {
5433                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5434                                ps.readUserState(userId), userId);
5435                    } else {
5436                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5437                    }
5438                    if (ai != null) {
5439                        list.add(ai);
5440                    }
5441                }
5442            } else {
5443                list = new ArrayList<ApplicationInfo>(mPackages.size());
5444                for (PackageParser.Package p : mPackages.values()) {
5445                    if (p.mExtras != null) {
5446                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5447                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5448                        if (ai != null) {
5449                            list.add(ai);
5450                        }
5451                    }
5452                }
5453            }
5454
5455            return new ParceledListSlice<ApplicationInfo>(list);
5456        }
5457    }
5458
5459    public List<ApplicationInfo> getPersistentApplications(int flags) {
5460        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5461
5462        // reader
5463        synchronized (mPackages) {
5464            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5465            final int userId = UserHandle.getCallingUserId();
5466            while (i.hasNext()) {
5467                final PackageParser.Package p = i.next();
5468                if (p.applicationInfo != null
5469                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5470                        && (!mSafeMode || isSystemApp(p))) {
5471                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5472                    if (ps != null) {
5473                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5474                                ps.readUserState(userId), userId);
5475                        if (ai != null) {
5476                            finalList.add(ai);
5477                        }
5478                    }
5479                }
5480            }
5481        }
5482
5483        return finalList;
5484    }
5485
5486    @Override
5487    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5488        if (!sUserManager.exists(userId)) return null;
5489        // reader
5490        synchronized (mPackages) {
5491            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5492            PackageSetting ps = provider != null
5493                    ? mSettings.mPackages.get(provider.owner.packageName)
5494                    : null;
5495            return ps != null
5496                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5497                    && (!mSafeMode || (provider.info.applicationInfo.flags
5498                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5499                    ? PackageParser.generateProviderInfo(provider, flags,
5500                            ps.readUserState(userId), userId)
5501                    : null;
5502        }
5503    }
5504
5505    /**
5506     * @deprecated
5507     */
5508    @Deprecated
5509    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5510        // reader
5511        synchronized (mPackages) {
5512            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5513                    .entrySet().iterator();
5514            final int userId = UserHandle.getCallingUserId();
5515            while (i.hasNext()) {
5516                Map.Entry<String, PackageParser.Provider> entry = i.next();
5517                PackageParser.Provider p = entry.getValue();
5518                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5519
5520                if (ps != null && p.syncable
5521                        && (!mSafeMode || (p.info.applicationInfo.flags
5522                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5523                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5524                            ps.readUserState(userId), userId);
5525                    if (info != null) {
5526                        outNames.add(entry.getKey());
5527                        outInfo.add(info);
5528                    }
5529                }
5530            }
5531        }
5532    }
5533
5534    @Override
5535    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5536            int uid, int flags) {
5537        ArrayList<ProviderInfo> finalList = null;
5538        // reader
5539        synchronized (mPackages) {
5540            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5541            final int userId = processName != null ?
5542                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5543            while (i.hasNext()) {
5544                final PackageParser.Provider p = i.next();
5545                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5546                if (ps != null && p.info.authority != null
5547                        && (processName == null
5548                                || (p.info.processName.equals(processName)
5549                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5550                        && mSettings.isEnabledLPr(p.info, flags, userId)
5551                        && (!mSafeMode
5552                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5553                    if (finalList == null) {
5554                        finalList = new ArrayList<ProviderInfo>(3);
5555                    }
5556                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5557                            ps.readUserState(userId), userId);
5558                    if (info != null) {
5559                        finalList.add(info);
5560                    }
5561                }
5562            }
5563        }
5564
5565        if (finalList != null) {
5566            Collections.sort(finalList, mProviderInitOrderSorter);
5567            return new ParceledListSlice<ProviderInfo>(finalList);
5568        }
5569
5570        return null;
5571    }
5572
5573    @Override
5574    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5575            int flags) {
5576        // reader
5577        synchronized (mPackages) {
5578            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5579            return PackageParser.generateInstrumentationInfo(i, flags);
5580        }
5581    }
5582
5583    @Override
5584    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5585            int flags) {
5586        ArrayList<InstrumentationInfo> finalList =
5587            new ArrayList<InstrumentationInfo>();
5588
5589        // reader
5590        synchronized (mPackages) {
5591            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5592            while (i.hasNext()) {
5593                final PackageParser.Instrumentation p = i.next();
5594                if (targetPackage == null
5595                        || targetPackage.equals(p.info.targetPackage)) {
5596                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5597                            flags);
5598                    if (ii != null) {
5599                        finalList.add(ii);
5600                    }
5601                }
5602            }
5603        }
5604
5605        return finalList;
5606    }
5607
5608    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5609        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5610        if (overlays == null) {
5611            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5612            return;
5613        }
5614        for (PackageParser.Package opkg : overlays.values()) {
5615            // Not much to do if idmap fails: we already logged the error
5616            // and we certainly don't want to abort installation of pkg simply
5617            // because an overlay didn't fit properly. For these reasons,
5618            // ignore the return value of createIdmapForPackagePairLI.
5619            createIdmapForPackagePairLI(pkg, opkg);
5620        }
5621    }
5622
5623    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5624            PackageParser.Package opkg) {
5625        if (!opkg.mTrustedOverlay) {
5626            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5627                    opkg.baseCodePath + ": overlay not trusted");
5628            return false;
5629        }
5630        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5631        if (overlaySet == null) {
5632            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5633                    opkg.baseCodePath + " but target package has no known overlays");
5634            return false;
5635        }
5636        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5637        // TODO: generate idmap for split APKs
5638        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5639            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5640                    + opkg.baseCodePath);
5641            return false;
5642        }
5643        PackageParser.Package[] overlayArray =
5644            overlaySet.values().toArray(new PackageParser.Package[0]);
5645        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5646            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5647                return p1.mOverlayPriority - p2.mOverlayPriority;
5648            }
5649        };
5650        Arrays.sort(overlayArray, cmp);
5651
5652        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5653        int i = 0;
5654        for (PackageParser.Package p : overlayArray) {
5655            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5656        }
5657        return true;
5658    }
5659
5660    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5661        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
5662        try {
5663            scanDirLI(dir, parseFlags, scanFlags, currentTime);
5664        } finally {
5665            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5666        }
5667    }
5668
5669    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5670        final File[] files = dir.listFiles();
5671        if (ArrayUtils.isEmpty(files)) {
5672            Log.d(TAG, "No files in app dir " + dir);
5673            return;
5674        }
5675
5676        if (DEBUG_PACKAGE_SCANNING) {
5677            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5678                    + " flags=0x" + Integer.toHexString(parseFlags));
5679        }
5680
5681        for (File file : files) {
5682            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5683                    && !PackageInstallerService.isStageName(file.getName());
5684            if (!isPackage) {
5685                // Ignore entries which are not packages
5686                continue;
5687            }
5688            try {
5689                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5690                        scanFlags, currentTime, null);
5691            } catch (PackageManagerException e) {
5692                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5693
5694                // Delete invalid userdata apps
5695                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5696                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5697                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5698                    if (file.isDirectory()) {
5699                        mInstaller.rmPackageDir(file.getAbsolutePath());
5700                    } else {
5701                        file.delete();
5702                    }
5703                }
5704            }
5705        }
5706    }
5707
5708    private static File getSettingsProblemFile() {
5709        File dataDir = Environment.getDataDirectory();
5710        File systemDir = new File(dataDir, "system");
5711        File fname = new File(systemDir, "uiderrors.txt");
5712        return fname;
5713    }
5714
5715    static void reportSettingsProblem(int priority, String msg) {
5716        logCriticalInfo(priority, msg);
5717    }
5718
5719    static void logCriticalInfo(int priority, String msg) {
5720        Slog.println(priority, TAG, msg);
5721        EventLogTags.writePmCriticalInfo(msg);
5722        try {
5723            File fname = getSettingsProblemFile();
5724            FileOutputStream out = new FileOutputStream(fname, true);
5725            PrintWriter pw = new FastPrintWriter(out);
5726            SimpleDateFormat formatter = new SimpleDateFormat();
5727            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5728            pw.println(dateString + ": " + msg);
5729            pw.close();
5730            FileUtils.setPermissions(
5731                    fname.toString(),
5732                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5733                    -1, -1);
5734        } catch (java.io.IOException e) {
5735        }
5736    }
5737
5738    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5739            PackageParser.Package pkg, File srcFile, int parseFlags)
5740            throws PackageManagerException {
5741        if (ps != null
5742                && ps.codePath.equals(srcFile)
5743                && ps.timeStamp == srcFile.lastModified()
5744                && !isCompatSignatureUpdateNeeded(pkg)
5745                && !isRecoverSignatureUpdateNeeded(pkg)) {
5746            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5747            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5748            ArraySet<PublicKey> signingKs;
5749            synchronized (mPackages) {
5750                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5751            }
5752            if (ps.signatures.mSignatures != null
5753                    && ps.signatures.mSignatures.length != 0
5754                    && signingKs != null) {
5755                // Optimization: reuse the existing cached certificates
5756                // if the package appears to be unchanged.
5757                pkg.mSignatures = ps.signatures.mSignatures;
5758                pkg.mSigningKeys = signingKs;
5759                return;
5760            }
5761
5762            Slog.w(TAG, "PackageSetting for " + ps.name
5763                    + " is missing signatures.  Collecting certs again to recover them.");
5764        } else {
5765            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5766        }
5767
5768        try {
5769            pp.collectCertificates(pkg, parseFlags);
5770            pp.collectManifestDigest(pkg);
5771        } catch (PackageParserException e) {
5772            throw PackageManagerException.from(e);
5773        }
5774    }
5775
5776    /**
5777     *  Traces a package scan.
5778     *  @see #scanPackageLI(File, int, int, long, UserHandle)
5779     */
5780    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
5781            long currentTime, UserHandle user) throws PackageManagerException {
5782        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
5783        try {
5784            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
5785        } finally {
5786            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5787        }
5788    }
5789
5790    /**
5791     *  Scans a package and returns the newly parsed package.
5792     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
5793     */
5794    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5795            long currentTime, UserHandle user) throws PackageManagerException {
5796        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5797        parseFlags |= mDefParseFlags;
5798        PackageParser pp = new PackageParser();
5799        pp.setSeparateProcesses(mSeparateProcesses);
5800        pp.setOnlyCoreApps(mOnlyCore);
5801        pp.setDisplayMetrics(mMetrics);
5802
5803        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5804            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5805        }
5806
5807        final PackageParser.Package pkg;
5808        try {
5809            pkg = pp.parsePackage(scanFile, parseFlags);
5810        } catch (PackageParserException e) {
5811            throw PackageManagerException.from(e);
5812        }
5813
5814        PackageSetting ps = null;
5815        PackageSetting updatedPkg;
5816        // reader
5817        synchronized (mPackages) {
5818            // Look to see if we already know about this package.
5819            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5820            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5821                // This package has been renamed to its original name.  Let's
5822                // use that.
5823                ps = mSettings.peekPackageLPr(oldName);
5824            }
5825            // If there was no original package, see one for the real package name.
5826            if (ps == null) {
5827                ps = mSettings.peekPackageLPr(pkg.packageName);
5828            }
5829            // Check to see if this package could be hiding/updating a system
5830            // package.  Must look for it either under the original or real
5831            // package name depending on our state.
5832            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5833            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5834        }
5835        boolean updatedPkgBetter = false;
5836        // First check if this is a system package that may involve an update
5837        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5838            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5839            // it needs to drop FLAG_PRIVILEGED.
5840            if (locationIsPrivileged(scanFile)) {
5841                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5842            } else {
5843                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5844            }
5845
5846            if (ps != null && !ps.codePath.equals(scanFile)) {
5847                // The path has changed from what was last scanned...  check the
5848                // version of the new path against what we have stored to determine
5849                // what to do.
5850                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5851                if (pkg.mVersionCode <= ps.versionCode) {
5852                    // The system package has been updated and the code path does not match
5853                    // Ignore entry. Skip it.
5854                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5855                            + " ignored: updated version " + ps.versionCode
5856                            + " better than this " + pkg.mVersionCode);
5857                    if (!updatedPkg.codePath.equals(scanFile)) {
5858                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5859                                + ps.name + " changing from " + updatedPkg.codePathString
5860                                + " to " + scanFile);
5861                        updatedPkg.codePath = scanFile;
5862                        updatedPkg.codePathString = scanFile.toString();
5863                        updatedPkg.resourcePath = scanFile;
5864                        updatedPkg.resourcePathString = scanFile.toString();
5865                    }
5866                    updatedPkg.pkg = pkg;
5867                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5868                            "Package " + ps.name + " at " + scanFile
5869                                    + " ignored: updated version " + ps.versionCode
5870                                    + " better than this " + pkg.mVersionCode);
5871                } else {
5872                    // The current app on the system partition is better than
5873                    // what we have updated to on the data partition; switch
5874                    // back to the system partition version.
5875                    // At this point, its safely assumed that package installation for
5876                    // apps in system partition will go through. If not there won't be a working
5877                    // version of the app
5878                    // writer
5879                    synchronized (mPackages) {
5880                        // Just remove the loaded entries from package lists.
5881                        mPackages.remove(ps.name);
5882                    }
5883
5884                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5885                            + " reverting from " + ps.codePathString
5886                            + ": new version " + pkg.mVersionCode
5887                            + " better than installed " + ps.versionCode);
5888
5889                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5890                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5891                    synchronized (mInstallLock) {
5892                        args.cleanUpResourcesLI();
5893                    }
5894                    synchronized (mPackages) {
5895                        mSettings.enableSystemPackageLPw(ps.name);
5896                    }
5897                    updatedPkgBetter = true;
5898                }
5899            }
5900        }
5901
5902        if (updatedPkg != null) {
5903            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5904            // initially
5905            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5906
5907            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5908            // flag set initially
5909            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5910                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5911            }
5912        }
5913
5914        // Verify certificates against what was last scanned
5915        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5916
5917        /*
5918         * A new system app appeared, but we already had a non-system one of the
5919         * same name installed earlier.
5920         */
5921        boolean shouldHideSystemApp = false;
5922        if (updatedPkg == null && ps != null
5923                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5924            /*
5925             * Check to make sure the signatures match first. If they don't,
5926             * wipe the installed application and its data.
5927             */
5928            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5929                    != PackageManager.SIGNATURE_MATCH) {
5930                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5931                        + " signatures don't match existing userdata copy; removing");
5932                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5933                ps = null;
5934            } else {
5935                /*
5936                 * If the newly-added system app is an older version than the
5937                 * already installed version, hide it. It will be scanned later
5938                 * and re-added like an update.
5939                 */
5940                if (pkg.mVersionCode <= ps.versionCode) {
5941                    shouldHideSystemApp = true;
5942                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5943                            + " but new version " + pkg.mVersionCode + " better than installed "
5944                            + ps.versionCode + "; hiding system");
5945                } else {
5946                    /*
5947                     * The newly found system app is a newer version that the
5948                     * one previously installed. Simply remove the
5949                     * already-installed application and replace it with our own
5950                     * while keeping the application data.
5951                     */
5952                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5953                            + " reverting from " + ps.codePathString + ": new version "
5954                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5955                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5956                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5957                    synchronized (mInstallLock) {
5958                        args.cleanUpResourcesLI();
5959                    }
5960                }
5961            }
5962        }
5963
5964        // The apk is forward locked (not public) if its code and resources
5965        // are kept in different files. (except for app in either system or
5966        // vendor path).
5967        // TODO grab this value from PackageSettings
5968        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5969            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5970                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5971            }
5972        }
5973
5974        // TODO: extend to support forward-locked splits
5975        String resourcePath = null;
5976        String baseResourcePath = null;
5977        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5978            if (ps != null && ps.resourcePathString != null) {
5979                resourcePath = ps.resourcePathString;
5980                baseResourcePath = ps.resourcePathString;
5981            } else {
5982                // Should not happen at all. Just log an error.
5983                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5984            }
5985        } else {
5986            resourcePath = pkg.codePath;
5987            baseResourcePath = pkg.baseCodePath;
5988        }
5989
5990        // Set application objects path explicitly.
5991        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5992        pkg.applicationInfo.setCodePath(pkg.codePath);
5993        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5994        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5995        pkg.applicationInfo.setResourcePath(resourcePath);
5996        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5997        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5998
5999        // Note that we invoke the following method only if we are about to unpack an application
6000        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6001                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6002
6003        /*
6004         * If the system app should be overridden by a previously installed
6005         * data, hide the system app now and let the /data/app scan pick it up
6006         * again.
6007         */
6008        if (shouldHideSystemApp) {
6009            synchronized (mPackages) {
6010                mSettings.disableSystemPackageLPw(pkg.packageName);
6011            }
6012        }
6013
6014        return scannedPkg;
6015    }
6016
6017    private static String fixProcessName(String defProcessName,
6018            String processName, int uid) {
6019        if (processName == null) {
6020            return defProcessName;
6021        }
6022        return processName;
6023    }
6024
6025    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6026            throws PackageManagerException {
6027        if (pkgSetting.signatures.mSignatures != null) {
6028            // Already existing package. Make sure signatures match
6029            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6030                    == PackageManager.SIGNATURE_MATCH;
6031            if (!match) {
6032                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6033                        == PackageManager.SIGNATURE_MATCH;
6034            }
6035            if (!match) {
6036                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6037                        == PackageManager.SIGNATURE_MATCH;
6038            }
6039            if (!match) {
6040                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6041                        + pkg.packageName + " signatures do not match the "
6042                        + "previously installed version; ignoring!");
6043            }
6044        }
6045
6046        // Check for shared user signatures
6047        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6048            // Already existing package. Make sure signatures match
6049            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6050                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6051            if (!match) {
6052                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6053                        == PackageManager.SIGNATURE_MATCH;
6054            }
6055            if (!match) {
6056                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6057                        == PackageManager.SIGNATURE_MATCH;
6058            }
6059            if (!match) {
6060                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6061                        "Package " + pkg.packageName
6062                        + " has no signatures that match those in shared user "
6063                        + pkgSetting.sharedUser.name + "; ignoring!");
6064            }
6065        }
6066    }
6067
6068    /**
6069     * Enforces that only the system UID or root's UID can call a method exposed
6070     * via Binder.
6071     *
6072     * @param message used as message if SecurityException is thrown
6073     * @throws SecurityException if the caller is not system or root
6074     */
6075    private static final void enforceSystemOrRoot(String message) {
6076        final int uid = Binder.getCallingUid();
6077        if (uid != Process.SYSTEM_UID && uid != 0) {
6078            throw new SecurityException(message);
6079        }
6080    }
6081
6082    @Override
6083    public void performBootDexOpt() {
6084        enforceSystemOrRoot("Only the system can request dexopt be performed");
6085
6086        // Before everything else, see whether we need to fstrim.
6087        try {
6088            IMountService ms = PackageHelper.getMountService();
6089            if (ms != null) {
6090                final boolean isUpgrade = isUpgrade();
6091                boolean doTrim = isUpgrade;
6092                if (doTrim) {
6093                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6094                } else {
6095                    final long interval = android.provider.Settings.Global.getLong(
6096                            mContext.getContentResolver(),
6097                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6098                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6099                    if (interval > 0) {
6100                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6101                        if (timeSinceLast > interval) {
6102                            doTrim = true;
6103                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6104                                    + "; running immediately");
6105                        }
6106                    }
6107                }
6108                if (doTrim) {
6109                    if (!isFirstBoot()) {
6110                        try {
6111                            ActivityManagerNative.getDefault().showBootMessage(
6112                                    mContext.getResources().getString(
6113                                            R.string.android_upgrading_fstrim), true);
6114                        } catch (RemoteException e) {
6115                        }
6116                    }
6117                    ms.runMaintenance();
6118                }
6119            } else {
6120                Slog.e(TAG, "Mount service unavailable!");
6121            }
6122        } catch (RemoteException e) {
6123            // Can't happen; MountService is local
6124        }
6125
6126        final ArraySet<PackageParser.Package> pkgs;
6127        synchronized (mPackages) {
6128            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6129        }
6130
6131        if (pkgs != null) {
6132            // Sort apps by importance for dexopt ordering. Important apps are given more priority
6133            // in case the device runs out of space.
6134            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6135            // Give priority to core apps.
6136            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6137                PackageParser.Package pkg = it.next();
6138                if (pkg.coreApp) {
6139                    if (DEBUG_DEXOPT) {
6140                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6141                    }
6142                    sortedPkgs.add(pkg);
6143                    it.remove();
6144                }
6145            }
6146            // Give priority to system apps that listen for pre boot complete.
6147            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6148            ArraySet<String> pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM);
6149            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6150                PackageParser.Package pkg = it.next();
6151                if (pkgNames.contains(pkg.packageName)) {
6152                    if (DEBUG_DEXOPT) {
6153                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6154                    }
6155                    sortedPkgs.add(pkg);
6156                    it.remove();
6157                }
6158            }
6159            // Filter out packages that aren't recently used.
6160            filterRecentlyUsedApps(pkgs);
6161            // Add all remaining apps.
6162            for (PackageParser.Package pkg : pkgs) {
6163                if (DEBUG_DEXOPT) {
6164                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6165                }
6166                sortedPkgs.add(pkg);
6167            }
6168
6169            // If we want to be lazy, filter everything that wasn't recently used.
6170            if (mLazyDexOpt) {
6171                filterRecentlyUsedApps(sortedPkgs);
6172            }
6173
6174            int i = 0;
6175            int total = sortedPkgs.size();
6176            File dataDir = Environment.getDataDirectory();
6177            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6178            if (lowThreshold == 0) {
6179                throw new IllegalStateException("Invalid low memory threshold");
6180            }
6181            for (PackageParser.Package pkg : sortedPkgs) {
6182                long usableSpace = dataDir.getUsableSpace();
6183                if (usableSpace < lowThreshold) {
6184                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6185                    break;
6186                }
6187                performBootDexOpt(pkg, ++i, total);
6188            }
6189        }
6190    }
6191
6192    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6193        // Filter out packages that aren't recently used.
6194        //
6195        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6196        // should do a full dexopt.
6197        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6198            int total = pkgs.size();
6199            int skipped = 0;
6200            long now = System.currentTimeMillis();
6201            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6202                PackageParser.Package pkg = i.next();
6203                long then = pkg.mLastPackageUsageTimeInMills;
6204                if (then + mDexOptLRUThresholdInMills < now) {
6205                    if (DEBUG_DEXOPT) {
6206                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6207                              ((then == 0) ? "never" : new Date(then)));
6208                    }
6209                    i.remove();
6210                    skipped++;
6211                }
6212            }
6213            if (DEBUG_DEXOPT) {
6214                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6215            }
6216        }
6217    }
6218
6219    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6220        List<ResolveInfo> ris = null;
6221        try {
6222            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6223                    intent, null, 0, userId);
6224        } catch (RemoteException e) {
6225        }
6226        ArraySet<String> pkgNames = new ArraySet<String>();
6227        if (ris != null) {
6228            for (ResolveInfo ri : ris) {
6229                pkgNames.add(ri.activityInfo.packageName);
6230            }
6231        }
6232        return pkgNames;
6233    }
6234
6235    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6236        if (DEBUG_DEXOPT) {
6237            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6238        }
6239        if (!isFirstBoot()) {
6240            try {
6241                ActivityManagerNative.getDefault().showBootMessage(
6242                        mContext.getResources().getString(R.string.android_upgrading_apk,
6243                                curr, total), true);
6244            } catch (RemoteException e) {
6245            }
6246        }
6247        PackageParser.Package p = pkg;
6248        synchronized (mInstallLock) {
6249            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6250                    false /* force dex */, false /* defer */, true /* include dependencies */,
6251                    false /* boot complete */);
6252        }
6253    }
6254
6255    @Override
6256    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6257        return performDexOptTraced(packageName, instructionSet, false);
6258    }
6259
6260    public boolean performDexOpt(
6261            String packageName, String instructionSet, boolean backgroundDexopt) {
6262        return performDexOptTraced(packageName, instructionSet, backgroundDexopt);
6263    }
6264
6265    private boolean performDexOptTraced(
6266            String packageName, String instructionSet, boolean backgroundDexopt) {
6267        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6268        try {
6269            return performDexOptInternal(packageName, instructionSet, backgroundDexopt);
6270        } finally {
6271            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6272        }
6273    }
6274
6275    private boolean performDexOptInternal(
6276            String packageName, String instructionSet, boolean backgroundDexopt) {
6277        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6278        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6279        if (!dexopt && !updateUsage) {
6280            // We aren't going to dexopt or update usage, so bail early.
6281            return false;
6282        }
6283        PackageParser.Package p;
6284        final String targetInstructionSet;
6285        synchronized (mPackages) {
6286            p = mPackages.get(packageName);
6287            if (p == null) {
6288                return false;
6289            }
6290            if (updateUsage) {
6291                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6292            }
6293            mPackageUsage.write(false);
6294            if (!dexopt) {
6295                // We aren't going to dexopt, so bail early.
6296                return false;
6297            }
6298
6299            targetInstructionSet = instructionSet != null ? instructionSet :
6300                    getPrimaryInstructionSet(p.applicationInfo);
6301            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6302                return false;
6303            }
6304        }
6305        long callingId = Binder.clearCallingIdentity();
6306        try {
6307            synchronized (mInstallLock) {
6308                final String[] instructionSets = new String[] { targetInstructionSet };
6309                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6310                        false /* forceDex */, false /* defer */, true /* inclDependencies */,
6311                        true /* boot complete */);
6312                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6313            }
6314        } finally {
6315            Binder.restoreCallingIdentity(callingId);
6316        }
6317    }
6318
6319    public ArraySet<String> getPackagesThatNeedDexOpt() {
6320        ArraySet<String> pkgs = null;
6321        synchronized (mPackages) {
6322            for (PackageParser.Package p : mPackages.values()) {
6323                if (DEBUG_DEXOPT) {
6324                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6325                }
6326                if (!p.mDexOptPerformed.isEmpty()) {
6327                    continue;
6328                }
6329                if (pkgs == null) {
6330                    pkgs = new ArraySet<String>();
6331                }
6332                pkgs.add(p.packageName);
6333            }
6334        }
6335        return pkgs;
6336    }
6337
6338    public void shutdown() {
6339        mPackageUsage.write(true);
6340    }
6341
6342    @Override
6343    public void forceDexOpt(String packageName) {
6344        enforceSystemOrRoot("forceDexOpt");
6345
6346        PackageParser.Package pkg;
6347        synchronized (mPackages) {
6348            pkg = mPackages.get(packageName);
6349            if (pkg == null) {
6350                throw new IllegalArgumentException("Missing package: " + packageName);
6351            }
6352        }
6353
6354        synchronized (mInstallLock) {
6355            final String[] instructionSets = new String[] {
6356                    getPrimaryInstructionSet(pkg.applicationInfo) };
6357
6358            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6359
6360            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6361                    true /*forceDex*/, false /* defer */, true /* inclDependencies */,
6362                    true /* boot complete */);
6363
6364            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6365            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6366                throw new IllegalStateException("Failed to dexopt: " + res);
6367            }
6368        }
6369    }
6370
6371    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6372        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6373            Slog.w(TAG, "Unable to update from " + oldPkg.name
6374                    + " to " + newPkg.packageName
6375                    + ": old package not in system partition");
6376            return false;
6377        } else if (mPackages.get(oldPkg.name) != null) {
6378            Slog.w(TAG, "Unable to update from " + oldPkg.name
6379                    + " to " + newPkg.packageName
6380                    + ": old package still exists");
6381            return false;
6382        }
6383        return true;
6384    }
6385
6386    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6387        int[] users = sUserManager.getUserIds();
6388        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6389        if (res < 0) {
6390            return res;
6391        }
6392        for (int user : users) {
6393            if (user != 0) {
6394                res = mInstaller.createUserData(volumeUuid, packageName,
6395                        UserHandle.getUid(user, uid), user, seinfo);
6396                if (res < 0) {
6397                    return res;
6398                }
6399            }
6400        }
6401        return res;
6402    }
6403
6404    private int removeDataDirsLI(String volumeUuid, String packageName) {
6405        int[] users = sUserManager.getUserIds();
6406        int res = 0;
6407        for (int user : users) {
6408            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6409            if (resInner < 0) {
6410                res = resInner;
6411            }
6412        }
6413
6414        return res;
6415    }
6416
6417    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6418        int[] users = sUserManager.getUserIds();
6419        int res = 0;
6420        for (int user : users) {
6421            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6422            if (resInner < 0) {
6423                res = resInner;
6424            }
6425        }
6426        return res;
6427    }
6428
6429    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6430            PackageParser.Package changingLib) {
6431        if (file.path != null) {
6432            usesLibraryFiles.add(file.path);
6433            return;
6434        }
6435        PackageParser.Package p = mPackages.get(file.apk);
6436        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6437            // If we are doing this while in the middle of updating a library apk,
6438            // then we need to make sure to use that new apk for determining the
6439            // dependencies here.  (We haven't yet finished committing the new apk
6440            // to the package manager state.)
6441            if (p == null || p.packageName.equals(changingLib.packageName)) {
6442                p = changingLib;
6443            }
6444        }
6445        if (p != null) {
6446            usesLibraryFiles.addAll(p.getAllCodePaths());
6447        }
6448    }
6449
6450    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6451            PackageParser.Package changingLib) throws PackageManagerException {
6452        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6453            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6454            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6455            for (int i=0; i<N; i++) {
6456                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6457                if (file == null) {
6458                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6459                            "Package " + pkg.packageName + " requires unavailable shared library "
6460                            + pkg.usesLibraries.get(i) + "; failing!");
6461                }
6462                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6463            }
6464            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6465            for (int i=0; i<N; i++) {
6466                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6467                if (file == null) {
6468                    Slog.w(TAG, "Package " + pkg.packageName
6469                            + " desires unavailable shared library "
6470                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6471                } else {
6472                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6473                }
6474            }
6475            N = usesLibraryFiles.size();
6476            if (N > 0) {
6477                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6478            } else {
6479                pkg.usesLibraryFiles = null;
6480            }
6481        }
6482    }
6483
6484    private static boolean hasString(List<String> list, List<String> which) {
6485        if (list == null) {
6486            return false;
6487        }
6488        for (int i=list.size()-1; i>=0; i--) {
6489            for (int j=which.size()-1; j>=0; j--) {
6490                if (which.get(j).equals(list.get(i))) {
6491                    return true;
6492                }
6493            }
6494        }
6495        return false;
6496    }
6497
6498    private void updateAllSharedLibrariesLPw() {
6499        for (PackageParser.Package pkg : mPackages.values()) {
6500            try {
6501                updateSharedLibrariesLPw(pkg, null);
6502            } catch (PackageManagerException e) {
6503                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6504            }
6505        }
6506    }
6507
6508    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6509            PackageParser.Package changingPkg) {
6510        ArrayList<PackageParser.Package> res = null;
6511        for (PackageParser.Package pkg : mPackages.values()) {
6512            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6513                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6514                if (res == null) {
6515                    res = new ArrayList<PackageParser.Package>();
6516                }
6517                res.add(pkg);
6518                try {
6519                    updateSharedLibrariesLPw(pkg, changingPkg);
6520                } catch (PackageManagerException e) {
6521                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6522                }
6523            }
6524        }
6525        return res;
6526    }
6527
6528    /**
6529     * Derive the value of the {@code cpuAbiOverride} based on the provided
6530     * value and an optional stored value from the package settings.
6531     */
6532    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6533        String cpuAbiOverride = null;
6534
6535        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6536            cpuAbiOverride = null;
6537        } else if (abiOverride != null) {
6538            cpuAbiOverride = abiOverride;
6539        } else if (settings != null) {
6540            cpuAbiOverride = settings.cpuAbiOverrideString;
6541        }
6542
6543        return cpuAbiOverride;
6544    }
6545
6546    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6547            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6548        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6549        try {
6550            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6551        } finally {
6552            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6553        }
6554    }
6555
6556    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6557            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6558        boolean success = false;
6559        try {
6560            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6561                    currentTime, user);
6562            success = true;
6563            return res;
6564        } finally {
6565            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6566                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6567            }
6568        }
6569    }
6570
6571    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6572            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6573        final File scanFile = new File(pkg.codePath);
6574        if (pkg.applicationInfo.getCodePath() == null ||
6575                pkg.applicationInfo.getResourcePath() == null) {
6576            // Bail out. The resource and code paths haven't been set.
6577            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6578                    "Code and resource paths haven't been set correctly");
6579        }
6580
6581        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6582            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6583        } else {
6584            // Only allow system apps to be flagged as core apps.
6585            pkg.coreApp = false;
6586        }
6587
6588        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6589            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6590        }
6591
6592        if (mCustomResolverComponentName != null &&
6593                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6594            setUpCustomResolverActivity(pkg);
6595        }
6596
6597        if (pkg.packageName.equals("android")) {
6598            synchronized (mPackages) {
6599                if (mAndroidApplication != null) {
6600                    Slog.w(TAG, "*************************************************");
6601                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6602                    Slog.w(TAG, " file=" + scanFile);
6603                    Slog.w(TAG, "*************************************************");
6604                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6605                            "Core android package being redefined.  Skipping.");
6606                }
6607
6608                // Set up information for our fall-back user intent resolution activity.
6609                mPlatformPackage = pkg;
6610                pkg.mVersionCode = mSdkVersion;
6611                mAndroidApplication = pkg.applicationInfo;
6612
6613                if (!mResolverReplaced) {
6614                    mResolveActivity.applicationInfo = mAndroidApplication;
6615                    mResolveActivity.name = ResolverActivity.class.getName();
6616                    mResolveActivity.packageName = mAndroidApplication.packageName;
6617                    mResolveActivity.processName = "system:ui";
6618                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6619                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6620                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6621                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6622                    mResolveActivity.exported = true;
6623                    mResolveActivity.enabled = true;
6624                    mResolveInfo.activityInfo = mResolveActivity;
6625                    mResolveInfo.priority = 0;
6626                    mResolveInfo.preferredOrder = 0;
6627                    mResolveInfo.match = 0;
6628                    mResolveComponentName = new ComponentName(
6629                            mAndroidApplication.packageName, mResolveActivity.name);
6630                }
6631            }
6632        }
6633
6634        if (DEBUG_PACKAGE_SCANNING) {
6635            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6636                Log.d(TAG, "Scanning package " + pkg.packageName);
6637        }
6638
6639        if (mPackages.containsKey(pkg.packageName)
6640                || mSharedLibraries.containsKey(pkg.packageName)) {
6641            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6642                    "Application package " + pkg.packageName
6643                    + " already installed.  Skipping duplicate.");
6644        }
6645
6646        // If we're only installing presumed-existing packages, require that the
6647        // scanned APK is both already known and at the path previously established
6648        // for it.  Previously unknown packages we pick up normally, but if we have an
6649        // a priori expectation about this package's install presence, enforce it.
6650        // With a singular exception for new system packages. When an OTA contains
6651        // a new system package, we allow the codepath to change from a system location
6652        // to the user-installed location. If we don't allow this change, any newer,
6653        // user-installed version of the application will be ignored.
6654        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6655            if (mExpectingBetter.containsKey(pkg.packageName)) {
6656                logCriticalInfo(Log.WARN,
6657                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6658            } else {
6659                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6660                if (known != null) {
6661                    if (DEBUG_PACKAGE_SCANNING) {
6662                        Log.d(TAG, "Examining " + pkg.codePath
6663                                + " and requiring known paths " + known.codePathString
6664                                + " & " + known.resourcePathString);
6665                    }
6666                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6667                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6668                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6669                                "Application package " + pkg.packageName
6670                                + " found at " + pkg.applicationInfo.getCodePath()
6671                                + " but expected at " + known.codePathString + "; ignoring.");
6672                    }
6673                }
6674            }
6675        }
6676
6677        // Initialize package source and resource directories
6678        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6679        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6680
6681        SharedUserSetting suid = null;
6682        PackageSetting pkgSetting = null;
6683
6684        if (!isSystemApp(pkg)) {
6685            // Only system apps can use these features.
6686            pkg.mOriginalPackages = null;
6687            pkg.mRealPackage = null;
6688            pkg.mAdoptPermissions = null;
6689        }
6690
6691        // writer
6692        synchronized (mPackages) {
6693            if (pkg.mSharedUserId != null) {
6694                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6695                if (suid == null) {
6696                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6697                            "Creating application package " + pkg.packageName
6698                            + " for shared user failed");
6699                }
6700                if (DEBUG_PACKAGE_SCANNING) {
6701                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6702                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6703                                + "): packages=" + suid.packages);
6704                }
6705            }
6706
6707            // Check if we are renaming from an original package name.
6708            PackageSetting origPackage = null;
6709            String realName = null;
6710            if (pkg.mOriginalPackages != null) {
6711                // This package may need to be renamed to a previously
6712                // installed name.  Let's check on that...
6713                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6714                if (pkg.mOriginalPackages.contains(renamed)) {
6715                    // This package had originally been installed as the
6716                    // original name, and we have already taken care of
6717                    // transitioning to the new one.  Just update the new
6718                    // one to continue using the old name.
6719                    realName = pkg.mRealPackage;
6720                    if (!pkg.packageName.equals(renamed)) {
6721                        // Callers into this function may have already taken
6722                        // care of renaming the package; only do it here if
6723                        // it is not already done.
6724                        pkg.setPackageName(renamed);
6725                    }
6726
6727                } else {
6728                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6729                        if ((origPackage = mSettings.peekPackageLPr(
6730                                pkg.mOriginalPackages.get(i))) != null) {
6731                            // We do have the package already installed under its
6732                            // original name...  should we use it?
6733                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6734                                // New package is not compatible with original.
6735                                origPackage = null;
6736                                continue;
6737                            } else if (origPackage.sharedUser != null) {
6738                                // Make sure uid is compatible between packages.
6739                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6740                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6741                                            + " to " + pkg.packageName + ": old uid "
6742                                            + origPackage.sharedUser.name
6743                                            + " differs from " + pkg.mSharedUserId);
6744                                    origPackage = null;
6745                                    continue;
6746                                }
6747                            } else {
6748                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6749                                        + pkg.packageName + " to old name " + origPackage.name);
6750                            }
6751                            break;
6752                        }
6753                    }
6754                }
6755            }
6756
6757            if (mTransferedPackages.contains(pkg.packageName)) {
6758                Slog.w(TAG, "Package " + pkg.packageName
6759                        + " was transferred to another, but its .apk remains");
6760            }
6761
6762            // Just create the setting, don't add it yet. For already existing packages
6763            // the PkgSetting exists already and doesn't have to be created.
6764            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6765                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6766                    pkg.applicationInfo.primaryCpuAbi,
6767                    pkg.applicationInfo.secondaryCpuAbi,
6768                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6769                    user, false);
6770            if (pkgSetting == null) {
6771                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6772                        "Creating application package " + pkg.packageName + " failed");
6773            }
6774
6775            if (pkgSetting.origPackage != null) {
6776                // If we are first transitioning from an original package,
6777                // fix up the new package's name now.  We need to do this after
6778                // looking up the package under its new name, so getPackageLP
6779                // can take care of fiddling things correctly.
6780                pkg.setPackageName(origPackage.name);
6781
6782                // File a report about this.
6783                String msg = "New package " + pkgSetting.realName
6784                        + " renamed to replace old package " + pkgSetting.name;
6785                reportSettingsProblem(Log.WARN, msg);
6786
6787                // Make a note of it.
6788                mTransferedPackages.add(origPackage.name);
6789
6790                // No longer need to retain this.
6791                pkgSetting.origPackage = null;
6792            }
6793
6794            if (realName != null) {
6795                // Make a note of it.
6796                mTransferedPackages.add(pkg.packageName);
6797            }
6798
6799            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6800                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6801            }
6802
6803            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6804                // Check all shared libraries and map to their actual file path.
6805                // We only do this here for apps not on a system dir, because those
6806                // are the only ones that can fail an install due to this.  We
6807                // will take care of the system apps by updating all of their
6808                // library paths after the scan is done.
6809                updateSharedLibrariesLPw(pkg, null);
6810            }
6811
6812            if (mFoundPolicyFile) {
6813                SELinuxMMAC.assignSeinfoValue(pkg);
6814            }
6815
6816            pkg.applicationInfo.uid = pkgSetting.appId;
6817            pkg.mExtras = pkgSetting;
6818            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6819                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6820                    // We just determined the app is signed correctly, so bring
6821                    // over the latest parsed certs.
6822                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6823                } else {
6824                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6825                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6826                                "Package " + pkg.packageName + " upgrade keys do not match the "
6827                                + "previously installed version");
6828                    } else {
6829                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6830                        String msg = "System package " + pkg.packageName
6831                            + " signature changed; retaining data.";
6832                        reportSettingsProblem(Log.WARN, msg);
6833                    }
6834                }
6835            } else {
6836                try {
6837                    verifySignaturesLP(pkgSetting, pkg);
6838                    // We just determined the app is signed correctly, so bring
6839                    // over the latest parsed certs.
6840                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6841                } catch (PackageManagerException e) {
6842                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6843                        throw e;
6844                    }
6845                    // The signature has changed, but this package is in the system
6846                    // image...  let's recover!
6847                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6848                    // However...  if this package is part of a shared user, but it
6849                    // doesn't match the signature of the shared user, let's fail.
6850                    // What this means is that you can't change the signatures
6851                    // associated with an overall shared user, which doesn't seem all
6852                    // that unreasonable.
6853                    if (pkgSetting.sharedUser != null) {
6854                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6855                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6856                            throw new PackageManagerException(
6857                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6858                                            "Signature mismatch for shared user : "
6859                                            + pkgSetting.sharedUser);
6860                        }
6861                    }
6862                    // File a report about this.
6863                    String msg = "System package " + pkg.packageName
6864                        + " signature changed; retaining data.";
6865                    reportSettingsProblem(Log.WARN, msg);
6866                }
6867            }
6868            // Verify that this new package doesn't have any content providers
6869            // that conflict with existing packages.  Only do this if the
6870            // package isn't already installed, since we don't want to break
6871            // things that are installed.
6872            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6873                final int N = pkg.providers.size();
6874                int i;
6875                for (i=0; i<N; i++) {
6876                    PackageParser.Provider p = pkg.providers.get(i);
6877                    if (p.info.authority != null) {
6878                        String names[] = p.info.authority.split(";");
6879                        for (int j = 0; j < names.length; j++) {
6880                            if (mProvidersByAuthority.containsKey(names[j])) {
6881                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6882                                final String otherPackageName =
6883                                        ((other != null && other.getComponentName() != null) ?
6884                                                other.getComponentName().getPackageName() : "?");
6885                                throw new PackageManagerException(
6886                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6887                                                "Can't install because provider name " + names[j]
6888                                                + " (in package " + pkg.applicationInfo.packageName
6889                                                + ") is already used by " + otherPackageName);
6890                            }
6891                        }
6892                    }
6893                }
6894            }
6895
6896            if (pkg.mAdoptPermissions != null) {
6897                // This package wants to adopt ownership of permissions from
6898                // another package.
6899                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6900                    final String origName = pkg.mAdoptPermissions.get(i);
6901                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6902                    if (orig != null) {
6903                        if (verifyPackageUpdateLPr(orig, pkg)) {
6904                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6905                                    + pkg.packageName);
6906                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6907                        }
6908                    }
6909                }
6910            }
6911        }
6912
6913        final String pkgName = pkg.packageName;
6914
6915        final long scanFileTime = scanFile.lastModified();
6916        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6917        pkg.applicationInfo.processName = fixProcessName(
6918                pkg.applicationInfo.packageName,
6919                pkg.applicationInfo.processName,
6920                pkg.applicationInfo.uid);
6921
6922        File dataPath;
6923        if (mPlatformPackage == pkg) {
6924            // The system package is special.
6925            dataPath = new File(Environment.getDataDirectory(), "system");
6926
6927            pkg.applicationInfo.dataDir = dataPath.getPath();
6928
6929        } else {
6930            // This is a normal package, need to make its data directory.
6931            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6932                    UserHandle.USER_OWNER, pkg.packageName);
6933
6934            boolean uidError = false;
6935            if (dataPath.exists()) {
6936                int currentUid = 0;
6937                try {
6938                    StructStat stat = Os.stat(dataPath.getPath());
6939                    currentUid = stat.st_uid;
6940                } catch (ErrnoException e) {
6941                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6942                }
6943
6944                // If we have mismatched owners for the data path, we have a problem.
6945                if (currentUid != pkg.applicationInfo.uid) {
6946                    boolean recovered = false;
6947                    if (currentUid == 0) {
6948                        // The directory somehow became owned by root.  Wow.
6949                        // This is probably because the system was stopped while
6950                        // installd was in the middle of messing with its libs
6951                        // directory.  Ask installd to fix that.
6952                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6953                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6954                        if (ret >= 0) {
6955                            recovered = true;
6956                            String msg = "Package " + pkg.packageName
6957                                    + " unexpectedly changed to uid 0; recovered to " +
6958                                    + pkg.applicationInfo.uid;
6959                            reportSettingsProblem(Log.WARN, msg);
6960                        }
6961                    }
6962                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6963                            || (scanFlags&SCAN_BOOTING) != 0)) {
6964                        // If this is a system app, we can at least delete its
6965                        // current data so the application will still work.
6966                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6967                        if (ret >= 0) {
6968                            // TODO: Kill the processes first
6969                            // Old data gone!
6970                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6971                                    ? "System package " : "Third party package ";
6972                            String msg = prefix + pkg.packageName
6973                                    + " has changed from uid: "
6974                                    + currentUid + " to "
6975                                    + pkg.applicationInfo.uid + "; old data erased";
6976                            reportSettingsProblem(Log.WARN, msg);
6977                            recovered = true;
6978
6979                            // And now re-install the app.
6980                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6981                                    pkg.applicationInfo.seinfo);
6982                            if (ret == -1) {
6983                                // Ack should not happen!
6984                                msg = prefix + pkg.packageName
6985                                        + " could not have data directory re-created after delete.";
6986                                reportSettingsProblem(Log.WARN, msg);
6987                                throw new PackageManagerException(
6988                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6989                            }
6990                        }
6991                        if (!recovered) {
6992                            mHasSystemUidErrors = true;
6993                        }
6994                    } else if (!recovered) {
6995                        // If we allow this install to proceed, we will be broken.
6996                        // Abort, abort!
6997                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6998                                "scanPackageLI");
6999                    }
7000                    if (!recovered) {
7001                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7002                            + pkg.applicationInfo.uid + "/fs_"
7003                            + currentUid;
7004                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7005                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7006                        String msg = "Package " + pkg.packageName
7007                                + " has mismatched uid: "
7008                                + currentUid + " on disk, "
7009                                + pkg.applicationInfo.uid + " in settings";
7010                        // writer
7011                        synchronized (mPackages) {
7012                            mSettings.mReadMessages.append(msg);
7013                            mSettings.mReadMessages.append('\n');
7014                            uidError = true;
7015                            if (!pkgSetting.uidError) {
7016                                reportSettingsProblem(Log.ERROR, msg);
7017                            }
7018                        }
7019                    }
7020                }
7021                pkg.applicationInfo.dataDir = dataPath.getPath();
7022                if (mShouldRestoreconData) {
7023                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7024                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7025                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7026                }
7027            } else {
7028                if (DEBUG_PACKAGE_SCANNING) {
7029                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7030                        Log.v(TAG, "Want this data dir: " + dataPath);
7031                }
7032                //invoke installer to do the actual installation
7033                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7034                        pkg.applicationInfo.seinfo);
7035                if (ret < 0) {
7036                    // Error from installer
7037                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7038                            "Unable to create data dirs [errorCode=" + ret + "]");
7039                }
7040
7041                if (dataPath.exists()) {
7042                    pkg.applicationInfo.dataDir = dataPath.getPath();
7043                } else {
7044                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
7045                    pkg.applicationInfo.dataDir = null;
7046                }
7047            }
7048
7049            pkgSetting.uidError = uidError;
7050        }
7051
7052        final String path = scanFile.getPath();
7053        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7054
7055        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7056            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7057
7058            // Some system apps still use directory structure for native libraries
7059            // in which case we might end up not detecting abi solely based on apk
7060            // structure. Try to detect abi based on directory structure.
7061            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7062                    pkg.applicationInfo.primaryCpuAbi == null) {
7063                setBundledAppAbisAndRoots(pkg, pkgSetting);
7064                setNativeLibraryPaths(pkg);
7065            }
7066
7067        } else {
7068            if ((scanFlags & SCAN_MOVE) != 0) {
7069                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7070                // but we already have this packages package info in the PackageSetting. We just
7071                // use that and derive the native library path based on the new codepath.
7072                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7073                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7074            }
7075
7076            // Set native library paths again. For moves, the path will be updated based on the
7077            // ABIs we've determined above. For non-moves, the path will be updated based on the
7078            // ABIs we determined during compilation, but the path will depend on the final
7079            // package path (after the rename away from the stage path).
7080            setNativeLibraryPaths(pkg);
7081        }
7082
7083        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7084        final int[] userIds = sUserManager.getUserIds();
7085        synchronized (mInstallLock) {
7086            // Make sure all user data directories are ready to roll; we're okay
7087            // if they already exist
7088            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7089                for (int userId : userIds) {
7090                    if (userId != 0) {
7091                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7092                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7093                                pkg.applicationInfo.seinfo);
7094                    }
7095                }
7096            }
7097
7098            // Create a native library symlink only if we have native libraries
7099            // and if the native libraries are 32 bit libraries. We do not provide
7100            // this symlink for 64 bit libraries.
7101            if (pkg.applicationInfo.primaryCpuAbi != null &&
7102                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7103                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7104                try {
7105                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7106                    for (int userId : userIds) {
7107                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7108                                nativeLibPath, userId) < 0) {
7109                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7110                                    "Failed linking native library dir (user=" + userId + ")");
7111                        }
7112                    }
7113                } finally {
7114                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7115                }
7116            }
7117        }
7118
7119        // This is a special case for the "system" package, where the ABI is
7120        // dictated by the zygote configuration (and init.rc). We should keep track
7121        // of this ABI so that we can deal with "normal" applications that run under
7122        // the same UID correctly.
7123        if (mPlatformPackage == pkg) {
7124            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7125                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7126        }
7127
7128        // If there's a mismatch between the abi-override in the package setting
7129        // and the abiOverride specified for the install. Warn about this because we
7130        // would've already compiled the app without taking the package setting into
7131        // account.
7132        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7133            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7134                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7135                        " for package: " + pkg.packageName);
7136            }
7137        }
7138
7139        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7140        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7141        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7142
7143        // Copy the derived override back to the parsed package, so that we can
7144        // update the package settings accordingly.
7145        pkg.cpuAbiOverride = cpuAbiOverride;
7146
7147        if (DEBUG_ABI_SELECTION) {
7148            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7149                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7150                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7151        }
7152
7153        // Push the derived path down into PackageSettings so we know what to
7154        // clean up at uninstall time.
7155        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7156
7157        if (DEBUG_ABI_SELECTION) {
7158            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7159                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7160                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7161        }
7162
7163        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7164            // We don't do this here during boot because we can do it all
7165            // at once after scanning all existing packages.
7166            //
7167            // We also do this *before* we perform dexopt on this package, so that
7168            // we can avoid redundant dexopts, and also to make sure we've got the
7169            // code and package path correct.
7170            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7171                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */);
7172        }
7173
7174        if ((scanFlags & SCAN_NO_DEX) == 0) {
7175            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7176
7177            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7178                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */,
7179                    (scanFlags & SCAN_BOOTING) == 0);
7180
7181            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7182            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7183                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7184            }
7185        }
7186        if (mFactoryTest && pkg.requestedPermissions.contains(
7187                android.Manifest.permission.FACTORY_TEST)) {
7188            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7189        }
7190
7191        ArrayList<PackageParser.Package> clientLibPkgs = null;
7192
7193        // writer
7194        synchronized (mPackages) {
7195            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7196                // Only system apps can add new shared libraries.
7197                if (pkg.libraryNames != null) {
7198                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7199                        String name = pkg.libraryNames.get(i);
7200                        boolean allowed = false;
7201                        if (pkg.isUpdatedSystemApp()) {
7202                            // New library entries can only be added through the
7203                            // system image.  This is important to get rid of a lot
7204                            // of nasty edge cases: for example if we allowed a non-
7205                            // system update of the app to add a library, then uninstalling
7206                            // the update would make the library go away, and assumptions
7207                            // we made such as through app install filtering would now
7208                            // have allowed apps on the device which aren't compatible
7209                            // with it.  Better to just have the restriction here, be
7210                            // conservative, and create many fewer cases that can negatively
7211                            // impact the user experience.
7212                            final PackageSetting sysPs = mSettings
7213                                    .getDisabledSystemPkgLPr(pkg.packageName);
7214                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7215                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7216                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7217                                        allowed = true;
7218                                        allowed = true;
7219                                        break;
7220                                    }
7221                                }
7222                            }
7223                        } else {
7224                            allowed = true;
7225                        }
7226                        if (allowed) {
7227                            if (!mSharedLibraries.containsKey(name)) {
7228                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7229                            } else if (!name.equals(pkg.packageName)) {
7230                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7231                                        + name + " already exists; skipping");
7232                            }
7233                        } else {
7234                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7235                                    + name + " that is not declared on system image; skipping");
7236                        }
7237                    }
7238                    if ((scanFlags&SCAN_BOOTING) == 0) {
7239                        // If we are not booting, we need to update any applications
7240                        // that are clients of our shared library.  If we are booting,
7241                        // this will all be done once the scan is complete.
7242                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7243                    }
7244                }
7245            }
7246        }
7247
7248        // We also need to dexopt any apps that are dependent on this library.  Note that
7249        // if these fail, we should abort the install since installing the library will
7250        // result in some apps being broken.
7251        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7252        try {
7253            if (clientLibPkgs != null) {
7254                if ((scanFlags & SCAN_NO_DEX) == 0) {
7255                    for (int i = 0; i < clientLibPkgs.size(); i++) {
7256                        PackageParser.Package clientPkg = clientLibPkgs.get(i);
7257                        int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7258                                null /* instruction sets */, forceDex,
7259                                (scanFlags & SCAN_DEFER_DEX) != 0, false,
7260                                (scanFlags & SCAN_BOOTING) == 0);
7261                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7262                            throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7263                                    "scanPackageLI failed to dexopt clientLibPkgs");
7264                        }
7265                    }
7266                }
7267            }
7268        } finally {
7269            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7270        }
7271
7272        // Request the ActivityManager to kill the process(only for existing packages)
7273        // so that we do not end up in a confused state while the user is still using the older
7274        // version of the application while the new one gets installed.
7275        if ((scanFlags & SCAN_REPLACING) != 0) {
7276            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7277
7278            killApplication(pkg.applicationInfo.packageName,
7279                        pkg.applicationInfo.uid, "replace pkg");
7280
7281            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7282        }
7283
7284        // Also need to kill any apps that are dependent on the library.
7285        if (clientLibPkgs != null) {
7286            for (int i=0; i<clientLibPkgs.size(); i++) {
7287                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7288                killApplication(clientPkg.applicationInfo.packageName,
7289                        clientPkg.applicationInfo.uid, "update lib");
7290            }
7291        }
7292
7293        // Make sure we're not adding any bogus keyset info
7294        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7295        ksms.assertScannedPackageValid(pkg);
7296
7297        // writer
7298        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7299
7300        boolean createIdmapFailed = false;
7301        synchronized (mPackages) {
7302            // We don't expect installation to fail beyond this point
7303
7304            // Add the new setting to mSettings
7305            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7306            // Add the new setting to mPackages
7307            mPackages.put(pkg.applicationInfo.packageName, pkg);
7308            // Make sure we don't accidentally delete its data.
7309            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7310            while (iter.hasNext()) {
7311                PackageCleanItem item = iter.next();
7312                if (pkgName.equals(item.packageName)) {
7313                    iter.remove();
7314                }
7315            }
7316
7317            // Take care of first install / last update times.
7318            if (currentTime != 0) {
7319                if (pkgSetting.firstInstallTime == 0) {
7320                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7321                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7322                    pkgSetting.lastUpdateTime = currentTime;
7323                }
7324            } else if (pkgSetting.firstInstallTime == 0) {
7325                // We need *something*.  Take time time stamp of the file.
7326                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7327            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7328                if (scanFileTime != pkgSetting.timeStamp) {
7329                    // A package on the system image has changed; consider this
7330                    // to be an update.
7331                    pkgSetting.lastUpdateTime = scanFileTime;
7332                }
7333            }
7334
7335            // Add the package's KeySets to the global KeySetManagerService
7336            ksms.addScannedPackageLPw(pkg);
7337
7338            int N = pkg.providers.size();
7339            StringBuilder r = null;
7340            int i;
7341            for (i=0; i<N; i++) {
7342                PackageParser.Provider p = pkg.providers.get(i);
7343                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7344                        p.info.processName, pkg.applicationInfo.uid);
7345                mProviders.addProvider(p);
7346                p.syncable = p.info.isSyncable;
7347                if (p.info.authority != null) {
7348                    String names[] = p.info.authority.split(";");
7349                    p.info.authority = null;
7350                    for (int j = 0; j < names.length; j++) {
7351                        if (j == 1 && p.syncable) {
7352                            // We only want the first authority for a provider to possibly be
7353                            // syncable, so if we already added this provider using a different
7354                            // authority clear the syncable flag. We copy the provider before
7355                            // changing it because the mProviders object contains a reference
7356                            // to a provider that we don't want to change.
7357                            // Only do this for the second authority since the resulting provider
7358                            // object can be the same for all future authorities for this provider.
7359                            p = new PackageParser.Provider(p);
7360                            p.syncable = false;
7361                        }
7362                        if (!mProvidersByAuthority.containsKey(names[j])) {
7363                            mProvidersByAuthority.put(names[j], p);
7364                            if (p.info.authority == null) {
7365                                p.info.authority = names[j];
7366                            } else {
7367                                p.info.authority = p.info.authority + ";" + names[j];
7368                            }
7369                            if (DEBUG_PACKAGE_SCANNING) {
7370                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7371                                    Log.d(TAG, "Registered content provider: " + names[j]
7372                                            + ", className = " + p.info.name + ", isSyncable = "
7373                                            + p.info.isSyncable);
7374                            }
7375                        } else {
7376                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7377                            Slog.w(TAG, "Skipping provider name " + names[j] +
7378                                    " (in package " + pkg.applicationInfo.packageName +
7379                                    "): name already used by "
7380                                    + ((other != null && other.getComponentName() != null)
7381                                            ? other.getComponentName().getPackageName() : "?"));
7382                        }
7383                    }
7384                }
7385                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7386                    if (r == null) {
7387                        r = new StringBuilder(256);
7388                    } else {
7389                        r.append(' ');
7390                    }
7391                    r.append(p.info.name);
7392                }
7393            }
7394            if (r != null) {
7395                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7396            }
7397
7398            N = pkg.services.size();
7399            r = null;
7400            for (i=0; i<N; i++) {
7401                PackageParser.Service s = pkg.services.get(i);
7402                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7403                        s.info.processName, pkg.applicationInfo.uid);
7404                mServices.addService(s);
7405                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7406                    if (r == null) {
7407                        r = new StringBuilder(256);
7408                    } else {
7409                        r.append(' ');
7410                    }
7411                    r.append(s.info.name);
7412                }
7413            }
7414            if (r != null) {
7415                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7416            }
7417
7418            N = pkg.receivers.size();
7419            r = null;
7420            for (i=0; i<N; i++) {
7421                PackageParser.Activity a = pkg.receivers.get(i);
7422                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7423                        a.info.processName, pkg.applicationInfo.uid);
7424                mReceivers.addActivity(a, "receiver");
7425                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7426                    if (r == null) {
7427                        r = new StringBuilder(256);
7428                    } else {
7429                        r.append(' ');
7430                    }
7431                    r.append(a.info.name);
7432                }
7433            }
7434            if (r != null) {
7435                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7436            }
7437
7438            N = pkg.activities.size();
7439            r = null;
7440            for (i=0; i<N; i++) {
7441                PackageParser.Activity a = pkg.activities.get(i);
7442                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7443                        a.info.processName, pkg.applicationInfo.uid);
7444                mActivities.addActivity(a, "activity");
7445                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7446                    if (r == null) {
7447                        r = new StringBuilder(256);
7448                    } else {
7449                        r.append(' ');
7450                    }
7451                    r.append(a.info.name);
7452                }
7453            }
7454            if (r != null) {
7455                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7456            }
7457
7458            N = pkg.permissionGroups.size();
7459            r = null;
7460            for (i=0; i<N; i++) {
7461                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7462                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7463                if (cur == null) {
7464                    mPermissionGroups.put(pg.info.name, pg);
7465                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7466                        if (r == null) {
7467                            r = new StringBuilder(256);
7468                        } else {
7469                            r.append(' ');
7470                        }
7471                        r.append(pg.info.name);
7472                    }
7473                } else {
7474                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7475                            + pg.info.packageName + " ignored: original from "
7476                            + cur.info.packageName);
7477                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7478                        if (r == null) {
7479                            r = new StringBuilder(256);
7480                        } else {
7481                            r.append(' ');
7482                        }
7483                        r.append("DUP:");
7484                        r.append(pg.info.name);
7485                    }
7486                }
7487            }
7488            if (r != null) {
7489                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7490            }
7491
7492            N = pkg.permissions.size();
7493            r = null;
7494            for (i=0; i<N; i++) {
7495                PackageParser.Permission p = pkg.permissions.get(i);
7496
7497                // Assume by default that we did not install this permission into the system.
7498                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7499
7500                // Now that permission groups have a special meaning, we ignore permission
7501                // groups for legacy apps to prevent unexpected behavior. In particular,
7502                // permissions for one app being granted to someone just becuase they happen
7503                // to be in a group defined by another app (before this had no implications).
7504                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7505                    p.group = mPermissionGroups.get(p.info.group);
7506                    // Warn for a permission in an unknown group.
7507                    if (p.info.group != null && p.group == null) {
7508                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7509                                + p.info.packageName + " in an unknown group " + p.info.group);
7510                    }
7511                }
7512
7513                ArrayMap<String, BasePermission> permissionMap =
7514                        p.tree ? mSettings.mPermissionTrees
7515                                : mSettings.mPermissions;
7516                BasePermission bp = permissionMap.get(p.info.name);
7517
7518                // Allow system apps to redefine non-system permissions
7519                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7520                    final boolean currentOwnerIsSystem = (bp.perm != null
7521                            && isSystemApp(bp.perm.owner));
7522                    if (isSystemApp(p.owner)) {
7523                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7524                            // It's a built-in permission and no owner, take ownership now
7525                            bp.packageSetting = pkgSetting;
7526                            bp.perm = p;
7527                            bp.uid = pkg.applicationInfo.uid;
7528                            bp.sourcePackage = p.info.packageName;
7529                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7530                        } else if (!currentOwnerIsSystem) {
7531                            String msg = "New decl " + p.owner + " of permission  "
7532                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7533                            reportSettingsProblem(Log.WARN, msg);
7534                            bp = null;
7535                        }
7536                    }
7537                }
7538
7539                if (bp == null) {
7540                    bp = new BasePermission(p.info.name, p.info.packageName,
7541                            BasePermission.TYPE_NORMAL);
7542                    permissionMap.put(p.info.name, bp);
7543                }
7544
7545                if (bp.perm == null) {
7546                    if (bp.sourcePackage == null
7547                            || bp.sourcePackage.equals(p.info.packageName)) {
7548                        BasePermission tree = findPermissionTreeLP(p.info.name);
7549                        if (tree == null
7550                                || tree.sourcePackage.equals(p.info.packageName)) {
7551                            bp.packageSetting = pkgSetting;
7552                            bp.perm = p;
7553                            bp.uid = pkg.applicationInfo.uid;
7554                            bp.sourcePackage = p.info.packageName;
7555                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7556                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7557                                if (r == null) {
7558                                    r = new StringBuilder(256);
7559                                } else {
7560                                    r.append(' ');
7561                                }
7562                                r.append(p.info.name);
7563                            }
7564                        } else {
7565                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7566                                    + p.info.packageName + " ignored: base tree "
7567                                    + tree.name + " is from package "
7568                                    + tree.sourcePackage);
7569                        }
7570                    } else {
7571                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7572                                + p.info.packageName + " ignored: original from "
7573                                + bp.sourcePackage);
7574                    }
7575                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7576                    if (r == null) {
7577                        r = new StringBuilder(256);
7578                    } else {
7579                        r.append(' ');
7580                    }
7581                    r.append("DUP:");
7582                    r.append(p.info.name);
7583                }
7584                if (bp.perm == p) {
7585                    bp.protectionLevel = p.info.protectionLevel;
7586                }
7587            }
7588
7589            if (r != null) {
7590                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7591            }
7592
7593            N = pkg.instrumentation.size();
7594            r = null;
7595            for (i=0; i<N; i++) {
7596                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7597                a.info.packageName = pkg.applicationInfo.packageName;
7598                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7599                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7600                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7601                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7602                a.info.dataDir = pkg.applicationInfo.dataDir;
7603
7604                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7605                // need other information about the application, like the ABI and what not ?
7606                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7607                mInstrumentation.put(a.getComponentName(), a);
7608                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7609                    if (r == null) {
7610                        r = new StringBuilder(256);
7611                    } else {
7612                        r.append(' ');
7613                    }
7614                    r.append(a.info.name);
7615                }
7616            }
7617            if (r != null) {
7618                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7619            }
7620
7621            if (pkg.protectedBroadcasts != null) {
7622                N = pkg.protectedBroadcasts.size();
7623                for (i=0; i<N; i++) {
7624                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7625                }
7626            }
7627
7628            pkgSetting.setTimeStamp(scanFileTime);
7629
7630            // Create idmap files for pairs of (packages, overlay packages).
7631            // Note: "android", ie framework-res.apk, is handled by native layers.
7632            if (pkg.mOverlayTarget != null) {
7633                // This is an overlay package.
7634                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7635                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7636                        mOverlays.put(pkg.mOverlayTarget,
7637                                new ArrayMap<String, PackageParser.Package>());
7638                    }
7639                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7640                    map.put(pkg.packageName, pkg);
7641                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7642                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7643                        createIdmapFailed = true;
7644                    }
7645                }
7646            } else if (mOverlays.containsKey(pkg.packageName) &&
7647                    !pkg.packageName.equals("android")) {
7648                // This is a regular package, with one or more known overlay packages.
7649                createIdmapsForPackageLI(pkg);
7650            }
7651        }
7652
7653        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7654
7655        if (createIdmapFailed) {
7656            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7657                    "scanPackageLI failed to createIdmap");
7658        }
7659        return pkg;
7660    }
7661
7662    /**
7663     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7664     * is derived purely on the basis of the contents of {@code scanFile} and
7665     * {@code cpuAbiOverride}.
7666     *
7667     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7668     */
7669    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7670                                 String cpuAbiOverride, boolean extractLibs)
7671            throws PackageManagerException {
7672        // TODO: We can probably be smarter about this stuff. For installed apps,
7673        // we can calculate this information at install time once and for all. For
7674        // system apps, we can probably assume that this information doesn't change
7675        // after the first boot scan. As things stand, we do lots of unnecessary work.
7676
7677        // Give ourselves some initial paths; we'll come back for another
7678        // pass once we've determined ABI below.
7679        setNativeLibraryPaths(pkg);
7680
7681        // We would never need to extract libs for forward-locked and external packages,
7682        // since the container service will do it for us. We shouldn't attempt to
7683        // extract libs from system app when it was not updated.
7684        if (pkg.isForwardLocked() || isExternal(pkg) ||
7685            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7686            extractLibs = false;
7687        }
7688
7689        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7690        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7691
7692        NativeLibraryHelper.Handle handle = null;
7693        try {
7694            handle = NativeLibraryHelper.Handle.create(pkg);
7695            // TODO(multiArch): This can be null for apps that didn't go through the
7696            // usual installation process. We can calculate it again, like we
7697            // do during install time.
7698            //
7699            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7700            // unnecessary.
7701            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7702
7703            // Null out the abis so that they can be recalculated.
7704            pkg.applicationInfo.primaryCpuAbi = null;
7705            pkg.applicationInfo.secondaryCpuAbi = null;
7706            if (isMultiArch(pkg.applicationInfo)) {
7707                // Warn if we've set an abiOverride for multi-lib packages..
7708                // By definition, we need to copy both 32 and 64 bit libraries for
7709                // such packages.
7710                if (pkg.cpuAbiOverride != null
7711                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7712                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7713                }
7714
7715                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7716                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7717                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7718                    if (extractLibs) {
7719                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7720                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7721                                useIsaSpecificSubdirs);
7722                    } else {
7723                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7724                    }
7725                }
7726
7727                maybeThrowExceptionForMultiArchCopy(
7728                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7729
7730                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7731                    if (extractLibs) {
7732                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7733                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7734                                useIsaSpecificSubdirs);
7735                    } else {
7736                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7737                    }
7738                }
7739
7740                maybeThrowExceptionForMultiArchCopy(
7741                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7742
7743                if (abi64 >= 0) {
7744                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7745                }
7746
7747                if (abi32 >= 0) {
7748                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7749                    if (abi64 >= 0) {
7750                        pkg.applicationInfo.secondaryCpuAbi = abi;
7751                    } else {
7752                        pkg.applicationInfo.primaryCpuAbi = abi;
7753                    }
7754                }
7755            } else {
7756                String[] abiList = (cpuAbiOverride != null) ?
7757                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7758
7759                // Enable gross and lame hacks for apps that are built with old
7760                // SDK tools. We must scan their APKs for renderscript bitcode and
7761                // not launch them if it's present. Don't bother checking on devices
7762                // that don't have 64 bit support.
7763                boolean needsRenderScriptOverride = false;
7764                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7765                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7766                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7767                    needsRenderScriptOverride = true;
7768                }
7769
7770                final int copyRet;
7771                if (extractLibs) {
7772                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7773                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7774                } else {
7775                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7776                }
7777
7778                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7779                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7780                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7781                }
7782
7783                if (copyRet >= 0) {
7784                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7785                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7786                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7787                } else if (needsRenderScriptOverride) {
7788                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7789                }
7790            }
7791        } catch (IOException ioe) {
7792            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7793        } finally {
7794            IoUtils.closeQuietly(handle);
7795        }
7796
7797        // Now that we've calculated the ABIs and determined if it's an internal app,
7798        // we will go ahead and populate the nativeLibraryPath.
7799        setNativeLibraryPaths(pkg);
7800    }
7801
7802    /**
7803     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7804     * i.e, so that all packages can be run inside a single process if required.
7805     *
7806     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7807     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7808     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7809     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7810     * updating a package that belongs to a shared user.
7811     *
7812     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7813     * adds unnecessary complexity.
7814     */
7815    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7816            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt,
7817            boolean bootComplete) {
7818        String requiredInstructionSet = null;
7819        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7820            requiredInstructionSet = VMRuntime.getInstructionSet(
7821                     scannedPackage.applicationInfo.primaryCpuAbi);
7822        }
7823
7824        PackageSetting requirer = null;
7825        for (PackageSetting ps : packagesForUser) {
7826            // If packagesForUser contains scannedPackage, we skip it. This will happen
7827            // when scannedPackage is an update of an existing package. Without this check,
7828            // we will never be able to change the ABI of any package belonging to a shared
7829            // user, even if it's compatible with other packages.
7830            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7831                if (ps.primaryCpuAbiString == null) {
7832                    continue;
7833                }
7834
7835                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7836                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7837                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7838                    // this but there's not much we can do.
7839                    String errorMessage = "Instruction set mismatch, "
7840                            + ((requirer == null) ? "[caller]" : requirer)
7841                            + " requires " + requiredInstructionSet + " whereas " + ps
7842                            + " requires " + instructionSet;
7843                    Slog.w(TAG, errorMessage);
7844                }
7845
7846                if (requiredInstructionSet == null) {
7847                    requiredInstructionSet = instructionSet;
7848                    requirer = ps;
7849                }
7850            }
7851        }
7852
7853        if (requiredInstructionSet != null) {
7854            String adjustedAbi;
7855            if (requirer != null) {
7856                // requirer != null implies that either scannedPackage was null or that scannedPackage
7857                // did not require an ABI, in which case we have to adjust scannedPackage to match
7858                // the ABI of the set (which is the same as requirer's ABI)
7859                adjustedAbi = requirer.primaryCpuAbiString;
7860                if (scannedPackage != null) {
7861                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7862                }
7863            } else {
7864                // requirer == null implies that we're updating all ABIs in the set to
7865                // match scannedPackage.
7866                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7867            }
7868
7869            for (PackageSetting ps : packagesForUser) {
7870                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7871                    if (ps.primaryCpuAbiString != null) {
7872                        continue;
7873                    }
7874
7875                    ps.primaryCpuAbiString = adjustedAbi;
7876                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7877                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7878                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7879
7880                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7881
7882                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7883                                null /* instruction sets */, forceDexOpt, deferDexOpt, true,
7884                                bootComplete);
7885
7886                        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7887                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7888                            ps.primaryCpuAbiString = null;
7889                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7890                            return;
7891                        } else {
7892                            mInstaller.rmdex(ps.codePathString,
7893                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7894                        }
7895                    }
7896                }
7897            }
7898        }
7899    }
7900
7901    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7902        synchronized (mPackages) {
7903            mResolverReplaced = true;
7904            // Set up information for custom user intent resolution activity.
7905            mResolveActivity.applicationInfo = pkg.applicationInfo;
7906            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7907            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7908            mResolveActivity.processName = pkg.applicationInfo.packageName;
7909            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7910            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7911                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7912            mResolveActivity.theme = 0;
7913            mResolveActivity.exported = true;
7914            mResolveActivity.enabled = true;
7915            mResolveInfo.activityInfo = mResolveActivity;
7916            mResolveInfo.priority = 0;
7917            mResolveInfo.preferredOrder = 0;
7918            mResolveInfo.match = 0;
7919            mResolveComponentName = mCustomResolverComponentName;
7920            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7921                    mResolveComponentName);
7922        }
7923    }
7924
7925    private static String calculateBundledApkRoot(final String codePathString) {
7926        final File codePath = new File(codePathString);
7927        final File codeRoot;
7928        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7929            codeRoot = Environment.getRootDirectory();
7930        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7931            codeRoot = Environment.getOemDirectory();
7932        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7933            codeRoot = Environment.getVendorDirectory();
7934        } else {
7935            // Unrecognized code path; take its top real segment as the apk root:
7936            // e.g. /something/app/blah.apk => /something
7937            try {
7938                File f = codePath.getCanonicalFile();
7939                File parent = f.getParentFile();    // non-null because codePath is a file
7940                File tmp;
7941                while ((tmp = parent.getParentFile()) != null) {
7942                    f = parent;
7943                    parent = tmp;
7944                }
7945                codeRoot = f;
7946                Slog.w(TAG, "Unrecognized code path "
7947                        + codePath + " - using " + codeRoot);
7948            } catch (IOException e) {
7949                // Can't canonicalize the code path -- shenanigans?
7950                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7951                return Environment.getRootDirectory().getPath();
7952            }
7953        }
7954        return codeRoot.getPath();
7955    }
7956
7957    /**
7958     * Derive and set the location of native libraries for the given package,
7959     * which varies depending on where and how the package was installed.
7960     */
7961    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7962        final ApplicationInfo info = pkg.applicationInfo;
7963        final String codePath = pkg.codePath;
7964        final File codeFile = new File(codePath);
7965        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7966        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7967
7968        info.nativeLibraryRootDir = null;
7969        info.nativeLibraryRootRequiresIsa = false;
7970        info.nativeLibraryDir = null;
7971        info.secondaryNativeLibraryDir = null;
7972
7973        if (isApkFile(codeFile)) {
7974            // Monolithic install
7975            if (bundledApp) {
7976                // If "/system/lib64/apkname" exists, assume that is the per-package
7977                // native library directory to use; otherwise use "/system/lib/apkname".
7978                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7979                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7980                        getPrimaryInstructionSet(info));
7981
7982                // This is a bundled system app so choose the path based on the ABI.
7983                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7984                // is just the default path.
7985                final String apkName = deriveCodePathName(codePath);
7986                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7987                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7988                        apkName).getAbsolutePath();
7989
7990                if (info.secondaryCpuAbi != null) {
7991                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7992                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7993                            secondaryLibDir, apkName).getAbsolutePath();
7994                }
7995            } else if (asecApp) {
7996                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7997                        .getAbsolutePath();
7998            } else {
7999                final String apkName = deriveCodePathName(codePath);
8000                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8001                        .getAbsolutePath();
8002            }
8003
8004            info.nativeLibraryRootRequiresIsa = false;
8005            info.nativeLibraryDir = info.nativeLibraryRootDir;
8006        } else {
8007            // Cluster install
8008            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8009            info.nativeLibraryRootRequiresIsa = true;
8010
8011            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8012                    getPrimaryInstructionSet(info)).getAbsolutePath();
8013
8014            if (info.secondaryCpuAbi != null) {
8015                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8016                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8017            }
8018        }
8019    }
8020
8021    /**
8022     * Calculate the abis and roots for a bundled app. These can uniquely
8023     * be determined from the contents of the system partition, i.e whether
8024     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8025     * of this information, and instead assume that the system was built
8026     * sensibly.
8027     */
8028    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8029                                           PackageSetting pkgSetting) {
8030        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8031
8032        // If "/system/lib64/apkname" exists, assume that is the per-package
8033        // native library directory to use; otherwise use "/system/lib/apkname".
8034        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8035        setBundledAppAbi(pkg, apkRoot, apkName);
8036        // pkgSetting might be null during rescan following uninstall of updates
8037        // to a bundled app, so accommodate that possibility.  The settings in
8038        // that case will be established later from the parsed package.
8039        //
8040        // If the settings aren't null, sync them up with what we've just derived.
8041        // note that apkRoot isn't stored in the package settings.
8042        if (pkgSetting != null) {
8043            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8044            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8045        }
8046    }
8047
8048    /**
8049     * Deduces the ABI of a bundled app and sets the relevant fields on the
8050     * parsed pkg object.
8051     *
8052     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8053     *        under which system libraries are installed.
8054     * @param apkName the name of the installed package.
8055     */
8056    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8057        final File codeFile = new File(pkg.codePath);
8058
8059        final boolean has64BitLibs;
8060        final boolean has32BitLibs;
8061        if (isApkFile(codeFile)) {
8062            // Monolithic install
8063            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8064            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8065        } else {
8066            // Cluster install
8067            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8068            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8069                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8070                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8071                has64BitLibs = (new File(rootDir, isa)).exists();
8072            } else {
8073                has64BitLibs = false;
8074            }
8075            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8076                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8077                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8078                has32BitLibs = (new File(rootDir, isa)).exists();
8079            } else {
8080                has32BitLibs = false;
8081            }
8082        }
8083
8084        if (has64BitLibs && !has32BitLibs) {
8085            // The package has 64 bit libs, but not 32 bit libs. Its primary
8086            // ABI should be 64 bit. We can safely assume here that the bundled
8087            // native libraries correspond to the most preferred ABI in the list.
8088
8089            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8090            pkg.applicationInfo.secondaryCpuAbi = null;
8091        } else if (has32BitLibs && !has64BitLibs) {
8092            // The package has 32 bit libs but not 64 bit libs. Its primary
8093            // ABI should be 32 bit.
8094
8095            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8096            pkg.applicationInfo.secondaryCpuAbi = null;
8097        } else if (has32BitLibs && has64BitLibs) {
8098            // The application has both 64 and 32 bit bundled libraries. We check
8099            // here that the app declares multiArch support, and warn if it doesn't.
8100            //
8101            // We will be lenient here and record both ABIs. The primary will be the
8102            // ABI that's higher on the list, i.e, a device that's configured to prefer
8103            // 64 bit apps will see a 64 bit primary ABI,
8104
8105            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8106                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8107            }
8108
8109            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8110                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8111                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8112            } else {
8113                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8114                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8115            }
8116        } else {
8117            pkg.applicationInfo.primaryCpuAbi = null;
8118            pkg.applicationInfo.secondaryCpuAbi = null;
8119        }
8120    }
8121
8122    private void killApplication(String pkgName, int appId, String reason) {
8123        // Request the ActivityManager to kill the process(only for existing packages)
8124        // so that we do not end up in a confused state while the user is still using the older
8125        // version of the application while the new one gets installed.
8126        IActivityManager am = ActivityManagerNative.getDefault();
8127        if (am != null) {
8128            try {
8129                am.killApplicationWithAppId(pkgName, appId, reason);
8130            } catch (RemoteException e) {
8131            }
8132        }
8133    }
8134
8135    void removePackageLI(PackageSetting ps, boolean chatty) {
8136        if (DEBUG_INSTALL) {
8137            if (chatty)
8138                Log.d(TAG, "Removing package " + ps.name);
8139        }
8140
8141        // writer
8142        synchronized (mPackages) {
8143            mPackages.remove(ps.name);
8144            final PackageParser.Package pkg = ps.pkg;
8145            if (pkg != null) {
8146                cleanPackageDataStructuresLILPw(pkg, chatty);
8147            }
8148        }
8149    }
8150
8151    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8152        if (DEBUG_INSTALL) {
8153            if (chatty)
8154                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8155        }
8156
8157        // writer
8158        synchronized (mPackages) {
8159            mPackages.remove(pkg.applicationInfo.packageName);
8160            cleanPackageDataStructuresLILPw(pkg, chatty);
8161        }
8162    }
8163
8164    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8165        int N = pkg.providers.size();
8166        StringBuilder r = null;
8167        int i;
8168        for (i=0; i<N; i++) {
8169            PackageParser.Provider p = pkg.providers.get(i);
8170            mProviders.removeProvider(p);
8171            if (p.info.authority == null) {
8172
8173                /* There was another ContentProvider with this authority when
8174                 * this app was installed so this authority is null,
8175                 * Ignore it as we don't have to unregister the provider.
8176                 */
8177                continue;
8178            }
8179            String names[] = p.info.authority.split(";");
8180            for (int j = 0; j < names.length; j++) {
8181                if (mProvidersByAuthority.get(names[j]) == p) {
8182                    mProvidersByAuthority.remove(names[j]);
8183                    if (DEBUG_REMOVE) {
8184                        if (chatty)
8185                            Log.d(TAG, "Unregistered content provider: " + names[j]
8186                                    + ", className = " + p.info.name + ", isSyncable = "
8187                                    + p.info.isSyncable);
8188                    }
8189                }
8190            }
8191            if (DEBUG_REMOVE && chatty) {
8192                if (r == null) {
8193                    r = new StringBuilder(256);
8194                } else {
8195                    r.append(' ');
8196                }
8197                r.append(p.info.name);
8198            }
8199        }
8200        if (r != null) {
8201            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8202        }
8203
8204        N = pkg.services.size();
8205        r = null;
8206        for (i=0; i<N; i++) {
8207            PackageParser.Service s = pkg.services.get(i);
8208            mServices.removeService(s);
8209            if (chatty) {
8210                if (r == null) {
8211                    r = new StringBuilder(256);
8212                } else {
8213                    r.append(' ');
8214                }
8215                r.append(s.info.name);
8216            }
8217        }
8218        if (r != null) {
8219            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8220        }
8221
8222        N = pkg.receivers.size();
8223        r = null;
8224        for (i=0; i<N; i++) {
8225            PackageParser.Activity a = pkg.receivers.get(i);
8226            mReceivers.removeActivity(a, "receiver");
8227            if (DEBUG_REMOVE && chatty) {
8228                if (r == null) {
8229                    r = new StringBuilder(256);
8230                } else {
8231                    r.append(' ');
8232                }
8233                r.append(a.info.name);
8234            }
8235        }
8236        if (r != null) {
8237            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8238        }
8239
8240        N = pkg.activities.size();
8241        r = null;
8242        for (i=0; i<N; i++) {
8243            PackageParser.Activity a = pkg.activities.get(i);
8244            mActivities.removeActivity(a, "activity");
8245            if (DEBUG_REMOVE && chatty) {
8246                if (r == null) {
8247                    r = new StringBuilder(256);
8248                } else {
8249                    r.append(' ');
8250                }
8251                r.append(a.info.name);
8252            }
8253        }
8254        if (r != null) {
8255            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8256        }
8257
8258        N = pkg.permissions.size();
8259        r = null;
8260        for (i=0; i<N; i++) {
8261            PackageParser.Permission p = pkg.permissions.get(i);
8262            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8263            if (bp == null) {
8264                bp = mSettings.mPermissionTrees.get(p.info.name);
8265            }
8266            if (bp != null && bp.perm == p) {
8267                bp.perm = null;
8268                if (DEBUG_REMOVE && chatty) {
8269                    if (r == null) {
8270                        r = new StringBuilder(256);
8271                    } else {
8272                        r.append(' ');
8273                    }
8274                    r.append(p.info.name);
8275                }
8276            }
8277            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8278                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8279                if (appOpPerms != null) {
8280                    appOpPerms.remove(pkg.packageName);
8281                }
8282            }
8283        }
8284        if (r != null) {
8285            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8286        }
8287
8288        N = pkg.requestedPermissions.size();
8289        r = null;
8290        for (i=0; i<N; i++) {
8291            String perm = pkg.requestedPermissions.get(i);
8292            BasePermission bp = mSettings.mPermissions.get(perm);
8293            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8294                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8295                if (appOpPerms != null) {
8296                    appOpPerms.remove(pkg.packageName);
8297                    if (appOpPerms.isEmpty()) {
8298                        mAppOpPermissionPackages.remove(perm);
8299                    }
8300                }
8301            }
8302        }
8303        if (r != null) {
8304            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8305        }
8306
8307        N = pkg.instrumentation.size();
8308        r = null;
8309        for (i=0; i<N; i++) {
8310            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8311            mInstrumentation.remove(a.getComponentName());
8312            if (DEBUG_REMOVE && chatty) {
8313                if (r == null) {
8314                    r = new StringBuilder(256);
8315                } else {
8316                    r.append(' ');
8317                }
8318                r.append(a.info.name);
8319            }
8320        }
8321        if (r != null) {
8322            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8323        }
8324
8325        r = null;
8326        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8327            // Only system apps can hold shared libraries.
8328            if (pkg.libraryNames != null) {
8329                for (i=0; i<pkg.libraryNames.size(); i++) {
8330                    String name = pkg.libraryNames.get(i);
8331                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8332                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8333                        mSharedLibraries.remove(name);
8334                        if (DEBUG_REMOVE && chatty) {
8335                            if (r == null) {
8336                                r = new StringBuilder(256);
8337                            } else {
8338                                r.append(' ');
8339                            }
8340                            r.append(name);
8341                        }
8342                    }
8343                }
8344            }
8345        }
8346        if (r != null) {
8347            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8348        }
8349    }
8350
8351    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8352        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8353            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8354                return true;
8355            }
8356        }
8357        return false;
8358    }
8359
8360    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8361    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8362    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8363
8364    private void updatePermissionsLPw(String changingPkg,
8365            PackageParser.Package pkgInfo, int flags) {
8366        // Make sure there are no dangling permission trees.
8367        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8368        while (it.hasNext()) {
8369            final BasePermission bp = it.next();
8370            if (bp.packageSetting == null) {
8371                // We may not yet have parsed the package, so just see if
8372                // we still know about its settings.
8373                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8374            }
8375            if (bp.packageSetting == null) {
8376                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8377                        + " from package " + bp.sourcePackage);
8378                it.remove();
8379            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8380                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8381                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8382                            + " from package " + bp.sourcePackage);
8383                    flags |= UPDATE_PERMISSIONS_ALL;
8384                    it.remove();
8385                }
8386            }
8387        }
8388
8389        // Make sure all dynamic permissions have been assigned to a package,
8390        // and make sure there are no dangling permissions.
8391        it = mSettings.mPermissions.values().iterator();
8392        while (it.hasNext()) {
8393            final BasePermission bp = it.next();
8394            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8395                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8396                        + bp.name + " pkg=" + bp.sourcePackage
8397                        + " info=" + bp.pendingInfo);
8398                if (bp.packageSetting == null && bp.pendingInfo != null) {
8399                    final BasePermission tree = findPermissionTreeLP(bp.name);
8400                    if (tree != null && tree.perm != null) {
8401                        bp.packageSetting = tree.packageSetting;
8402                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8403                                new PermissionInfo(bp.pendingInfo));
8404                        bp.perm.info.packageName = tree.perm.info.packageName;
8405                        bp.perm.info.name = bp.name;
8406                        bp.uid = tree.uid;
8407                    }
8408                }
8409            }
8410            if (bp.packageSetting == null) {
8411                // We may not yet have parsed the package, so just see if
8412                // we still know about its settings.
8413                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8414            }
8415            if (bp.packageSetting == null) {
8416                Slog.w(TAG, "Removing dangling permission: " + bp.name
8417                        + " from package " + bp.sourcePackage);
8418                it.remove();
8419            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8420                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8421                    Slog.i(TAG, "Removing old permission: " + bp.name
8422                            + " from package " + bp.sourcePackage);
8423                    flags |= UPDATE_PERMISSIONS_ALL;
8424                    it.remove();
8425                }
8426            }
8427        }
8428
8429        // Now update the permissions for all packages, in particular
8430        // replace the granted permissions of the system packages.
8431        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8432            for (PackageParser.Package pkg : mPackages.values()) {
8433                if (pkg != pkgInfo) {
8434                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8435                            changingPkg);
8436                }
8437            }
8438        }
8439
8440        if (pkgInfo != null) {
8441            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8442        }
8443    }
8444
8445    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8446            String packageOfInterest) {
8447        // IMPORTANT: There are two types of permissions: install and runtime.
8448        // Install time permissions are granted when the app is installed to
8449        // all device users and users added in the future. Runtime permissions
8450        // are granted at runtime explicitly to specific users. Normal and signature
8451        // protected permissions are install time permissions. Dangerous permissions
8452        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8453        // otherwise they are runtime permissions. This function does not manage
8454        // runtime permissions except for the case an app targeting Lollipop MR1
8455        // being upgraded to target a newer SDK, in which case dangerous permissions
8456        // are transformed from install time to runtime ones.
8457
8458        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8459        if (ps == null) {
8460            return;
8461        }
8462
8463        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8464
8465        PermissionsState permissionsState = ps.getPermissionsState();
8466        PermissionsState origPermissions = permissionsState;
8467
8468        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8469
8470        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8471
8472        boolean changedInstallPermission = false;
8473
8474        if (replace) {
8475            ps.installPermissionsFixed = false;
8476            if (!ps.isSharedUser()) {
8477                origPermissions = new PermissionsState(permissionsState);
8478                permissionsState.reset();
8479            }
8480        }
8481
8482        permissionsState.setGlobalGids(mGlobalGids);
8483
8484        final int N = pkg.requestedPermissions.size();
8485        for (int i=0; i<N; i++) {
8486            final String name = pkg.requestedPermissions.get(i);
8487            final BasePermission bp = mSettings.mPermissions.get(name);
8488
8489            if (DEBUG_INSTALL) {
8490                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8491            }
8492
8493            if (bp == null || bp.packageSetting == null) {
8494                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8495                    Slog.w(TAG, "Unknown permission " + name
8496                            + " in package " + pkg.packageName);
8497                }
8498                continue;
8499            }
8500
8501            final String perm = bp.name;
8502            boolean allowedSig = false;
8503            int grant = GRANT_DENIED;
8504
8505            // Keep track of app op permissions.
8506            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8507                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8508                if (pkgs == null) {
8509                    pkgs = new ArraySet<>();
8510                    mAppOpPermissionPackages.put(bp.name, pkgs);
8511                }
8512                pkgs.add(pkg.packageName);
8513            }
8514
8515            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8516            switch (level) {
8517                case PermissionInfo.PROTECTION_NORMAL: {
8518                    // For all apps normal permissions are install time ones.
8519                    grant = GRANT_INSTALL;
8520                } break;
8521
8522                case PermissionInfo.PROTECTION_DANGEROUS: {
8523                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8524                        // For legacy apps dangerous permissions are install time ones.
8525                        grant = GRANT_INSTALL_LEGACY;
8526                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8527                        // For legacy apps that became modern, install becomes runtime.
8528                        grant = GRANT_UPGRADE;
8529                    } else if (mPromoteSystemApps
8530                            && isSystemApp(ps)
8531                            && mExistingSystemPackages.contains(ps.name)) {
8532                        // For legacy system apps, install becomes runtime.
8533                        // We cannot check hasInstallPermission() for system apps since those
8534                        // permissions were granted implicitly and not persisted pre-M.
8535                        grant = GRANT_UPGRADE;
8536                    } else {
8537                        // For modern apps keep runtime permissions unchanged.
8538                        grant = GRANT_RUNTIME;
8539                    }
8540                } break;
8541
8542                case PermissionInfo.PROTECTION_SIGNATURE: {
8543                    // For all apps signature permissions are install time ones.
8544                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8545                    if (allowedSig) {
8546                        grant = GRANT_INSTALL;
8547                    }
8548                } break;
8549            }
8550
8551            if (DEBUG_INSTALL) {
8552                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8553            }
8554
8555            if (grant != GRANT_DENIED) {
8556                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8557                    // If this is an existing, non-system package, then
8558                    // we can't add any new permissions to it.
8559                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8560                        // Except...  if this is a permission that was added
8561                        // to the platform (note: need to only do this when
8562                        // updating the platform).
8563                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8564                            grant = GRANT_DENIED;
8565                        }
8566                    }
8567                }
8568
8569                switch (grant) {
8570                    case GRANT_INSTALL: {
8571                        // Revoke this as runtime permission to handle the case of
8572                        // a runtime permission being downgraded to an install one.
8573                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8574                            if (origPermissions.getRuntimePermissionState(
8575                                    bp.name, userId) != null) {
8576                                // Revoke the runtime permission and clear the flags.
8577                                origPermissions.revokeRuntimePermission(bp, userId);
8578                                origPermissions.updatePermissionFlags(bp, userId,
8579                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8580                                // If we revoked a permission permission, we have to write.
8581                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8582                                        changedRuntimePermissionUserIds, userId);
8583                            }
8584                        }
8585                        // Grant an install permission.
8586                        if (permissionsState.grantInstallPermission(bp) !=
8587                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8588                            changedInstallPermission = true;
8589                        }
8590                    } break;
8591
8592                    case GRANT_INSTALL_LEGACY: {
8593                        // Grant an install permission.
8594                        if (permissionsState.grantInstallPermission(bp) !=
8595                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8596                            changedInstallPermission = true;
8597                        }
8598                    } break;
8599
8600                    case GRANT_RUNTIME: {
8601                        // Grant previously granted runtime permissions.
8602                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8603                            PermissionState permissionState = origPermissions
8604                                    .getRuntimePermissionState(bp.name, userId);
8605                            final int flags = permissionState != null
8606                                    ? permissionState.getFlags() : 0;
8607                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8608                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8609                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8610                                    // If we cannot put the permission as it was, we have to write.
8611                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8612                                            changedRuntimePermissionUserIds, userId);
8613                                }
8614                            }
8615                            // Propagate the permission flags.
8616                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8617                        }
8618                    } break;
8619
8620                    case GRANT_UPGRADE: {
8621                        // Grant runtime permissions for a previously held install permission.
8622                        PermissionState permissionState = origPermissions
8623                                .getInstallPermissionState(bp.name);
8624                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8625
8626                        if (origPermissions.revokeInstallPermission(bp)
8627                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8628                            // We will be transferring the permission flags, so clear them.
8629                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8630                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8631                            changedInstallPermission = true;
8632                        }
8633
8634                        // If the permission is not to be promoted to runtime we ignore it and
8635                        // also its other flags as they are not applicable to install permissions.
8636                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8637                            for (int userId : currentUserIds) {
8638                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8639                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8640                                    // Transfer the permission flags.
8641                                    permissionsState.updatePermissionFlags(bp, userId,
8642                                            flags, flags);
8643                                    // If we granted the permission, we have to write.
8644                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8645                                            changedRuntimePermissionUserIds, userId);
8646                                }
8647                            }
8648                        }
8649                    } break;
8650
8651                    default: {
8652                        if (packageOfInterest == null
8653                                || packageOfInterest.equals(pkg.packageName)) {
8654                            Slog.w(TAG, "Not granting permission " + perm
8655                                    + " to package " + pkg.packageName
8656                                    + " because it was previously installed without");
8657                        }
8658                    } break;
8659                }
8660            } else {
8661                if (permissionsState.revokeInstallPermission(bp) !=
8662                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8663                    // Also drop the permission flags.
8664                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8665                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8666                    changedInstallPermission = true;
8667                    Slog.i(TAG, "Un-granting permission " + perm
8668                            + " from package " + pkg.packageName
8669                            + " (protectionLevel=" + bp.protectionLevel
8670                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8671                            + ")");
8672                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8673                    // Don't print warning for app op permissions, since it is fine for them
8674                    // not to be granted, there is a UI for the user to decide.
8675                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8676                        Slog.w(TAG, "Not granting permission " + perm
8677                                + " to package " + pkg.packageName
8678                                + " (protectionLevel=" + bp.protectionLevel
8679                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8680                                + ")");
8681                    }
8682                }
8683            }
8684        }
8685
8686        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8687                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8688            // This is the first that we have heard about this package, so the
8689            // permissions we have now selected are fixed until explicitly
8690            // changed.
8691            ps.installPermissionsFixed = true;
8692        }
8693
8694        // Persist the runtime permissions state for users with changes.
8695        for (int userId : changedRuntimePermissionUserIds) {
8696            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8697        }
8698
8699        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8700    }
8701
8702    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8703        boolean allowed = false;
8704        final int NP = PackageParser.NEW_PERMISSIONS.length;
8705        for (int ip=0; ip<NP; ip++) {
8706            final PackageParser.NewPermissionInfo npi
8707                    = PackageParser.NEW_PERMISSIONS[ip];
8708            if (npi.name.equals(perm)
8709                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8710                allowed = true;
8711                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8712                        + pkg.packageName);
8713                break;
8714            }
8715        }
8716        return allowed;
8717    }
8718
8719    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8720            BasePermission bp, PermissionsState origPermissions) {
8721        boolean allowed;
8722        allowed = (compareSignatures(
8723                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8724                        == PackageManager.SIGNATURE_MATCH)
8725                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8726                        == PackageManager.SIGNATURE_MATCH);
8727        if (!allowed && (bp.protectionLevel
8728                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8729            if (isSystemApp(pkg)) {
8730                // For updated system applications, a system permission
8731                // is granted only if it had been defined by the original application.
8732                if (pkg.isUpdatedSystemApp()) {
8733                    final PackageSetting sysPs = mSettings
8734                            .getDisabledSystemPkgLPr(pkg.packageName);
8735                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8736                        // If the original was granted this permission, we take
8737                        // that grant decision as read and propagate it to the
8738                        // update.
8739                        if (sysPs.isPrivileged()) {
8740                            allowed = true;
8741                        }
8742                    } else {
8743                        // The system apk may have been updated with an older
8744                        // version of the one on the data partition, but which
8745                        // granted a new system permission that it didn't have
8746                        // before.  In this case we do want to allow the app to
8747                        // now get the new permission if the ancestral apk is
8748                        // privileged to get it.
8749                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8750                            for (int j=0;
8751                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8752                                if (perm.equals(
8753                                        sysPs.pkg.requestedPermissions.get(j))) {
8754                                    allowed = true;
8755                                    break;
8756                                }
8757                            }
8758                        }
8759                    }
8760                } else {
8761                    allowed = isPrivilegedApp(pkg);
8762                }
8763            }
8764        }
8765        if (!allowed) {
8766            if (!allowed && (bp.protectionLevel
8767                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8768                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8769                // If this was a previously normal/dangerous permission that got moved
8770                // to a system permission as part of the runtime permission redesign, then
8771                // we still want to blindly grant it to old apps.
8772                allowed = true;
8773            }
8774            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8775                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8776                // If this permission is to be granted to the system installer and
8777                // this app is an installer, then it gets the permission.
8778                allowed = true;
8779            }
8780            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8781                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8782                // If this permission is to be granted to the system verifier and
8783                // this app is a verifier, then it gets the permission.
8784                allowed = true;
8785            }
8786            if (!allowed && (bp.protectionLevel
8787                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8788                    && isSystemApp(pkg)) {
8789                // Any pre-installed system app is allowed to get this permission.
8790                allowed = true;
8791            }
8792            if (!allowed && (bp.protectionLevel
8793                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8794                // For development permissions, a development permission
8795                // is granted only if it was already granted.
8796                allowed = origPermissions.hasInstallPermission(perm);
8797            }
8798        }
8799        return allowed;
8800    }
8801
8802    final class ActivityIntentResolver
8803            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8804        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8805                boolean defaultOnly, int userId) {
8806            if (!sUserManager.exists(userId)) return null;
8807            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8808            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8809        }
8810
8811        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8812                int userId) {
8813            if (!sUserManager.exists(userId)) return null;
8814            mFlags = flags;
8815            return super.queryIntent(intent, resolvedType,
8816                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8817        }
8818
8819        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8820                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8821            if (!sUserManager.exists(userId)) return null;
8822            if (packageActivities == null) {
8823                return null;
8824            }
8825            mFlags = flags;
8826            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8827            final int N = packageActivities.size();
8828            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8829                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8830
8831            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8832            for (int i = 0; i < N; ++i) {
8833                intentFilters = packageActivities.get(i).intents;
8834                if (intentFilters != null && intentFilters.size() > 0) {
8835                    PackageParser.ActivityIntentInfo[] array =
8836                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8837                    intentFilters.toArray(array);
8838                    listCut.add(array);
8839                }
8840            }
8841            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8842        }
8843
8844        public final void addActivity(PackageParser.Activity a, String type) {
8845            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8846            mActivities.put(a.getComponentName(), a);
8847            if (DEBUG_SHOW_INFO)
8848                Log.v(
8849                TAG, "  " + type + " " +
8850                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8851            if (DEBUG_SHOW_INFO)
8852                Log.v(TAG, "    Class=" + a.info.name);
8853            final int NI = a.intents.size();
8854            for (int j=0; j<NI; j++) {
8855                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8856                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8857                    intent.setPriority(0);
8858                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8859                            + a.className + " with priority > 0, forcing to 0");
8860                }
8861                if (DEBUG_SHOW_INFO) {
8862                    Log.v(TAG, "    IntentFilter:");
8863                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8864                }
8865                if (!intent.debugCheck()) {
8866                    Log.w(TAG, "==> For Activity " + a.info.name);
8867                }
8868                addFilter(intent);
8869            }
8870        }
8871
8872        public final void removeActivity(PackageParser.Activity a, String type) {
8873            mActivities.remove(a.getComponentName());
8874            if (DEBUG_SHOW_INFO) {
8875                Log.v(TAG, "  " + type + " "
8876                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8877                                : a.info.name) + ":");
8878                Log.v(TAG, "    Class=" + a.info.name);
8879            }
8880            final int NI = a.intents.size();
8881            for (int j=0; j<NI; j++) {
8882                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8883                if (DEBUG_SHOW_INFO) {
8884                    Log.v(TAG, "    IntentFilter:");
8885                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8886                }
8887                removeFilter(intent);
8888            }
8889        }
8890
8891        @Override
8892        protected boolean allowFilterResult(
8893                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8894            ActivityInfo filterAi = filter.activity.info;
8895            for (int i=dest.size()-1; i>=0; i--) {
8896                ActivityInfo destAi = dest.get(i).activityInfo;
8897                if (destAi.name == filterAi.name
8898                        && destAi.packageName == filterAi.packageName) {
8899                    return false;
8900                }
8901            }
8902            return true;
8903        }
8904
8905        @Override
8906        protected ActivityIntentInfo[] newArray(int size) {
8907            return new ActivityIntentInfo[size];
8908        }
8909
8910        @Override
8911        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8912            if (!sUserManager.exists(userId)) return true;
8913            PackageParser.Package p = filter.activity.owner;
8914            if (p != null) {
8915                PackageSetting ps = (PackageSetting)p.mExtras;
8916                if (ps != null) {
8917                    // System apps are never considered stopped for purposes of
8918                    // filtering, because there may be no way for the user to
8919                    // actually re-launch them.
8920                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8921                            && ps.getStopped(userId);
8922                }
8923            }
8924            return false;
8925        }
8926
8927        @Override
8928        protected boolean isPackageForFilter(String packageName,
8929                PackageParser.ActivityIntentInfo info) {
8930            return packageName.equals(info.activity.owner.packageName);
8931        }
8932
8933        @Override
8934        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8935                int match, int userId) {
8936            if (!sUserManager.exists(userId)) return null;
8937            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8938                return null;
8939            }
8940            final PackageParser.Activity activity = info.activity;
8941            if (mSafeMode && (activity.info.applicationInfo.flags
8942                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8943                return null;
8944            }
8945            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8946            if (ps == null) {
8947                return null;
8948            }
8949            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8950                    ps.readUserState(userId), userId);
8951            if (ai == null) {
8952                return null;
8953            }
8954            final ResolveInfo res = new ResolveInfo();
8955            res.activityInfo = ai;
8956            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8957                res.filter = info;
8958            }
8959            if (info != null) {
8960                res.handleAllWebDataURI = info.handleAllWebDataURI();
8961            }
8962            res.priority = info.getPriority();
8963            res.preferredOrder = activity.owner.mPreferredOrder;
8964            //System.out.println("Result: " + res.activityInfo.className +
8965            //                   " = " + res.priority);
8966            res.match = match;
8967            res.isDefault = info.hasDefault;
8968            res.labelRes = info.labelRes;
8969            res.nonLocalizedLabel = info.nonLocalizedLabel;
8970            if (userNeedsBadging(userId)) {
8971                res.noResourceId = true;
8972            } else {
8973                res.icon = info.icon;
8974            }
8975            res.iconResourceId = info.icon;
8976            res.system = res.activityInfo.applicationInfo.isSystemApp();
8977            return res;
8978        }
8979
8980        @Override
8981        protected void sortResults(List<ResolveInfo> results) {
8982            Collections.sort(results, mResolvePrioritySorter);
8983        }
8984
8985        @Override
8986        protected void dumpFilter(PrintWriter out, String prefix,
8987                PackageParser.ActivityIntentInfo filter) {
8988            out.print(prefix); out.print(
8989                    Integer.toHexString(System.identityHashCode(filter.activity)));
8990                    out.print(' ');
8991                    filter.activity.printComponentShortName(out);
8992                    out.print(" filter ");
8993                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8994        }
8995
8996        @Override
8997        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8998            return filter.activity;
8999        }
9000
9001        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9002            PackageParser.Activity activity = (PackageParser.Activity)label;
9003            out.print(prefix); out.print(
9004                    Integer.toHexString(System.identityHashCode(activity)));
9005                    out.print(' ');
9006                    activity.printComponentShortName(out);
9007            if (count > 1) {
9008                out.print(" ("); out.print(count); out.print(" filters)");
9009            }
9010            out.println();
9011        }
9012
9013//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9014//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9015//            final List<ResolveInfo> retList = Lists.newArrayList();
9016//            while (i.hasNext()) {
9017//                final ResolveInfo resolveInfo = i.next();
9018//                if (isEnabledLP(resolveInfo.activityInfo)) {
9019//                    retList.add(resolveInfo);
9020//                }
9021//            }
9022//            return retList;
9023//        }
9024
9025        // Keys are String (activity class name), values are Activity.
9026        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9027                = new ArrayMap<ComponentName, PackageParser.Activity>();
9028        private int mFlags;
9029    }
9030
9031    private final class ServiceIntentResolver
9032            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9033        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9034                boolean defaultOnly, int userId) {
9035            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9036            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9037        }
9038
9039        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9040                int userId) {
9041            if (!sUserManager.exists(userId)) return null;
9042            mFlags = flags;
9043            return super.queryIntent(intent, resolvedType,
9044                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9045        }
9046
9047        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9048                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9049            if (!sUserManager.exists(userId)) return null;
9050            if (packageServices == null) {
9051                return null;
9052            }
9053            mFlags = flags;
9054            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9055            final int N = packageServices.size();
9056            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9057                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9058
9059            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9060            for (int i = 0; i < N; ++i) {
9061                intentFilters = packageServices.get(i).intents;
9062                if (intentFilters != null && intentFilters.size() > 0) {
9063                    PackageParser.ServiceIntentInfo[] array =
9064                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9065                    intentFilters.toArray(array);
9066                    listCut.add(array);
9067                }
9068            }
9069            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9070        }
9071
9072        public final void addService(PackageParser.Service s) {
9073            mServices.put(s.getComponentName(), s);
9074            if (DEBUG_SHOW_INFO) {
9075                Log.v(TAG, "  "
9076                        + (s.info.nonLocalizedLabel != null
9077                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9078                Log.v(TAG, "    Class=" + s.info.name);
9079            }
9080            final int NI = s.intents.size();
9081            int j;
9082            for (j=0; j<NI; j++) {
9083                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9084                if (DEBUG_SHOW_INFO) {
9085                    Log.v(TAG, "    IntentFilter:");
9086                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9087                }
9088                if (!intent.debugCheck()) {
9089                    Log.w(TAG, "==> For Service " + s.info.name);
9090                }
9091                addFilter(intent);
9092            }
9093        }
9094
9095        public final void removeService(PackageParser.Service s) {
9096            mServices.remove(s.getComponentName());
9097            if (DEBUG_SHOW_INFO) {
9098                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9099                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9100                Log.v(TAG, "    Class=" + s.info.name);
9101            }
9102            final int NI = s.intents.size();
9103            int j;
9104            for (j=0; j<NI; j++) {
9105                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9106                if (DEBUG_SHOW_INFO) {
9107                    Log.v(TAG, "    IntentFilter:");
9108                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9109                }
9110                removeFilter(intent);
9111            }
9112        }
9113
9114        @Override
9115        protected boolean allowFilterResult(
9116                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9117            ServiceInfo filterSi = filter.service.info;
9118            for (int i=dest.size()-1; i>=0; i--) {
9119                ServiceInfo destAi = dest.get(i).serviceInfo;
9120                if (destAi.name == filterSi.name
9121                        && destAi.packageName == filterSi.packageName) {
9122                    return false;
9123                }
9124            }
9125            return true;
9126        }
9127
9128        @Override
9129        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9130            return new PackageParser.ServiceIntentInfo[size];
9131        }
9132
9133        @Override
9134        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9135            if (!sUserManager.exists(userId)) return true;
9136            PackageParser.Package p = filter.service.owner;
9137            if (p != null) {
9138                PackageSetting ps = (PackageSetting)p.mExtras;
9139                if (ps != null) {
9140                    // System apps are never considered stopped for purposes of
9141                    // filtering, because there may be no way for the user to
9142                    // actually re-launch them.
9143                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9144                            && ps.getStopped(userId);
9145                }
9146            }
9147            return false;
9148        }
9149
9150        @Override
9151        protected boolean isPackageForFilter(String packageName,
9152                PackageParser.ServiceIntentInfo info) {
9153            return packageName.equals(info.service.owner.packageName);
9154        }
9155
9156        @Override
9157        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9158                int match, int userId) {
9159            if (!sUserManager.exists(userId)) return null;
9160            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9161            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
9162                return null;
9163            }
9164            final PackageParser.Service service = info.service;
9165            if (mSafeMode && (service.info.applicationInfo.flags
9166                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9167                return null;
9168            }
9169            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9170            if (ps == null) {
9171                return null;
9172            }
9173            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9174                    ps.readUserState(userId), userId);
9175            if (si == null) {
9176                return null;
9177            }
9178            final ResolveInfo res = new ResolveInfo();
9179            res.serviceInfo = si;
9180            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9181                res.filter = filter;
9182            }
9183            res.priority = info.getPriority();
9184            res.preferredOrder = service.owner.mPreferredOrder;
9185            res.match = match;
9186            res.isDefault = info.hasDefault;
9187            res.labelRes = info.labelRes;
9188            res.nonLocalizedLabel = info.nonLocalizedLabel;
9189            res.icon = info.icon;
9190            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9191            return res;
9192        }
9193
9194        @Override
9195        protected void sortResults(List<ResolveInfo> results) {
9196            Collections.sort(results, mResolvePrioritySorter);
9197        }
9198
9199        @Override
9200        protected void dumpFilter(PrintWriter out, String prefix,
9201                PackageParser.ServiceIntentInfo filter) {
9202            out.print(prefix); out.print(
9203                    Integer.toHexString(System.identityHashCode(filter.service)));
9204                    out.print(' ');
9205                    filter.service.printComponentShortName(out);
9206                    out.print(" filter ");
9207                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9208        }
9209
9210        @Override
9211        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9212            return filter.service;
9213        }
9214
9215        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9216            PackageParser.Service service = (PackageParser.Service)label;
9217            out.print(prefix); out.print(
9218                    Integer.toHexString(System.identityHashCode(service)));
9219                    out.print(' ');
9220                    service.printComponentShortName(out);
9221            if (count > 1) {
9222                out.print(" ("); out.print(count); out.print(" filters)");
9223            }
9224            out.println();
9225        }
9226
9227//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9228//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9229//            final List<ResolveInfo> retList = Lists.newArrayList();
9230//            while (i.hasNext()) {
9231//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9232//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9233//                    retList.add(resolveInfo);
9234//                }
9235//            }
9236//            return retList;
9237//        }
9238
9239        // Keys are String (activity class name), values are Activity.
9240        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9241                = new ArrayMap<ComponentName, PackageParser.Service>();
9242        private int mFlags;
9243    };
9244
9245    private final class ProviderIntentResolver
9246            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9247        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9248                boolean defaultOnly, int userId) {
9249            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9250            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9251        }
9252
9253        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9254                int userId) {
9255            if (!sUserManager.exists(userId))
9256                return null;
9257            mFlags = flags;
9258            return super.queryIntent(intent, resolvedType,
9259                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9260        }
9261
9262        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9263                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9264            if (!sUserManager.exists(userId))
9265                return null;
9266            if (packageProviders == null) {
9267                return null;
9268            }
9269            mFlags = flags;
9270            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9271            final int N = packageProviders.size();
9272            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9273                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9274
9275            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9276            for (int i = 0; i < N; ++i) {
9277                intentFilters = packageProviders.get(i).intents;
9278                if (intentFilters != null && intentFilters.size() > 0) {
9279                    PackageParser.ProviderIntentInfo[] array =
9280                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9281                    intentFilters.toArray(array);
9282                    listCut.add(array);
9283                }
9284            }
9285            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9286        }
9287
9288        public final void addProvider(PackageParser.Provider p) {
9289            if (mProviders.containsKey(p.getComponentName())) {
9290                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9291                return;
9292            }
9293
9294            mProviders.put(p.getComponentName(), p);
9295            if (DEBUG_SHOW_INFO) {
9296                Log.v(TAG, "  "
9297                        + (p.info.nonLocalizedLabel != null
9298                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9299                Log.v(TAG, "    Class=" + p.info.name);
9300            }
9301            final int NI = p.intents.size();
9302            int j;
9303            for (j = 0; j < NI; j++) {
9304                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9305                if (DEBUG_SHOW_INFO) {
9306                    Log.v(TAG, "    IntentFilter:");
9307                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9308                }
9309                if (!intent.debugCheck()) {
9310                    Log.w(TAG, "==> For Provider " + p.info.name);
9311                }
9312                addFilter(intent);
9313            }
9314        }
9315
9316        public final void removeProvider(PackageParser.Provider p) {
9317            mProviders.remove(p.getComponentName());
9318            if (DEBUG_SHOW_INFO) {
9319                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9320                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9321                Log.v(TAG, "    Class=" + p.info.name);
9322            }
9323            final int NI = p.intents.size();
9324            int j;
9325            for (j = 0; j < NI; j++) {
9326                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9327                if (DEBUG_SHOW_INFO) {
9328                    Log.v(TAG, "    IntentFilter:");
9329                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9330                }
9331                removeFilter(intent);
9332            }
9333        }
9334
9335        @Override
9336        protected boolean allowFilterResult(
9337                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9338            ProviderInfo filterPi = filter.provider.info;
9339            for (int i = dest.size() - 1; i >= 0; i--) {
9340                ProviderInfo destPi = dest.get(i).providerInfo;
9341                if (destPi.name == filterPi.name
9342                        && destPi.packageName == filterPi.packageName) {
9343                    return false;
9344                }
9345            }
9346            return true;
9347        }
9348
9349        @Override
9350        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9351            return new PackageParser.ProviderIntentInfo[size];
9352        }
9353
9354        @Override
9355        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9356            if (!sUserManager.exists(userId))
9357                return true;
9358            PackageParser.Package p = filter.provider.owner;
9359            if (p != null) {
9360                PackageSetting ps = (PackageSetting) p.mExtras;
9361                if (ps != null) {
9362                    // System apps are never considered stopped for purposes of
9363                    // filtering, because there may be no way for the user to
9364                    // actually re-launch them.
9365                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9366                            && ps.getStopped(userId);
9367                }
9368            }
9369            return false;
9370        }
9371
9372        @Override
9373        protected boolean isPackageForFilter(String packageName,
9374                PackageParser.ProviderIntentInfo info) {
9375            return packageName.equals(info.provider.owner.packageName);
9376        }
9377
9378        @Override
9379        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9380                int match, int userId) {
9381            if (!sUserManager.exists(userId))
9382                return null;
9383            final PackageParser.ProviderIntentInfo info = filter;
9384            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9385                return null;
9386            }
9387            final PackageParser.Provider provider = info.provider;
9388            if (mSafeMode && (provider.info.applicationInfo.flags
9389                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9390                return null;
9391            }
9392            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9393            if (ps == null) {
9394                return null;
9395            }
9396            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9397                    ps.readUserState(userId), userId);
9398            if (pi == null) {
9399                return null;
9400            }
9401            final ResolveInfo res = new ResolveInfo();
9402            res.providerInfo = pi;
9403            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9404                res.filter = filter;
9405            }
9406            res.priority = info.getPriority();
9407            res.preferredOrder = provider.owner.mPreferredOrder;
9408            res.match = match;
9409            res.isDefault = info.hasDefault;
9410            res.labelRes = info.labelRes;
9411            res.nonLocalizedLabel = info.nonLocalizedLabel;
9412            res.icon = info.icon;
9413            res.system = res.providerInfo.applicationInfo.isSystemApp();
9414            return res;
9415        }
9416
9417        @Override
9418        protected void sortResults(List<ResolveInfo> results) {
9419            Collections.sort(results, mResolvePrioritySorter);
9420        }
9421
9422        @Override
9423        protected void dumpFilter(PrintWriter out, String prefix,
9424                PackageParser.ProviderIntentInfo filter) {
9425            out.print(prefix);
9426            out.print(
9427                    Integer.toHexString(System.identityHashCode(filter.provider)));
9428            out.print(' ');
9429            filter.provider.printComponentShortName(out);
9430            out.print(" filter ");
9431            out.println(Integer.toHexString(System.identityHashCode(filter)));
9432        }
9433
9434        @Override
9435        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9436            return filter.provider;
9437        }
9438
9439        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9440            PackageParser.Provider provider = (PackageParser.Provider)label;
9441            out.print(prefix); out.print(
9442                    Integer.toHexString(System.identityHashCode(provider)));
9443                    out.print(' ');
9444                    provider.printComponentShortName(out);
9445            if (count > 1) {
9446                out.print(" ("); out.print(count); out.print(" filters)");
9447            }
9448            out.println();
9449        }
9450
9451        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9452                = new ArrayMap<ComponentName, PackageParser.Provider>();
9453        private int mFlags;
9454    };
9455
9456    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9457            new Comparator<ResolveInfo>() {
9458        public int compare(ResolveInfo r1, ResolveInfo r2) {
9459            int v1 = r1.priority;
9460            int v2 = r2.priority;
9461            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9462            if (v1 != v2) {
9463                return (v1 > v2) ? -1 : 1;
9464            }
9465            v1 = r1.preferredOrder;
9466            v2 = r2.preferredOrder;
9467            if (v1 != v2) {
9468                return (v1 > v2) ? -1 : 1;
9469            }
9470            if (r1.isDefault != r2.isDefault) {
9471                return r1.isDefault ? -1 : 1;
9472            }
9473            v1 = r1.match;
9474            v2 = r2.match;
9475            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9476            if (v1 != v2) {
9477                return (v1 > v2) ? -1 : 1;
9478            }
9479            if (r1.system != r2.system) {
9480                return r1.system ? -1 : 1;
9481            }
9482            return 0;
9483        }
9484    };
9485
9486    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9487            new Comparator<ProviderInfo>() {
9488        public int compare(ProviderInfo p1, ProviderInfo p2) {
9489            final int v1 = p1.initOrder;
9490            final int v2 = p2.initOrder;
9491            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9492        }
9493    };
9494
9495    final void sendPackageBroadcast(final String action, final String pkg,
9496            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9497            final int[] userIds) {
9498        mHandler.post(new Runnable() {
9499            @Override
9500            public void run() {
9501                try {
9502                    final IActivityManager am = ActivityManagerNative.getDefault();
9503                    if (am == null) return;
9504                    final int[] resolvedUserIds;
9505                    if (userIds == null) {
9506                        resolvedUserIds = am.getRunningUserIds();
9507                    } else {
9508                        resolvedUserIds = userIds;
9509                    }
9510                    for (int id : resolvedUserIds) {
9511                        final Intent intent = new Intent(action,
9512                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9513                        if (extras != null) {
9514                            intent.putExtras(extras);
9515                        }
9516                        if (targetPkg != null) {
9517                            intent.setPackage(targetPkg);
9518                        }
9519                        // Modify the UID when posting to other users
9520                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9521                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9522                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9523                            intent.putExtra(Intent.EXTRA_UID, uid);
9524                        }
9525                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9526                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9527                        if (DEBUG_BROADCASTS) {
9528                            RuntimeException here = new RuntimeException("here");
9529                            here.fillInStackTrace();
9530                            Slog.d(TAG, "Sending to user " + id + ": "
9531                                    + intent.toShortString(false, true, false, false)
9532                                    + " " + intent.getExtras(), here);
9533                        }
9534                        am.broadcastIntent(null, intent, null, finishedReceiver,
9535                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9536                                null, finishedReceiver != null, false, id);
9537                    }
9538                } catch (RemoteException ex) {
9539                }
9540            }
9541        });
9542    }
9543
9544    /**
9545     * Check if the external storage media is available. This is true if there
9546     * is a mounted external storage medium or if the external storage is
9547     * emulated.
9548     */
9549    private boolean isExternalMediaAvailable() {
9550        return mMediaMounted || Environment.isExternalStorageEmulated();
9551    }
9552
9553    @Override
9554    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9555        // writer
9556        synchronized (mPackages) {
9557            if (!isExternalMediaAvailable()) {
9558                // If the external storage is no longer mounted at this point,
9559                // the caller may not have been able to delete all of this
9560                // packages files and can not delete any more.  Bail.
9561                return null;
9562            }
9563            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9564            if (lastPackage != null) {
9565                pkgs.remove(lastPackage);
9566            }
9567            if (pkgs.size() > 0) {
9568                return pkgs.get(0);
9569            }
9570        }
9571        return null;
9572    }
9573
9574    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9575        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9576                userId, andCode ? 1 : 0, packageName);
9577        if (mSystemReady) {
9578            msg.sendToTarget();
9579        } else {
9580            if (mPostSystemReadyMessages == null) {
9581                mPostSystemReadyMessages = new ArrayList<>();
9582            }
9583            mPostSystemReadyMessages.add(msg);
9584        }
9585    }
9586
9587    void startCleaningPackages() {
9588        // reader
9589        synchronized (mPackages) {
9590            if (!isExternalMediaAvailable()) {
9591                return;
9592            }
9593            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9594                return;
9595            }
9596        }
9597        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9598        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9599        IActivityManager am = ActivityManagerNative.getDefault();
9600        if (am != null) {
9601            try {
9602                am.startService(null, intent, null, mContext.getOpPackageName(),
9603                        UserHandle.USER_OWNER);
9604            } catch (RemoteException e) {
9605            }
9606        }
9607    }
9608
9609    @Override
9610    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9611            int installFlags, String installerPackageName, VerificationParams verificationParams,
9612            String packageAbiOverride) {
9613        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9614                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9615    }
9616
9617    @Override
9618    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9619            int installFlags, String installerPackageName, VerificationParams verificationParams,
9620            String packageAbiOverride, int userId) {
9621        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9622
9623        final int callingUid = Binder.getCallingUid();
9624        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9625
9626        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9627            try {
9628                if (observer != null) {
9629                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9630                }
9631            } catch (RemoteException re) {
9632            }
9633            return;
9634        }
9635
9636        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9637            installFlags |= PackageManager.INSTALL_FROM_ADB;
9638
9639        } else {
9640            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9641            // about installerPackageName.
9642
9643            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9644            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9645        }
9646
9647        UserHandle user;
9648        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9649            user = UserHandle.ALL;
9650        } else {
9651            user = new UserHandle(userId);
9652        }
9653
9654        // Only system components can circumvent runtime permissions when installing.
9655        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9656                && mContext.checkCallingOrSelfPermission(Manifest.permission
9657                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9658            throw new SecurityException("You need the "
9659                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9660                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9661        }
9662
9663        verificationParams.setInstallerUid(callingUid);
9664
9665        final File originFile = new File(originPath);
9666        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9667
9668        final Message msg = mHandler.obtainMessage(INIT_COPY);
9669        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9670                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9671        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
9672        msg.obj = params;
9673
9674        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
9675                System.identityHashCode(msg.obj));
9676        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9677                System.identityHashCode(msg.obj));
9678
9679        mHandler.sendMessage(msg);
9680    }
9681
9682    void installStage(String packageName, File stagedDir, String stagedCid,
9683            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
9684            String installerPackageName, int installerUid, UserHandle user) {
9685        final VerificationParams verifParams = new VerificationParams(
9686                null, sessionParams.originatingUri, sessionParams.referrerUri, installerUid, null);
9687        verifParams.setInstallerUid(installerUid);
9688
9689        final OriginInfo origin;
9690        if (stagedDir != null) {
9691            origin = OriginInfo.fromStagedFile(stagedDir);
9692        } else {
9693            origin = OriginInfo.fromStagedContainer(stagedCid);
9694        }
9695
9696        final Message msg = mHandler.obtainMessage(INIT_COPY);
9697        final InstallParams params = new InstallParams(origin, null, observer,
9698                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
9699                verifParams, user, sessionParams.abiOverride,
9700                sessionParams.grantedRuntimePermissions);
9701        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
9702        msg.obj = params;
9703
9704        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
9705                System.identityHashCode(msg.obj));
9706        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9707                System.identityHashCode(msg.obj));
9708
9709        mHandler.sendMessage(msg);
9710    }
9711
9712    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9713        Bundle extras = new Bundle(1);
9714        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9715
9716        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9717                packageName, extras, null, null, new int[] {userId});
9718        try {
9719            IActivityManager am = ActivityManagerNative.getDefault();
9720            final boolean isSystem =
9721                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9722            if (isSystem && am.isUserRunning(userId, false)) {
9723                // The just-installed/enabled app is bundled on the system, so presumed
9724                // to be able to run automatically without needing an explicit launch.
9725                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9726                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9727                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9728                        .setPackage(packageName);
9729                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9730                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9731            }
9732        } catch (RemoteException e) {
9733            // shouldn't happen
9734            Slog.w(TAG, "Unable to bootstrap installed package", e);
9735        }
9736    }
9737
9738    @Override
9739    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9740            int userId) {
9741        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9742        PackageSetting pkgSetting;
9743        final int uid = Binder.getCallingUid();
9744        enforceCrossUserPermission(uid, userId, true, true,
9745                "setApplicationHiddenSetting for user " + userId);
9746
9747        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9748            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9749            return false;
9750        }
9751
9752        long callingId = Binder.clearCallingIdentity();
9753        try {
9754            boolean sendAdded = false;
9755            boolean sendRemoved = false;
9756            // writer
9757            synchronized (mPackages) {
9758                pkgSetting = mSettings.mPackages.get(packageName);
9759                if (pkgSetting == null) {
9760                    return false;
9761                }
9762                if (pkgSetting.getHidden(userId) != hidden) {
9763                    pkgSetting.setHidden(hidden, userId);
9764                    mSettings.writePackageRestrictionsLPr(userId);
9765                    if (hidden) {
9766                        sendRemoved = true;
9767                    } else {
9768                        sendAdded = true;
9769                    }
9770                }
9771            }
9772            if (sendAdded) {
9773                sendPackageAddedForUser(packageName, pkgSetting, userId);
9774                return true;
9775            }
9776            if (sendRemoved) {
9777                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9778                        "hiding pkg");
9779                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9780                return true;
9781            }
9782        } finally {
9783            Binder.restoreCallingIdentity(callingId);
9784        }
9785        return false;
9786    }
9787
9788    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9789            int userId) {
9790        final PackageRemovedInfo info = new PackageRemovedInfo();
9791        info.removedPackage = packageName;
9792        info.removedUsers = new int[] {userId};
9793        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9794        info.sendBroadcast(false, false, false);
9795    }
9796
9797    /**
9798     * Returns true if application is not found or there was an error. Otherwise it returns
9799     * the hidden state of the package for the given user.
9800     */
9801    @Override
9802    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9803        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9804        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9805                false, "getApplicationHidden for user " + userId);
9806        PackageSetting pkgSetting;
9807        long callingId = Binder.clearCallingIdentity();
9808        try {
9809            // writer
9810            synchronized (mPackages) {
9811                pkgSetting = mSettings.mPackages.get(packageName);
9812                if (pkgSetting == null) {
9813                    return true;
9814                }
9815                return pkgSetting.getHidden(userId);
9816            }
9817        } finally {
9818            Binder.restoreCallingIdentity(callingId);
9819        }
9820    }
9821
9822    /**
9823     * @hide
9824     */
9825    @Override
9826    public int installExistingPackageAsUser(String packageName, int userId) {
9827        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9828                null);
9829        PackageSetting pkgSetting;
9830        final int uid = Binder.getCallingUid();
9831        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9832                + userId);
9833        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9834            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9835        }
9836
9837        long callingId = Binder.clearCallingIdentity();
9838        try {
9839            boolean sendAdded = false;
9840
9841            // writer
9842            synchronized (mPackages) {
9843                pkgSetting = mSettings.mPackages.get(packageName);
9844                if (pkgSetting == null) {
9845                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9846                }
9847                if (!pkgSetting.getInstalled(userId)) {
9848                    pkgSetting.setInstalled(true, userId);
9849                    pkgSetting.setHidden(false, userId);
9850                    mSettings.writePackageRestrictionsLPr(userId);
9851                    sendAdded = true;
9852                }
9853            }
9854
9855            if (sendAdded) {
9856                sendPackageAddedForUser(packageName, pkgSetting, userId);
9857            }
9858        } finally {
9859            Binder.restoreCallingIdentity(callingId);
9860        }
9861
9862        return PackageManager.INSTALL_SUCCEEDED;
9863    }
9864
9865    boolean isUserRestricted(int userId, String restrictionKey) {
9866        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9867        if (restrictions.getBoolean(restrictionKey, false)) {
9868            Log.w(TAG, "User is restricted: " + restrictionKey);
9869            return true;
9870        }
9871        return false;
9872    }
9873
9874    @Override
9875    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9876        mContext.enforceCallingOrSelfPermission(
9877                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9878                "Only package verification agents can verify applications");
9879
9880        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9881        final PackageVerificationResponse response = new PackageVerificationResponse(
9882                verificationCode, Binder.getCallingUid());
9883        msg.arg1 = id;
9884        msg.obj = response;
9885        mHandler.sendMessage(msg);
9886    }
9887
9888    @Override
9889    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9890            long millisecondsToDelay) {
9891        mContext.enforceCallingOrSelfPermission(
9892                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9893                "Only package verification agents can extend verification timeouts");
9894
9895        final PackageVerificationState state = mPendingVerification.get(id);
9896        final PackageVerificationResponse response = new PackageVerificationResponse(
9897                verificationCodeAtTimeout, Binder.getCallingUid());
9898
9899        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9900            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9901        }
9902        if (millisecondsToDelay < 0) {
9903            millisecondsToDelay = 0;
9904        }
9905        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9906                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9907            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9908        }
9909
9910        if ((state != null) && !state.timeoutExtended()) {
9911            state.extendTimeout();
9912
9913            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9914            msg.arg1 = id;
9915            msg.obj = response;
9916            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9917        }
9918    }
9919
9920    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9921            int verificationCode, UserHandle user) {
9922        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9923        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9924        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9925        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9926        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9927
9928        mContext.sendBroadcastAsUser(intent, user,
9929                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9930    }
9931
9932    private ComponentName matchComponentForVerifier(String packageName,
9933            List<ResolveInfo> receivers) {
9934        ActivityInfo targetReceiver = null;
9935
9936        final int NR = receivers.size();
9937        for (int i = 0; i < NR; i++) {
9938            final ResolveInfo info = receivers.get(i);
9939            if (info.activityInfo == null) {
9940                continue;
9941            }
9942
9943            if (packageName.equals(info.activityInfo.packageName)) {
9944                targetReceiver = info.activityInfo;
9945                break;
9946            }
9947        }
9948
9949        if (targetReceiver == null) {
9950            return null;
9951        }
9952
9953        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9954    }
9955
9956    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9957            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9958        if (pkgInfo.verifiers.length == 0) {
9959            return null;
9960        }
9961
9962        final int N = pkgInfo.verifiers.length;
9963        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9964        for (int i = 0; i < N; i++) {
9965            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9966
9967            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9968                    receivers);
9969            if (comp == null) {
9970                continue;
9971            }
9972
9973            final int verifierUid = getUidForVerifier(verifierInfo);
9974            if (verifierUid == -1) {
9975                continue;
9976            }
9977
9978            if (DEBUG_VERIFY) {
9979                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9980                        + " with the correct signature");
9981            }
9982            sufficientVerifiers.add(comp);
9983            verificationState.addSufficientVerifier(verifierUid);
9984        }
9985
9986        return sufficientVerifiers;
9987    }
9988
9989    private int getUidForVerifier(VerifierInfo verifierInfo) {
9990        synchronized (mPackages) {
9991            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9992            if (pkg == null) {
9993                return -1;
9994            } else if (pkg.mSignatures.length != 1) {
9995                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9996                        + " has more than one signature; ignoring");
9997                return -1;
9998            }
9999
10000            /*
10001             * If the public key of the package's signature does not match
10002             * our expected public key, then this is a different package and
10003             * we should skip.
10004             */
10005
10006            final byte[] expectedPublicKey;
10007            try {
10008                final Signature verifierSig = pkg.mSignatures[0];
10009                final PublicKey publicKey = verifierSig.getPublicKey();
10010                expectedPublicKey = publicKey.getEncoded();
10011            } catch (CertificateException e) {
10012                return -1;
10013            }
10014
10015            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10016
10017            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10018                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10019                        + " does not have the expected public key; ignoring");
10020                return -1;
10021            }
10022
10023            return pkg.applicationInfo.uid;
10024        }
10025    }
10026
10027    @Override
10028    public void finishPackageInstall(int token) {
10029        enforceSystemOrRoot("Only the system is allowed to finish installs");
10030
10031        if (DEBUG_INSTALL) {
10032            Slog.v(TAG, "BM finishing package install for " + token);
10033        }
10034        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10035
10036        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10037        mHandler.sendMessage(msg);
10038    }
10039
10040    /**
10041     * Get the verification agent timeout.
10042     *
10043     * @return verification timeout in milliseconds
10044     */
10045    private long getVerificationTimeout() {
10046        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10047                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10048                DEFAULT_VERIFICATION_TIMEOUT);
10049    }
10050
10051    /**
10052     * Get the default verification agent response code.
10053     *
10054     * @return default verification response code
10055     */
10056    private int getDefaultVerificationResponse() {
10057        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10058                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10059                DEFAULT_VERIFICATION_RESPONSE);
10060    }
10061
10062    /**
10063     * Check whether or not package verification has been enabled.
10064     *
10065     * @return true if verification should be performed
10066     */
10067    private boolean isVerificationEnabled(int userId, int installFlags) {
10068        if (!DEFAULT_VERIFY_ENABLE) {
10069            return false;
10070        }
10071
10072        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10073
10074        // Check if installing from ADB
10075        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10076            // Do not run verification in a test harness environment
10077            if (ActivityManager.isRunningInTestHarness()) {
10078                return false;
10079            }
10080            if (ensureVerifyAppsEnabled) {
10081                return true;
10082            }
10083            // Check if the developer does not want package verification for ADB installs
10084            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10085                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10086                return false;
10087            }
10088        }
10089
10090        if (ensureVerifyAppsEnabled) {
10091            return true;
10092        }
10093
10094        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10095                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10096    }
10097
10098    @Override
10099    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10100            throws RemoteException {
10101        mContext.enforceCallingOrSelfPermission(
10102                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10103                "Only intentfilter verification agents can verify applications");
10104
10105        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10106        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10107                Binder.getCallingUid(), verificationCode, failedDomains);
10108        msg.arg1 = id;
10109        msg.obj = response;
10110        mHandler.sendMessage(msg);
10111    }
10112
10113    @Override
10114    public int getIntentVerificationStatus(String packageName, int userId) {
10115        synchronized (mPackages) {
10116            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10117        }
10118    }
10119
10120    @Override
10121    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10122        mContext.enforceCallingOrSelfPermission(
10123                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10124
10125        boolean result = false;
10126        synchronized (mPackages) {
10127            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10128        }
10129        if (result) {
10130            scheduleWritePackageRestrictionsLocked(userId);
10131        }
10132        return result;
10133    }
10134
10135    @Override
10136    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10137        synchronized (mPackages) {
10138            return mSettings.getIntentFilterVerificationsLPr(packageName);
10139        }
10140    }
10141
10142    @Override
10143    public List<IntentFilter> getAllIntentFilters(String packageName) {
10144        if (TextUtils.isEmpty(packageName)) {
10145            return Collections.<IntentFilter>emptyList();
10146        }
10147        synchronized (mPackages) {
10148            PackageParser.Package pkg = mPackages.get(packageName);
10149            if (pkg == null || pkg.activities == null) {
10150                return Collections.<IntentFilter>emptyList();
10151            }
10152            final int count = pkg.activities.size();
10153            ArrayList<IntentFilter> result = new ArrayList<>();
10154            for (int n=0; n<count; n++) {
10155                PackageParser.Activity activity = pkg.activities.get(n);
10156                if (activity.intents != null || activity.intents.size() > 0) {
10157                    result.addAll(activity.intents);
10158                }
10159            }
10160            return result;
10161        }
10162    }
10163
10164    @Override
10165    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10166        mContext.enforceCallingOrSelfPermission(
10167                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10168
10169        synchronized (mPackages) {
10170            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10171            if (packageName != null) {
10172                result |= updateIntentVerificationStatus(packageName,
10173                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10174                        userId);
10175                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10176                        packageName, userId);
10177            }
10178            return result;
10179        }
10180    }
10181
10182    @Override
10183    public String getDefaultBrowserPackageName(int userId) {
10184        synchronized (mPackages) {
10185            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10186        }
10187    }
10188
10189    /**
10190     * Get the "allow unknown sources" setting.
10191     *
10192     * @return the current "allow unknown sources" setting
10193     */
10194    private int getUnknownSourcesSettings() {
10195        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10196                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10197                -1);
10198    }
10199
10200    @Override
10201    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10202        final int uid = Binder.getCallingUid();
10203        // writer
10204        synchronized (mPackages) {
10205            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10206            if (targetPackageSetting == null) {
10207                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10208            }
10209
10210            PackageSetting installerPackageSetting;
10211            if (installerPackageName != null) {
10212                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10213                if (installerPackageSetting == null) {
10214                    throw new IllegalArgumentException("Unknown installer package: "
10215                            + installerPackageName);
10216                }
10217            } else {
10218                installerPackageSetting = null;
10219            }
10220
10221            Signature[] callerSignature;
10222            Object obj = mSettings.getUserIdLPr(uid);
10223            if (obj != null) {
10224                if (obj instanceof SharedUserSetting) {
10225                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10226                } else if (obj instanceof PackageSetting) {
10227                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10228                } else {
10229                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10230                }
10231            } else {
10232                throw new SecurityException("Unknown calling uid " + uid);
10233            }
10234
10235            // Verify: can't set installerPackageName to a package that is
10236            // not signed with the same cert as the caller.
10237            if (installerPackageSetting != null) {
10238                if (compareSignatures(callerSignature,
10239                        installerPackageSetting.signatures.mSignatures)
10240                        != PackageManager.SIGNATURE_MATCH) {
10241                    throw new SecurityException(
10242                            "Caller does not have same cert as new installer package "
10243                            + installerPackageName);
10244                }
10245            }
10246
10247            // Verify: if target already has an installer package, it must
10248            // be signed with the same cert as the caller.
10249            if (targetPackageSetting.installerPackageName != null) {
10250                PackageSetting setting = mSettings.mPackages.get(
10251                        targetPackageSetting.installerPackageName);
10252                // If the currently set package isn't valid, then it's always
10253                // okay to change it.
10254                if (setting != null) {
10255                    if (compareSignatures(callerSignature,
10256                            setting.signatures.mSignatures)
10257                            != PackageManager.SIGNATURE_MATCH) {
10258                        throw new SecurityException(
10259                                "Caller does not have same cert as old installer package "
10260                                + targetPackageSetting.installerPackageName);
10261                    }
10262                }
10263            }
10264
10265            // Okay!
10266            targetPackageSetting.installerPackageName = installerPackageName;
10267            scheduleWriteSettingsLocked();
10268        }
10269    }
10270
10271    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10272        // Queue up an async operation since the package installation may take a little while.
10273        mHandler.post(new Runnable() {
10274            public void run() {
10275                mHandler.removeCallbacks(this);
10276                 // Result object to be returned
10277                PackageInstalledInfo res = new PackageInstalledInfo();
10278                res.returnCode = currentStatus;
10279                res.uid = -1;
10280                res.pkg = null;
10281                res.removedInfo = new PackageRemovedInfo();
10282                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10283                    args.doPreInstall(res.returnCode);
10284                    synchronized (mInstallLock) {
10285                        installPackageTracedLI(args, res);
10286                    }
10287                    args.doPostInstall(res.returnCode, res.uid);
10288                }
10289
10290                // A restore should be performed at this point if (a) the install
10291                // succeeded, (b) the operation is not an update, and (c) the new
10292                // package has not opted out of backup participation.
10293                final boolean update = res.removedInfo.removedPackage != null;
10294                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10295                boolean doRestore = !update
10296                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10297
10298                // Set up the post-install work request bookkeeping.  This will be used
10299                // and cleaned up by the post-install event handling regardless of whether
10300                // there's a restore pass performed.  Token values are >= 1.
10301                int token;
10302                if (mNextInstallToken < 0) mNextInstallToken = 1;
10303                token = mNextInstallToken++;
10304
10305                PostInstallData data = new PostInstallData(args, res);
10306                mRunningInstalls.put(token, data);
10307                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10308
10309                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10310                    // Pass responsibility to the Backup Manager.  It will perform a
10311                    // restore if appropriate, then pass responsibility back to the
10312                    // Package Manager to run the post-install observer callbacks
10313                    // and broadcasts.
10314                    IBackupManager bm = IBackupManager.Stub.asInterface(
10315                            ServiceManager.getService(Context.BACKUP_SERVICE));
10316                    if (bm != null) {
10317                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10318                                + " to BM for possible restore");
10319                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10320                        try {
10321                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10322                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10323                            } else {
10324                                doRestore = false;
10325                            }
10326                        } catch (RemoteException e) {
10327                            // can't happen; the backup manager is local
10328                        } catch (Exception e) {
10329                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10330                            doRestore = false;
10331                        }
10332                    } else {
10333                        Slog.e(TAG, "Backup Manager not found!");
10334                        doRestore = false;
10335                    }
10336                }
10337
10338                if (!doRestore) {
10339                    // No restore possible, or the Backup Manager was mysteriously not
10340                    // available -- just fire the post-install work request directly.
10341                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10342
10343                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10344
10345                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10346                    mHandler.sendMessage(msg);
10347                }
10348            }
10349        });
10350    }
10351
10352    private abstract class HandlerParams {
10353        private static final int MAX_RETRIES = 4;
10354
10355        /**
10356         * Number of times startCopy() has been attempted and had a non-fatal
10357         * error.
10358         */
10359        private int mRetries = 0;
10360
10361        /** User handle for the user requesting the information or installation. */
10362        private final UserHandle mUser;
10363        String traceMethod;
10364        int traceCookie;
10365
10366        HandlerParams(UserHandle user) {
10367            mUser = user;
10368        }
10369
10370        UserHandle getUser() {
10371            return mUser;
10372        }
10373
10374        HandlerParams setTraceMethod(String traceMethod) {
10375            this.traceMethod = traceMethod;
10376            return this;
10377        }
10378
10379        HandlerParams setTraceCookie(int traceCookie) {
10380            this.traceCookie = traceCookie;
10381            return this;
10382        }
10383
10384        final boolean startCopy() {
10385            boolean res;
10386            try {
10387                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10388
10389                if (++mRetries > MAX_RETRIES) {
10390                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10391                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10392                    handleServiceError();
10393                    return false;
10394                } else {
10395                    handleStartCopy();
10396                    res = true;
10397                }
10398            } catch (RemoteException e) {
10399                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10400                mHandler.sendEmptyMessage(MCS_RECONNECT);
10401                res = false;
10402            }
10403            handleReturnCode();
10404            return res;
10405        }
10406
10407        final void serviceError() {
10408            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10409            handleServiceError();
10410            handleReturnCode();
10411        }
10412
10413        abstract void handleStartCopy() throws RemoteException;
10414        abstract void handleServiceError();
10415        abstract void handleReturnCode();
10416    }
10417
10418    class MeasureParams extends HandlerParams {
10419        private final PackageStats mStats;
10420        private boolean mSuccess;
10421
10422        private final IPackageStatsObserver mObserver;
10423
10424        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10425            super(new UserHandle(stats.userHandle));
10426            mObserver = observer;
10427            mStats = stats;
10428        }
10429
10430        @Override
10431        public String toString() {
10432            return "MeasureParams{"
10433                + Integer.toHexString(System.identityHashCode(this))
10434                + " " + mStats.packageName + "}";
10435        }
10436
10437        @Override
10438        void handleStartCopy() throws RemoteException {
10439            synchronized (mInstallLock) {
10440                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10441            }
10442
10443            if (mSuccess) {
10444                final boolean mounted;
10445                if (Environment.isExternalStorageEmulated()) {
10446                    mounted = true;
10447                } else {
10448                    final String status = Environment.getExternalStorageState();
10449                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10450                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10451                }
10452
10453                if (mounted) {
10454                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10455
10456                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10457                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10458
10459                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10460                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10461
10462                    // Always subtract cache size, since it's a subdirectory
10463                    mStats.externalDataSize -= mStats.externalCacheSize;
10464
10465                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10466                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10467
10468                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10469                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10470                }
10471            }
10472        }
10473
10474        @Override
10475        void handleReturnCode() {
10476            if (mObserver != null) {
10477                try {
10478                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10479                } catch (RemoteException e) {
10480                    Slog.i(TAG, "Observer no longer exists.");
10481                }
10482            }
10483        }
10484
10485        @Override
10486        void handleServiceError() {
10487            Slog.e(TAG, "Could not measure application " + mStats.packageName
10488                            + " external storage");
10489        }
10490    }
10491
10492    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10493            throws RemoteException {
10494        long result = 0;
10495        for (File path : paths) {
10496            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10497        }
10498        return result;
10499    }
10500
10501    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10502        for (File path : paths) {
10503            try {
10504                mcs.clearDirectory(path.getAbsolutePath());
10505            } catch (RemoteException e) {
10506            }
10507        }
10508    }
10509
10510    static class OriginInfo {
10511        /**
10512         * Location where install is coming from, before it has been
10513         * copied/renamed into place. This could be a single monolithic APK
10514         * file, or a cluster directory. This location may be untrusted.
10515         */
10516        final File file;
10517        final String cid;
10518
10519        /**
10520         * Flag indicating that {@link #file} or {@link #cid} has already been
10521         * staged, meaning downstream users don't need to defensively copy the
10522         * contents.
10523         */
10524        final boolean staged;
10525
10526        /**
10527         * Flag indicating that {@link #file} or {@link #cid} is an already
10528         * installed app that is being moved.
10529         */
10530        final boolean existing;
10531
10532        final String resolvedPath;
10533        final File resolvedFile;
10534
10535        static OriginInfo fromNothing() {
10536            return new OriginInfo(null, null, false, false);
10537        }
10538
10539        static OriginInfo fromUntrustedFile(File file) {
10540            return new OriginInfo(file, null, false, false);
10541        }
10542
10543        static OriginInfo fromExistingFile(File file) {
10544            return new OriginInfo(file, null, false, true);
10545        }
10546
10547        static OriginInfo fromStagedFile(File file) {
10548            return new OriginInfo(file, null, true, false);
10549        }
10550
10551        static OriginInfo fromStagedContainer(String cid) {
10552            return new OriginInfo(null, cid, true, false);
10553        }
10554
10555        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10556            this.file = file;
10557            this.cid = cid;
10558            this.staged = staged;
10559            this.existing = existing;
10560
10561            if (cid != null) {
10562                resolvedPath = PackageHelper.getSdDir(cid);
10563                resolvedFile = new File(resolvedPath);
10564            } else if (file != null) {
10565                resolvedPath = file.getAbsolutePath();
10566                resolvedFile = file;
10567            } else {
10568                resolvedPath = null;
10569                resolvedFile = null;
10570            }
10571        }
10572    }
10573
10574    class MoveInfo {
10575        final int moveId;
10576        final String fromUuid;
10577        final String toUuid;
10578        final String packageName;
10579        final String dataAppName;
10580        final int appId;
10581        final String seinfo;
10582
10583        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10584                String dataAppName, int appId, String seinfo) {
10585            this.moveId = moveId;
10586            this.fromUuid = fromUuid;
10587            this.toUuid = toUuid;
10588            this.packageName = packageName;
10589            this.dataAppName = dataAppName;
10590            this.appId = appId;
10591            this.seinfo = seinfo;
10592        }
10593    }
10594
10595    class InstallParams extends HandlerParams {
10596        final OriginInfo origin;
10597        final MoveInfo move;
10598        final IPackageInstallObserver2 observer;
10599        int installFlags;
10600        final String installerPackageName;
10601        final String volumeUuid;
10602        final VerificationParams verificationParams;
10603        private InstallArgs mArgs;
10604        private int mRet;
10605        final String packageAbiOverride;
10606        final String[] grantedRuntimePermissions;
10607
10608        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10609                int installFlags, String installerPackageName, String volumeUuid,
10610                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10611                String[] grantedPermissions) {
10612            super(user);
10613            this.origin = origin;
10614            this.move = move;
10615            this.observer = observer;
10616            this.installFlags = installFlags;
10617            this.installerPackageName = installerPackageName;
10618            this.volumeUuid = volumeUuid;
10619            this.verificationParams = verificationParams;
10620            this.packageAbiOverride = packageAbiOverride;
10621            this.grantedRuntimePermissions = grantedPermissions;
10622        }
10623
10624        @Override
10625        public String toString() {
10626            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10627                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10628        }
10629
10630        public ManifestDigest getManifestDigest() {
10631            if (verificationParams == null) {
10632                return null;
10633            }
10634            return verificationParams.getManifestDigest();
10635        }
10636
10637        private int installLocationPolicy(PackageInfoLite pkgLite) {
10638            String packageName = pkgLite.packageName;
10639            int installLocation = pkgLite.installLocation;
10640            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10641            // reader
10642            synchronized (mPackages) {
10643                PackageParser.Package pkg = mPackages.get(packageName);
10644                if (pkg != null) {
10645                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10646                        // Check for downgrading.
10647                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10648                            try {
10649                                checkDowngrade(pkg, pkgLite);
10650                            } catch (PackageManagerException e) {
10651                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10652                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10653                            }
10654                        }
10655                        // Check for updated system application.
10656                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10657                            if (onSd) {
10658                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10659                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10660                            }
10661                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10662                        } else {
10663                            if (onSd) {
10664                                // Install flag overrides everything.
10665                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10666                            }
10667                            // If current upgrade specifies particular preference
10668                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10669                                // Application explicitly specified internal.
10670                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10671                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10672                                // App explictly prefers external. Let policy decide
10673                            } else {
10674                                // Prefer previous location
10675                                if (isExternal(pkg)) {
10676                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10677                                }
10678                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10679                            }
10680                        }
10681                    } else {
10682                        // Invalid install. Return error code
10683                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10684                    }
10685                }
10686            }
10687            // All the special cases have been taken care of.
10688            // Return result based on recommended install location.
10689            if (onSd) {
10690                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10691            }
10692            return pkgLite.recommendedInstallLocation;
10693        }
10694
10695        /*
10696         * Invoke remote method to get package information and install
10697         * location values. Override install location based on default
10698         * policy if needed and then create install arguments based
10699         * on the install location.
10700         */
10701        public void handleStartCopy() throws RemoteException {
10702            int ret = PackageManager.INSTALL_SUCCEEDED;
10703
10704            // If we're already staged, we've firmly committed to an install location
10705            if (origin.staged) {
10706                if (origin.file != null) {
10707                    installFlags |= PackageManager.INSTALL_INTERNAL;
10708                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10709                } else if (origin.cid != null) {
10710                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10711                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10712                } else {
10713                    throw new IllegalStateException("Invalid stage location");
10714                }
10715            }
10716
10717            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10718            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10719            PackageInfoLite pkgLite = null;
10720
10721            if (onInt && onSd) {
10722                // Check if both bits are set.
10723                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10724                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10725            } else {
10726                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10727                        packageAbiOverride);
10728
10729                /*
10730                 * If we have too little free space, try to free cache
10731                 * before giving up.
10732                 */
10733                if (!origin.staged && pkgLite.recommendedInstallLocation
10734                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10735                    // TODO: focus freeing disk space on the target device
10736                    final StorageManager storage = StorageManager.from(mContext);
10737                    final long lowThreshold = storage.getStorageLowBytes(
10738                            Environment.getDataDirectory());
10739
10740                    final long sizeBytes = mContainerService.calculateInstalledSize(
10741                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10742
10743                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10744                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10745                                installFlags, packageAbiOverride);
10746                    }
10747
10748                    /*
10749                     * The cache free must have deleted the file we
10750                     * downloaded to install.
10751                     *
10752                     * TODO: fix the "freeCache" call to not delete
10753                     *       the file we care about.
10754                     */
10755                    if (pkgLite.recommendedInstallLocation
10756                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10757                        pkgLite.recommendedInstallLocation
10758                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10759                    }
10760                }
10761            }
10762
10763            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10764                int loc = pkgLite.recommendedInstallLocation;
10765                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10766                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10767                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10768                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10769                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10770                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10771                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10772                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10773                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10774                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10775                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10776                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10777                } else {
10778                    // Override with defaults if needed.
10779                    loc = installLocationPolicy(pkgLite);
10780                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10781                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10782                    } else if (!onSd && !onInt) {
10783                        // Override install location with flags
10784                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10785                            // Set the flag to install on external media.
10786                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10787                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10788                        } else {
10789                            // Make sure the flag for installing on external
10790                            // media is unset
10791                            installFlags |= PackageManager.INSTALL_INTERNAL;
10792                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10793                        }
10794                    }
10795                }
10796            }
10797
10798            final InstallArgs args = createInstallArgs(this);
10799            mArgs = args;
10800
10801            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10802                 /*
10803                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10804                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10805                 */
10806                int userIdentifier = getUser().getIdentifier();
10807                if (userIdentifier == UserHandle.USER_ALL
10808                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10809                    userIdentifier = UserHandle.USER_OWNER;
10810                }
10811
10812                /*
10813                 * Determine if we have any installed package verifiers. If we
10814                 * do, then we'll defer to them to verify the packages.
10815                 */
10816                final int requiredUid = mRequiredVerifierPackage == null ? -1
10817                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10818                if (!origin.existing && requiredUid != -1
10819                        && isVerificationEnabled(userIdentifier, installFlags)) {
10820                    final Intent verification = new Intent(
10821                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10822                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10823                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10824                            PACKAGE_MIME_TYPE);
10825                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10826
10827                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10828                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10829                            0 /* TODO: Which userId? */);
10830
10831                    if (DEBUG_VERIFY) {
10832                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10833                                + verification.toString() + " with " + pkgLite.verifiers.length
10834                                + " optional verifiers");
10835                    }
10836
10837                    final int verificationId = mPendingVerificationToken++;
10838
10839                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10840
10841                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10842                            installerPackageName);
10843
10844                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10845                            installFlags);
10846
10847                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10848                            pkgLite.packageName);
10849
10850                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10851                            pkgLite.versionCode);
10852
10853                    if (verificationParams != null) {
10854                        if (verificationParams.getVerificationURI() != null) {
10855                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10856                                 verificationParams.getVerificationURI());
10857                        }
10858                        if (verificationParams.getOriginatingURI() != null) {
10859                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10860                                  verificationParams.getOriginatingURI());
10861                        }
10862                        if (verificationParams.getReferrer() != null) {
10863                            verification.putExtra(Intent.EXTRA_REFERRER,
10864                                  verificationParams.getReferrer());
10865                        }
10866                        if (verificationParams.getOriginatingUid() >= 0) {
10867                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10868                                  verificationParams.getOriginatingUid());
10869                        }
10870                        if (verificationParams.getInstallerUid() >= 0) {
10871                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10872                                  verificationParams.getInstallerUid());
10873                        }
10874                    }
10875
10876                    final PackageVerificationState verificationState = new PackageVerificationState(
10877                            requiredUid, args);
10878
10879                    mPendingVerification.append(verificationId, verificationState);
10880
10881                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10882                            receivers, verificationState);
10883
10884                    // Apps installed for "all" users use the device owner to verify the app
10885                    UserHandle verifierUser = getUser();
10886                    if (verifierUser == UserHandle.ALL) {
10887                        verifierUser = UserHandle.OWNER;
10888                    }
10889
10890                    /*
10891                     * If any sufficient verifiers were listed in the package
10892                     * manifest, attempt to ask them.
10893                     */
10894                    if (sufficientVerifiers != null) {
10895                        final int N = sufficientVerifiers.size();
10896                        if (N == 0) {
10897                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10898                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10899                        } else {
10900                            for (int i = 0; i < N; i++) {
10901                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10902
10903                                final Intent sufficientIntent = new Intent(verification);
10904                                sufficientIntent.setComponent(verifierComponent);
10905                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10906                            }
10907                        }
10908                    }
10909
10910                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10911                            mRequiredVerifierPackage, receivers);
10912                    if (ret == PackageManager.INSTALL_SUCCEEDED
10913                            && mRequiredVerifierPackage != null) {
10914                        Trace.asyncTraceBegin(
10915                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
10916                        /*
10917                         * Send the intent to the required verification agent,
10918                         * but only start the verification timeout after the
10919                         * target BroadcastReceivers have run.
10920                         */
10921                        verification.setComponent(requiredVerifierComponent);
10922                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10923                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10924                                new BroadcastReceiver() {
10925                                    @Override
10926                                    public void onReceive(Context context, Intent intent) {
10927                                        final Message msg = mHandler
10928                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10929                                        msg.arg1 = verificationId;
10930                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10931                                    }
10932                                }, null, 0, null, null);
10933
10934                        /*
10935                         * We don't want the copy to proceed until verification
10936                         * succeeds, so null out this field.
10937                         */
10938                        mArgs = null;
10939                    }
10940                } else {
10941                    /*
10942                     * No package verification is enabled, so immediately start
10943                     * the remote call to initiate copy using temporary file.
10944                     */
10945                    ret = args.copyApk(mContainerService, true);
10946                }
10947            }
10948
10949            mRet = ret;
10950        }
10951
10952        @Override
10953        void handleReturnCode() {
10954            // If mArgs is null, then MCS couldn't be reached. When it
10955            // reconnects, it will try again to install. At that point, this
10956            // will succeed.
10957            if (mArgs != null) {
10958                processPendingInstall(mArgs, mRet);
10959            }
10960        }
10961
10962        @Override
10963        void handleServiceError() {
10964            mArgs = createInstallArgs(this);
10965            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10966        }
10967
10968        public boolean isForwardLocked() {
10969            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10970        }
10971    }
10972
10973    /**
10974     * Used during creation of InstallArgs
10975     *
10976     * @param installFlags package installation flags
10977     * @return true if should be installed on external storage
10978     */
10979    private static boolean installOnExternalAsec(int installFlags) {
10980        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10981            return false;
10982        }
10983        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10984            return true;
10985        }
10986        return false;
10987    }
10988
10989    /**
10990     * Used during creation of InstallArgs
10991     *
10992     * @param installFlags package installation flags
10993     * @return true if should be installed as forward locked
10994     */
10995    private static boolean installForwardLocked(int installFlags) {
10996        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10997    }
10998
10999    private InstallArgs createInstallArgs(InstallParams params) {
11000        if (params.move != null) {
11001            return new MoveInstallArgs(params);
11002        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11003            return new AsecInstallArgs(params);
11004        } else {
11005            return new FileInstallArgs(params);
11006        }
11007    }
11008
11009    /**
11010     * Create args that describe an existing installed package. Typically used
11011     * when cleaning up old installs, or used as a move source.
11012     */
11013    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11014            String resourcePath, String[] instructionSets) {
11015        final boolean isInAsec;
11016        if (installOnExternalAsec(installFlags)) {
11017            /* Apps on SD card are always in ASEC containers. */
11018            isInAsec = true;
11019        } else if (installForwardLocked(installFlags)
11020                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11021            /*
11022             * Forward-locked apps are only in ASEC containers if they're the
11023             * new style
11024             */
11025            isInAsec = true;
11026        } else {
11027            isInAsec = false;
11028        }
11029
11030        if (isInAsec) {
11031            return new AsecInstallArgs(codePath, instructionSets,
11032                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11033        } else {
11034            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11035        }
11036    }
11037
11038    static abstract class InstallArgs {
11039        /** @see InstallParams#origin */
11040        final OriginInfo origin;
11041        /** @see InstallParams#move */
11042        final MoveInfo move;
11043
11044        final IPackageInstallObserver2 observer;
11045        // Always refers to PackageManager flags only
11046        final int installFlags;
11047        final String installerPackageName;
11048        final String volumeUuid;
11049        final ManifestDigest manifestDigest;
11050        final UserHandle user;
11051        final String abiOverride;
11052        final String[] installGrantPermissions;
11053        /** If non-null, drop an async trace when the install completes */
11054        final String traceMethod;
11055        final int traceCookie;
11056
11057        // The list of instruction sets supported by this app. This is currently
11058        // only used during the rmdex() phase to clean up resources. We can get rid of this
11059        // if we move dex files under the common app path.
11060        /* nullable */ String[] instructionSets;
11061
11062        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11063                int installFlags, String installerPackageName, String volumeUuid,
11064                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11065                String abiOverride, String[] installGrantPermissions,
11066                String traceMethod, int traceCookie) {
11067            this.origin = origin;
11068            this.move = move;
11069            this.installFlags = installFlags;
11070            this.observer = observer;
11071            this.installerPackageName = installerPackageName;
11072            this.volumeUuid = volumeUuid;
11073            this.manifestDigest = manifestDigest;
11074            this.user = user;
11075            this.instructionSets = instructionSets;
11076            this.abiOverride = abiOverride;
11077            this.installGrantPermissions = installGrantPermissions;
11078            this.traceMethod = traceMethod;
11079            this.traceCookie = traceCookie;
11080        }
11081
11082        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11083        abstract int doPreInstall(int status);
11084
11085        /**
11086         * Rename package into final resting place. All paths on the given
11087         * scanned package should be updated to reflect the rename.
11088         */
11089        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11090        abstract int doPostInstall(int status, int uid);
11091
11092        /** @see PackageSettingBase#codePathString */
11093        abstract String getCodePath();
11094        /** @see PackageSettingBase#resourcePathString */
11095        abstract String getResourcePath();
11096
11097        // Need installer lock especially for dex file removal.
11098        abstract void cleanUpResourcesLI();
11099        abstract boolean doPostDeleteLI(boolean delete);
11100
11101        /**
11102         * Called before the source arguments are copied. This is used mostly
11103         * for MoveParams when it needs to read the source file to put it in the
11104         * destination.
11105         */
11106        int doPreCopy() {
11107            return PackageManager.INSTALL_SUCCEEDED;
11108        }
11109
11110        /**
11111         * Called after the source arguments are copied. This is used mostly for
11112         * MoveParams when it needs to read the source file to put it in the
11113         * destination.
11114         *
11115         * @return
11116         */
11117        int doPostCopy(int uid) {
11118            return PackageManager.INSTALL_SUCCEEDED;
11119        }
11120
11121        protected boolean isFwdLocked() {
11122            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11123        }
11124
11125        protected boolean isExternalAsec() {
11126            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11127        }
11128
11129        UserHandle getUser() {
11130            return user;
11131        }
11132    }
11133
11134    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11135        if (!allCodePaths.isEmpty()) {
11136            if (instructionSets == null) {
11137                throw new IllegalStateException("instructionSet == null");
11138            }
11139            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11140            for (String codePath : allCodePaths) {
11141                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11142                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11143                    if (retCode < 0) {
11144                        Slog.w(TAG, "Couldn't remove dex file for package: "
11145                                + " at location " + codePath + ", retcode=" + retCode);
11146                        // we don't consider this to be a failure of the core package deletion
11147                    }
11148                }
11149            }
11150        }
11151    }
11152
11153    /**
11154     * Logic to handle installation of non-ASEC applications, including copying
11155     * and renaming logic.
11156     */
11157    class FileInstallArgs extends InstallArgs {
11158        private File codeFile;
11159        private File resourceFile;
11160
11161        // Example topology:
11162        // /data/app/com.example/base.apk
11163        // /data/app/com.example/split_foo.apk
11164        // /data/app/com.example/lib/arm/libfoo.so
11165        // /data/app/com.example/lib/arm64/libfoo.so
11166        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11167
11168        /** New install */
11169        FileInstallArgs(InstallParams params) {
11170            super(params.origin, params.move, params.observer, params.installFlags,
11171                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11172                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11173                    params.grantedRuntimePermissions,
11174                    params.traceMethod, params.traceCookie);
11175            if (isFwdLocked()) {
11176                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11177            }
11178        }
11179
11180        /** Existing install */
11181        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11182            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11183                    null, null, null, 0);
11184            this.codeFile = (codePath != null) ? new File(codePath) : null;
11185            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11186        }
11187
11188        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11189            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11190            try {
11191                return doCopyApk(imcs, temp);
11192            } finally {
11193                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11194            }
11195        }
11196
11197        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11198            if (origin.staged) {
11199                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11200                codeFile = origin.file;
11201                resourceFile = origin.file;
11202                return PackageManager.INSTALL_SUCCEEDED;
11203            }
11204
11205            try {
11206                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11207                codeFile = tempDir;
11208                resourceFile = tempDir;
11209            } catch (IOException e) {
11210                Slog.w(TAG, "Failed to create copy file: " + e);
11211                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11212            }
11213
11214            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11215                @Override
11216                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11217                    if (!FileUtils.isValidExtFilename(name)) {
11218                        throw new IllegalArgumentException("Invalid filename: " + name);
11219                    }
11220                    try {
11221                        final File file = new File(codeFile, name);
11222                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11223                                O_RDWR | O_CREAT, 0644);
11224                        Os.chmod(file.getAbsolutePath(), 0644);
11225                        return new ParcelFileDescriptor(fd);
11226                    } catch (ErrnoException e) {
11227                        throw new RemoteException("Failed to open: " + e.getMessage());
11228                    }
11229                }
11230            };
11231
11232            int ret = PackageManager.INSTALL_SUCCEEDED;
11233            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11234            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11235                Slog.e(TAG, "Failed to copy package");
11236                return ret;
11237            }
11238
11239            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11240            NativeLibraryHelper.Handle handle = null;
11241            try {
11242                handle = NativeLibraryHelper.Handle.create(codeFile);
11243                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11244                        abiOverride);
11245            } catch (IOException e) {
11246                Slog.e(TAG, "Copying native libraries failed", e);
11247                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11248            } finally {
11249                IoUtils.closeQuietly(handle);
11250            }
11251
11252            return ret;
11253        }
11254
11255        int doPreInstall(int status) {
11256            if (status != PackageManager.INSTALL_SUCCEEDED) {
11257                cleanUp();
11258            }
11259            return status;
11260        }
11261
11262        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11263            if (status != PackageManager.INSTALL_SUCCEEDED) {
11264                cleanUp();
11265                return false;
11266            }
11267
11268            final File targetDir = codeFile.getParentFile();
11269            final File beforeCodeFile = codeFile;
11270            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11271
11272            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11273            try {
11274                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11275            } catch (ErrnoException e) {
11276                Slog.w(TAG, "Failed to rename", e);
11277                return false;
11278            }
11279
11280            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11281                Slog.w(TAG, "Failed to restorecon");
11282                return false;
11283            }
11284
11285            // Reflect the rename internally
11286            codeFile = afterCodeFile;
11287            resourceFile = afterCodeFile;
11288
11289            // Reflect the rename in scanned details
11290            pkg.codePath = afterCodeFile.getAbsolutePath();
11291            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11292                    pkg.baseCodePath);
11293            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11294                    pkg.splitCodePaths);
11295
11296            // Reflect the rename in app info
11297            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11298            pkg.applicationInfo.setCodePath(pkg.codePath);
11299            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11300            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11301            pkg.applicationInfo.setResourcePath(pkg.codePath);
11302            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11303            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11304
11305            return true;
11306        }
11307
11308        int doPostInstall(int status, int uid) {
11309            if (status != PackageManager.INSTALL_SUCCEEDED) {
11310                cleanUp();
11311            }
11312            return status;
11313        }
11314
11315        @Override
11316        String getCodePath() {
11317            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11318        }
11319
11320        @Override
11321        String getResourcePath() {
11322            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11323        }
11324
11325        private boolean cleanUp() {
11326            if (codeFile == null || !codeFile.exists()) {
11327                return false;
11328            }
11329
11330            if (codeFile.isDirectory()) {
11331                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11332            } else {
11333                codeFile.delete();
11334            }
11335
11336            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11337                resourceFile.delete();
11338            }
11339
11340            return true;
11341        }
11342
11343        void cleanUpResourcesLI() {
11344            // Try enumerating all code paths before deleting
11345            List<String> allCodePaths = Collections.EMPTY_LIST;
11346            if (codeFile != null && codeFile.exists()) {
11347                try {
11348                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11349                    allCodePaths = pkg.getAllCodePaths();
11350                } catch (PackageParserException e) {
11351                    // Ignored; we tried our best
11352                }
11353            }
11354
11355            cleanUp();
11356            removeDexFiles(allCodePaths, instructionSets);
11357        }
11358
11359        boolean doPostDeleteLI(boolean delete) {
11360            // XXX err, shouldn't we respect the delete flag?
11361            cleanUpResourcesLI();
11362            return true;
11363        }
11364    }
11365
11366    private boolean isAsecExternal(String cid) {
11367        final String asecPath = PackageHelper.getSdFilesystem(cid);
11368        return !asecPath.startsWith(mAsecInternalPath);
11369    }
11370
11371    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11372            PackageManagerException {
11373        if (copyRet < 0) {
11374            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11375                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11376                throw new PackageManagerException(copyRet, message);
11377            }
11378        }
11379    }
11380
11381    /**
11382     * Extract the MountService "container ID" from the full code path of an
11383     * .apk.
11384     */
11385    static String cidFromCodePath(String fullCodePath) {
11386        int eidx = fullCodePath.lastIndexOf("/");
11387        String subStr1 = fullCodePath.substring(0, eidx);
11388        int sidx = subStr1.lastIndexOf("/");
11389        return subStr1.substring(sidx+1, eidx);
11390    }
11391
11392    /**
11393     * Logic to handle installation of ASEC applications, including copying and
11394     * renaming logic.
11395     */
11396    class AsecInstallArgs extends InstallArgs {
11397        static final String RES_FILE_NAME = "pkg.apk";
11398        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11399
11400        String cid;
11401        String packagePath;
11402        String resourcePath;
11403
11404        /** New install */
11405        AsecInstallArgs(InstallParams params) {
11406            super(params.origin, params.move, params.observer, params.installFlags,
11407                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11408                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11409                    params.grantedRuntimePermissions,
11410                    params.traceMethod, params.traceCookie);
11411        }
11412
11413        /** Existing install */
11414        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11415                        boolean isExternal, boolean isForwardLocked) {
11416            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11417                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11418                    instructionSets, null, null, null, 0);
11419            // Hackily pretend we're still looking at a full code path
11420            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11421                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11422            }
11423
11424            // Extract cid from fullCodePath
11425            int eidx = fullCodePath.lastIndexOf("/");
11426            String subStr1 = fullCodePath.substring(0, eidx);
11427            int sidx = subStr1.lastIndexOf("/");
11428            cid = subStr1.substring(sidx+1, eidx);
11429            setMountPath(subStr1);
11430        }
11431
11432        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11433            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11434                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11435                    instructionSets, null, null, null, 0);
11436            this.cid = cid;
11437            setMountPath(PackageHelper.getSdDir(cid));
11438        }
11439
11440        void createCopyFile() {
11441            cid = mInstallerService.allocateExternalStageCidLegacy();
11442        }
11443
11444        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11445            if (origin.staged) {
11446                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11447                cid = origin.cid;
11448                setMountPath(PackageHelper.getSdDir(cid));
11449                return PackageManager.INSTALL_SUCCEEDED;
11450            }
11451
11452            if (temp) {
11453                createCopyFile();
11454            } else {
11455                /*
11456                 * Pre-emptively destroy the container since it's destroyed if
11457                 * copying fails due to it existing anyway.
11458                 */
11459                PackageHelper.destroySdDir(cid);
11460            }
11461
11462            final String newMountPath = imcs.copyPackageToContainer(
11463                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11464                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11465
11466            if (newMountPath != null) {
11467                setMountPath(newMountPath);
11468                return PackageManager.INSTALL_SUCCEEDED;
11469            } else {
11470                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11471            }
11472        }
11473
11474        @Override
11475        String getCodePath() {
11476            return packagePath;
11477        }
11478
11479        @Override
11480        String getResourcePath() {
11481            return resourcePath;
11482        }
11483
11484        int doPreInstall(int status) {
11485            if (status != PackageManager.INSTALL_SUCCEEDED) {
11486                // Destroy container
11487                PackageHelper.destroySdDir(cid);
11488            } else {
11489                boolean mounted = PackageHelper.isContainerMounted(cid);
11490                if (!mounted) {
11491                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11492                            Process.SYSTEM_UID);
11493                    if (newMountPath != null) {
11494                        setMountPath(newMountPath);
11495                    } else {
11496                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11497                    }
11498                }
11499            }
11500            return status;
11501        }
11502
11503        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11504            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11505            String newMountPath = null;
11506            if (PackageHelper.isContainerMounted(cid)) {
11507                // Unmount the container
11508                if (!PackageHelper.unMountSdDir(cid)) {
11509                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11510                    return false;
11511                }
11512            }
11513            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11514                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11515                        " which might be stale. Will try to clean up.");
11516                // Clean up the stale container and proceed to recreate.
11517                if (!PackageHelper.destroySdDir(newCacheId)) {
11518                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11519                    return false;
11520                }
11521                // Successfully cleaned up stale container. Try to rename again.
11522                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11523                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11524                            + " inspite of cleaning it up.");
11525                    return false;
11526                }
11527            }
11528            if (!PackageHelper.isContainerMounted(newCacheId)) {
11529                Slog.w(TAG, "Mounting container " + newCacheId);
11530                newMountPath = PackageHelper.mountSdDir(newCacheId,
11531                        getEncryptKey(), Process.SYSTEM_UID);
11532            } else {
11533                newMountPath = PackageHelper.getSdDir(newCacheId);
11534            }
11535            if (newMountPath == null) {
11536                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11537                return false;
11538            }
11539            Log.i(TAG, "Succesfully renamed " + cid +
11540                    " to " + newCacheId +
11541                    " at new path: " + newMountPath);
11542            cid = newCacheId;
11543
11544            final File beforeCodeFile = new File(packagePath);
11545            setMountPath(newMountPath);
11546            final File afterCodeFile = new File(packagePath);
11547
11548            // Reflect the rename in scanned details
11549            pkg.codePath = afterCodeFile.getAbsolutePath();
11550            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11551                    pkg.baseCodePath);
11552            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11553                    pkg.splitCodePaths);
11554
11555            // Reflect the rename in app info
11556            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11557            pkg.applicationInfo.setCodePath(pkg.codePath);
11558            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11559            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11560            pkg.applicationInfo.setResourcePath(pkg.codePath);
11561            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11562            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11563
11564            return true;
11565        }
11566
11567        private void setMountPath(String mountPath) {
11568            final File mountFile = new File(mountPath);
11569
11570            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11571            if (monolithicFile.exists()) {
11572                packagePath = monolithicFile.getAbsolutePath();
11573                if (isFwdLocked()) {
11574                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11575                } else {
11576                    resourcePath = packagePath;
11577                }
11578            } else {
11579                packagePath = mountFile.getAbsolutePath();
11580                resourcePath = packagePath;
11581            }
11582        }
11583
11584        int doPostInstall(int status, int uid) {
11585            if (status != PackageManager.INSTALL_SUCCEEDED) {
11586                cleanUp();
11587            } else {
11588                final int groupOwner;
11589                final String protectedFile;
11590                if (isFwdLocked()) {
11591                    groupOwner = UserHandle.getSharedAppGid(uid);
11592                    protectedFile = RES_FILE_NAME;
11593                } else {
11594                    groupOwner = -1;
11595                    protectedFile = null;
11596                }
11597
11598                if (uid < Process.FIRST_APPLICATION_UID
11599                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11600                    Slog.e(TAG, "Failed to finalize " + cid);
11601                    PackageHelper.destroySdDir(cid);
11602                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11603                }
11604
11605                boolean mounted = PackageHelper.isContainerMounted(cid);
11606                if (!mounted) {
11607                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11608                }
11609            }
11610            return status;
11611        }
11612
11613        private void cleanUp() {
11614            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11615
11616            // Destroy secure container
11617            PackageHelper.destroySdDir(cid);
11618        }
11619
11620        private List<String> getAllCodePaths() {
11621            final File codeFile = new File(getCodePath());
11622            if (codeFile != null && codeFile.exists()) {
11623                try {
11624                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11625                    return pkg.getAllCodePaths();
11626                } catch (PackageParserException e) {
11627                    // Ignored; we tried our best
11628                }
11629            }
11630            return Collections.EMPTY_LIST;
11631        }
11632
11633        void cleanUpResourcesLI() {
11634            // Enumerate all code paths before deleting
11635            cleanUpResourcesLI(getAllCodePaths());
11636        }
11637
11638        private void cleanUpResourcesLI(List<String> allCodePaths) {
11639            cleanUp();
11640            removeDexFiles(allCodePaths, instructionSets);
11641        }
11642
11643        String getPackageName() {
11644            return getAsecPackageName(cid);
11645        }
11646
11647        boolean doPostDeleteLI(boolean delete) {
11648            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11649            final List<String> allCodePaths = getAllCodePaths();
11650            boolean mounted = PackageHelper.isContainerMounted(cid);
11651            if (mounted) {
11652                // Unmount first
11653                if (PackageHelper.unMountSdDir(cid)) {
11654                    mounted = false;
11655                }
11656            }
11657            if (!mounted && delete) {
11658                cleanUpResourcesLI(allCodePaths);
11659            }
11660            return !mounted;
11661        }
11662
11663        @Override
11664        int doPreCopy() {
11665            if (isFwdLocked()) {
11666                if (!PackageHelper.fixSdPermissions(cid,
11667                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11668                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11669                }
11670            }
11671
11672            return PackageManager.INSTALL_SUCCEEDED;
11673        }
11674
11675        @Override
11676        int doPostCopy(int uid) {
11677            if (isFwdLocked()) {
11678                if (uid < Process.FIRST_APPLICATION_UID
11679                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11680                                RES_FILE_NAME)) {
11681                    Slog.e(TAG, "Failed to finalize " + cid);
11682                    PackageHelper.destroySdDir(cid);
11683                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11684                }
11685            }
11686
11687            return PackageManager.INSTALL_SUCCEEDED;
11688        }
11689    }
11690
11691    /**
11692     * Logic to handle movement of existing installed applications.
11693     */
11694    class MoveInstallArgs extends InstallArgs {
11695        private File codeFile;
11696        private File resourceFile;
11697
11698        /** New install */
11699        MoveInstallArgs(InstallParams params) {
11700            super(params.origin, params.move, params.observer, params.installFlags,
11701                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11702                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11703                    params.grantedRuntimePermissions,
11704                    params.traceMethod, params.traceCookie);
11705        }
11706
11707        int copyApk(IMediaContainerService imcs, boolean temp) {
11708            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11709                    + move.fromUuid + " to " + move.toUuid);
11710            synchronized (mInstaller) {
11711                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11712                        move.dataAppName, move.appId, move.seinfo) != 0) {
11713                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11714                }
11715            }
11716
11717            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11718            resourceFile = codeFile;
11719            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11720
11721            return PackageManager.INSTALL_SUCCEEDED;
11722        }
11723
11724        int doPreInstall(int status) {
11725            if (status != PackageManager.INSTALL_SUCCEEDED) {
11726                cleanUp(move.toUuid);
11727            }
11728            return status;
11729        }
11730
11731        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11732            if (status != PackageManager.INSTALL_SUCCEEDED) {
11733                cleanUp(move.toUuid);
11734                return false;
11735            }
11736
11737            // Reflect the move in app info
11738            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11739            pkg.applicationInfo.setCodePath(pkg.codePath);
11740            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11741            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11742            pkg.applicationInfo.setResourcePath(pkg.codePath);
11743            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11744            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11745
11746            return true;
11747        }
11748
11749        int doPostInstall(int status, int uid) {
11750            if (status == PackageManager.INSTALL_SUCCEEDED) {
11751                cleanUp(move.fromUuid);
11752            } else {
11753                cleanUp(move.toUuid);
11754            }
11755            return status;
11756        }
11757
11758        @Override
11759        String getCodePath() {
11760            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11761        }
11762
11763        @Override
11764        String getResourcePath() {
11765            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11766        }
11767
11768        private boolean cleanUp(String volumeUuid) {
11769            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11770                    move.dataAppName);
11771            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11772            synchronized (mInstallLock) {
11773                // Clean up both app data and code
11774                removeDataDirsLI(volumeUuid, move.packageName);
11775                if (codeFile.isDirectory()) {
11776                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11777                } else {
11778                    codeFile.delete();
11779                }
11780            }
11781            return true;
11782        }
11783
11784        void cleanUpResourcesLI() {
11785            throw new UnsupportedOperationException();
11786        }
11787
11788        boolean doPostDeleteLI(boolean delete) {
11789            throw new UnsupportedOperationException();
11790        }
11791    }
11792
11793    static String getAsecPackageName(String packageCid) {
11794        int idx = packageCid.lastIndexOf("-");
11795        if (idx == -1) {
11796            return packageCid;
11797        }
11798        return packageCid.substring(0, idx);
11799    }
11800
11801    // Utility method used to create code paths based on package name and available index.
11802    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11803        String idxStr = "";
11804        int idx = 1;
11805        // Fall back to default value of idx=1 if prefix is not
11806        // part of oldCodePath
11807        if (oldCodePath != null) {
11808            String subStr = oldCodePath;
11809            // Drop the suffix right away
11810            if (suffix != null && subStr.endsWith(suffix)) {
11811                subStr = subStr.substring(0, subStr.length() - suffix.length());
11812            }
11813            // If oldCodePath already contains prefix find out the
11814            // ending index to either increment or decrement.
11815            int sidx = subStr.lastIndexOf(prefix);
11816            if (sidx != -1) {
11817                subStr = subStr.substring(sidx + prefix.length());
11818                if (subStr != null) {
11819                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11820                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11821                    }
11822                    try {
11823                        idx = Integer.parseInt(subStr);
11824                        if (idx <= 1) {
11825                            idx++;
11826                        } else {
11827                            idx--;
11828                        }
11829                    } catch(NumberFormatException e) {
11830                    }
11831                }
11832            }
11833        }
11834        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11835        return prefix + idxStr;
11836    }
11837
11838    private File getNextCodePath(File targetDir, String packageName) {
11839        int suffix = 1;
11840        File result;
11841        do {
11842            result = new File(targetDir, packageName + "-" + suffix);
11843            suffix++;
11844        } while (result.exists());
11845        return result;
11846    }
11847
11848    // Utility method that returns the relative package path with respect
11849    // to the installation directory. Like say for /data/data/com.test-1.apk
11850    // string com.test-1 is returned.
11851    static String deriveCodePathName(String codePath) {
11852        if (codePath == null) {
11853            return null;
11854        }
11855        final File codeFile = new File(codePath);
11856        final String name = codeFile.getName();
11857        if (codeFile.isDirectory()) {
11858            return name;
11859        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11860            final int lastDot = name.lastIndexOf('.');
11861            return name.substring(0, lastDot);
11862        } else {
11863            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11864            return null;
11865        }
11866    }
11867
11868    class PackageInstalledInfo {
11869        String name;
11870        int uid;
11871        // The set of users that originally had this package installed.
11872        int[] origUsers;
11873        // The set of users that now have this package installed.
11874        int[] newUsers;
11875        PackageParser.Package pkg;
11876        int returnCode;
11877        String returnMsg;
11878        PackageRemovedInfo removedInfo;
11879
11880        public void setError(int code, String msg) {
11881            returnCode = code;
11882            returnMsg = msg;
11883            Slog.w(TAG, msg);
11884        }
11885
11886        public void setError(String msg, PackageParserException e) {
11887            returnCode = e.error;
11888            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11889            Slog.w(TAG, msg, e);
11890        }
11891
11892        public void setError(String msg, PackageManagerException e) {
11893            returnCode = e.error;
11894            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11895            Slog.w(TAG, msg, e);
11896        }
11897
11898        // In some error cases we want to convey more info back to the observer
11899        String origPackage;
11900        String origPermission;
11901    }
11902
11903    /*
11904     * Install a non-existing package.
11905     */
11906    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11907            UserHandle user, String installerPackageName, String volumeUuid,
11908            PackageInstalledInfo res) {
11909        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
11910
11911        // Remember this for later, in case we need to rollback this install
11912        String pkgName = pkg.packageName;
11913
11914        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11915        // TODO: b/23350563
11916        final boolean dataDirExists = Environment
11917                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
11918
11919        synchronized(mPackages) {
11920            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11921                // A package with the same name is already installed, though
11922                // it has been renamed to an older name.  The package we
11923                // are trying to install should be installed as an update to
11924                // the existing one, but that has not been requested, so bail.
11925                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11926                        + " without first uninstalling package running as "
11927                        + mSettings.mRenamedPackages.get(pkgName));
11928                return;
11929            }
11930            if (mPackages.containsKey(pkgName)) {
11931                // Don't allow installation over an existing package with the same name.
11932                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11933                        + " without first uninstalling.");
11934                return;
11935            }
11936        }
11937
11938        try {
11939            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
11940                    System.currentTimeMillis(), user);
11941
11942            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11943            // delete the partially installed application. the data directory will have to be
11944            // restored if it was already existing
11945            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11946                // remove package from internal structures.  Note that we want deletePackageX to
11947                // delete the package data and cache directories that it created in
11948                // scanPackageLocked, unless those directories existed before we even tried to
11949                // install.
11950                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11951                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11952                                res.removedInfo, true);
11953            }
11954
11955        } catch (PackageManagerException e) {
11956            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11957        }
11958
11959        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11960    }
11961
11962    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11963        // Can't rotate keys during boot or if sharedUser.
11964        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11965                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11966            return false;
11967        }
11968        // app is using upgradeKeySets; make sure all are valid
11969        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11970        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11971        for (int i = 0; i < upgradeKeySets.length; i++) {
11972            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11973                Slog.wtf(TAG, "Package "
11974                         + (oldPs.name != null ? oldPs.name : "<null>")
11975                         + " contains upgrade-key-set reference to unknown key-set: "
11976                         + upgradeKeySets[i]
11977                         + " reverting to signatures check.");
11978                return false;
11979            }
11980        }
11981        return true;
11982    }
11983
11984    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11985        // Upgrade keysets are being used.  Determine if new package has a superset of the
11986        // required keys.
11987        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11988        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11989        for (int i = 0; i < upgradeKeySets.length; i++) {
11990            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11991            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11992                return true;
11993            }
11994        }
11995        return false;
11996    }
11997
11998    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11999            UserHandle user, String installerPackageName, String volumeUuid,
12000            PackageInstalledInfo res) {
12001        final PackageParser.Package oldPackage;
12002        final String pkgName = pkg.packageName;
12003        final int[] allUsers;
12004        final boolean[] perUserInstalled;
12005
12006        // First find the old package info and check signatures
12007        synchronized(mPackages) {
12008            oldPackage = mPackages.get(pkgName);
12009            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12010            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12011            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12012                if(!checkUpgradeKeySetLP(ps, pkg)) {
12013                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12014                            "New package not signed by keys specified by upgrade-keysets: "
12015                            + pkgName);
12016                    return;
12017                }
12018            } else {
12019                // default to original signature matching
12020                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12021                    != PackageManager.SIGNATURE_MATCH) {
12022                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12023                            "New package has a different signature: " + pkgName);
12024                    return;
12025                }
12026            }
12027
12028            // In case of rollback, remember per-user/profile install state
12029            allUsers = sUserManager.getUserIds();
12030            perUserInstalled = new boolean[allUsers.length];
12031            for (int i = 0; i < allUsers.length; i++) {
12032                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12033            }
12034        }
12035
12036        boolean sysPkg = (isSystemApp(oldPackage));
12037        if (sysPkg) {
12038            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12039                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12040        } else {
12041            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12042                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12043        }
12044    }
12045
12046    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12047            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12048            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12049            String volumeUuid, PackageInstalledInfo res) {
12050        String pkgName = deletedPackage.packageName;
12051        boolean deletedPkg = true;
12052        boolean updatedSettings = false;
12053
12054        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12055                + deletedPackage);
12056        long origUpdateTime;
12057        if (pkg.mExtras != null) {
12058            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12059        } else {
12060            origUpdateTime = 0;
12061        }
12062
12063        // First delete the existing package while retaining the data directory
12064        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12065                res.removedInfo, true)) {
12066            // If the existing package wasn't successfully deleted
12067            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12068            deletedPkg = false;
12069        } else {
12070            // Successfully deleted the old package; proceed with replace.
12071
12072            // If deleted package lived in a container, give users a chance to
12073            // relinquish resources before killing.
12074            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12075                if (DEBUG_INSTALL) {
12076                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12077                }
12078                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12079                final ArrayList<String> pkgList = new ArrayList<String>(1);
12080                pkgList.add(deletedPackage.applicationInfo.packageName);
12081                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12082            }
12083
12084            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12085            try {
12086                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12087                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12088                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12089                        perUserInstalled, res, user);
12090                updatedSettings = true;
12091            } catch (PackageManagerException e) {
12092                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12093            }
12094        }
12095
12096        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12097            // remove package from internal structures.  Note that we want deletePackageX to
12098            // delete the package data and cache directories that it created in
12099            // scanPackageLocked, unless those directories existed before we even tried to
12100            // install.
12101            if(updatedSettings) {
12102                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12103                deletePackageLI(
12104                        pkgName, null, true, allUsers, perUserInstalled,
12105                        PackageManager.DELETE_KEEP_DATA,
12106                                res.removedInfo, true);
12107            }
12108            // Since we failed to install the new package we need to restore the old
12109            // package that we deleted.
12110            if (deletedPkg) {
12111                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12112                File restoreFile = new File(deletedPackage.codePath);
12113                // Parse old package
12114                boolean oldExternal = isExternal(deletedPackage);
12115                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12116                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12117                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12118                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12119                try {
12120                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
12121                } catch (PackageManagerException e) {
12122                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12123                            + e.getMessage());
12124                    return;
12125                }
12126                // Restore of old package succeeded. Update permissions.
12127                // writer
12128                synchronized (mPackages) {
12129                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12130                            UPDATE_PERMISSIONS_ALL);
12131                    // can downgrade to reader
12132                    mSettings.writeLPr();
12133                }
12134                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12135            }
12136        }
12137    }
12138
12139    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12140            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12141            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12142            String volumeUuid, PackageInstalledInfo res) {
12143        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12144                + ", old=" + deletedPackage);
12145        boolean disabledSystem = false;
12146        boolean updatedSettings = false;
12147        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12148        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12149                != 0) {
12150            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12151        }
12152        String packageName = deletedPackage.packageName;
12153        if (packageName == null) {
12154            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12155                    "Attempt to delete null packageName.");
12156            return;
12157        }
12158        PackageParser.Package oldPkg;
12159        PackageSetting oldPkgSetting;
12160        // reader
12161        synchronized (mPackages) {
12162            oldPkg = mPackages.get(packageName);
12163            oldPkgSetting = mSettings.mPackages.get(packageName);
12164            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12165                    (oldPkgSetting == null)) {
12166                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12167                        "Couldn't find package:" + packageName + " information");
12168                return;
12169            }
12170        }
12171
12172        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12173
12174        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12175        res.removedInfo.removedPackage = packageName;
12176        // Remove existing system package
12177        removePackageLI(oldPkgSetting, true);
12178        // writer
12179        synchronized (mPackages) {
12180            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12181            if (!disabledSystem && deletedPackage != null) {
12182                // We didn't need to disable the .apk as a current system package,
12183                // which means we are replacing another update that is already
12184                // installed.  We need to make sure to delete the older one's .apk.
12185                res.removedInfo.args = createInstallArgsForExisting(0,
12186                        deletedPackage.applicationInfo.getCodePath(),
12187                        deletedPackage.applicationInfo.getResourcePath(),
12188                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12189            } else {
12190                res.removedInfo.args = null;
12191            }
12192        }
12193
12194        // Successfully disabled the old package. Now proceed with re-installation
12195        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12196
12197        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12198        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12199
12200        PackageParser.Package newPackage = null;
12201        try {
12202            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12203            if (newPackage.mExtras != null) {
12204                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12205                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12206                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12207
12208                // is the update attempting to change shared user? that isn't going to work...
12209                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12210                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12211                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12212                            + " to " + newPkgSetting.sharedUser);
12213                    updatedSettings = true;
12214                }
12215            }
12216
12217            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12218                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12219                        perUserInstalled, res, user);
12220                updatedSettings = true;
12221            }
12222
12223        } catch (PackageManagerException e) {
12224            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12225        }
12226
12227        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12228            // Re installation failed. Restore old information
12229            // Remove new pkg information
12230            if (newPackage != null) {
12231                removeInstalledPackageLI(newPackage, true);
12232            }
12233            // Add back the old system package
12234            try {
12235                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12236            } catch (PackageManagerException e) {
12237                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12238            }
12239            // Restore the old system information in Settings
12240            synchronized (mPackages) {
12241                if (disabledSystem) {
12242                    mSettings.enableSystemPackageLPw(packageName);
12243                }
12244                if (updatedSettings) {
12245                    mSettings.setInstallerPackageName(packageName,
12246                            oldPkgSetting.installerPackageName);
12247                }
12248                mSettings.writeLPr();
12249            }
12250        }
12251    }
12252
12253    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12254            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12255            UserHandle user) {
12256        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12257
12258        String pkgName = newPackage.packageName;
12259        synchronized (mPackages) {
12260            //write settings. the installStatus will be incomplete at this stage.
12261            //note that the new package setting would have already been
12262            //added to mPackages. It hasn't been persisted yet.
12263            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12264            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12265            mSettings.writeLPr();
12266            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12267        }
12268
12269        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12270        synchronized (mPackages) {
12271            updatePermissionsLPw(newPackage.packageName, newPackage,
12272                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12273                            ? UPDATE_PERMISSIONS_ALL : 0));
12274            // For system-bundled packages, we assume that installing an upgraded version
12275            // of the package implies that the user actually wants to run that new code,
12276            // so we enable the package.
12277            PackageSetting ps = mSettings.mPackages.get(pkgName);
12278            if (ps != null) {
12279                if (isSystemApp(newPackage)) {
12280                    // NB: implicit assumption that system package upgrades apply to all users
12281                    if (DEBUG_INSTALL) {
12282                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12283                    }
12284                    if (res.origUsers != null) {
12285                        for (int userHandle : res.origUsers) {
12286                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12287                                    userHandle, installerPackageName);
12288                        }
12289                    }
12290                    // Also convey the prior install/uninstall state
12291                    if (allUsers != null && perUserInstalled != null) {
12292                        for (int i = 0; i < allUsers.length; i++) {
12293                            if (DEBUG_INSTALL) {
12294                                Slog.d(TAG, "    user " + allUsers[i]
12295                                        + " => " + perUserInstalled[i]);
12296                            }
12297                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12298                        }
12299                        // these install state changes will be persisted in the
12300                        // upcoming call to mSettings.writeLPr().
12301                    }
12302                }
12303                // It's implied that when a user requests installation, they want the app to be
12304                // installed and enabled.
12305                int userId = user.getIdentifier();
12306                if (userId != UserHandle.USER_ALL) {
12307                    ps.setInstalled(true, userId);
12308                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12309                }
12310            }
12311            res.name = pkgName;
12312            res.uid = newPackage.applicationInfo.uid;
12313            res.pkg = newPackage;
12314            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12315            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12316            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12317            //to update install status
12318            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12319            mSettings.writeLPr();
12320            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12321        }
12322
12323        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12324    }
12325
12326    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12327        try {
12328            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12329            installPackageLI(args, res);
12330        } finally {
12331            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12332        }
12333    }
12334
12335    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12336        final int installFlags = args.installFlags;
12337        final String installerPackageName = args.installerPackageName;
12338        final String volumeUuid = args.volumeUuid;
12339        final File tmpPackageFile = new File(args.getCodePath());
12340        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12341        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12342                || (args.volumeUuid != null));
12343        boolean replace = false;
12344        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12345        if (args.move != null) {
12346            // moving a complete application; perfom an initial scan on the new install location
12347            scanFlags |= SCAN_INITIAL;
12348        }
12349        // Result object to be returned
12350        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12351
12352        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12353
12354        // Retrieve PackageSettings and parse package
12355        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12356                | PackageParser.PARSE_ENFORCE_CODE
12357                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12358                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12359        PackageParser pp = new PackageParser();
12360        pp.setSeparateProcesses(mSeparateProcesses);
12361        pp.setDisplayMetrics(mMetrics);
12362
12363        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12364        final PackageParser.Package pkg;
12365        try {
12366            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12367        } catch (PackageParserException e) {
12368            res.setError("Failed parse during installPackageLI", e);
12369            return;
12370        } finally {
12371            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12372        }
12373
12374        // Mark that we have an install time CPU ABI override.
12375        pkg.cpuAbiOverride = args.abiOverride;
12376
12377        String pkgName = res.name = pkg.packageName;
12378        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12379            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12380                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12381                return;
12382            }
12383        }
12384
12385        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12386        try {
12387            pp.collectCertificates(pkg, parseFlags);
12388            pp.collectManifestDigest(pkg);
12389        } catch (PackageParserException e) {
12390            res.setError("Failed collect during installPackageLI", e);
12391            return;
12392        } finally {
12393            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12394        }
12395
12396        /* If the installer passed in a manifest digest, compare it now. */
12397        if (args.manifestDigest != null) {
12398            if (DEBUG_INSTALL) {
12399                final String parsedManifest = pkg.manifestDigest == null ? "null"
12400                        : pkg.manifestDigest.toString();
12401                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12402                        + parsedManifest);
12403            }
12404
12405            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12406                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12407                return;
12408            }
12409        } else if (DEBUG_INSTALL) {
12410            final String parsedManifest = pkg.manifestDigest == null
12411                    ? "null" : pkg.manifestDigest.toString();
12412            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12413        }
12414
12415        // Get rid of all references to package scan path via parser.
12416        pp = null;
12417        String oldCodePath = null;
12418        boolean systemApp = false;
12419        synchronized (mPackages) {
12420            // Check if installing already existing package
12421            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12422                String oldName = mSettings.mRenamedPackages.get(pkgName);
12423                if (pkg.mOriginalPackages != null
12424                        && pkg.mOriginalPackages.contains(oldName)
12425                        && mPackages.containsKey(oldName)) {
12426                    // This package is derived from an original package,
12427                    // and this device has been updating from that original
12428                    // name.  We must continue using the original name, so
12429                    // rename the new package here.
12430                    pkg.setPackageName(oldName);
12431                    pkgName = pkg.packageName;
12432                    replace = true;
12433                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12434                            + oldName + " pkgName=" + pkgName);
12435                } else if (mPackages.containsKey(pkgName)) {
12436                    // This package, under its official name, already exists
12437                    // on the device; we should replace it.
12438                    replace = true;
12439                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12440                }
12441
12442                // Prevent apps opting out from runtime permissions
12443                if (replace) {
12444                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12445                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12446                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12447                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12448                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12449                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12450                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12451                                        + " doesn't support runtime permissions but the old"
12452                                        + " target SDK " + oldTargetSdk + " does.");
12453                        return;
12454                    }
12455                }
12456            }
12457
12458            PackageSetting ps = mSettings.mPackages.get(pkgName);
12459            if (ps != null) {
12460                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12461
12462                // Quick sanity check that we're signed correctly if updating;
12463                // we'll check this again later when scanning, but we want to
12464                // bail early here before tripping over redefined permissions.
12465                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12466                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12467                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12468                                + pkg.packageName + " upgrade keys do not match the "
12469                                + "previously installed version");
12470                        return;
12471                    }
12472                } else {
12473                    try {
12474                        verifySignaturesLP(ps, pkg);
12475                    } catch (PackageManagerException e) {
12476                        res.setError(e.error, e.getMessage());
12477                        return;
12478                    }
12479                }
12480
12481                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12482                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12483                    systemApp = (ps.pkg.applicationInfo.flags &
12484                            ApplicationInfo.FLAG_SYSTEM) != 0;
12485                }
12486                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12487            }
12488
12489            // Check whether the newly-scanned package wants to define an already-defined perm
12490            int N = pkg.permissions.size();
12491            for (int i = N-1; i >= 0; i--) {
12492                PackageParser.Permission perm = pkg.permissions.get(i);
12493                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12494                if (bp != null) {
12495                    // If the defining package is signed with our cert, it's okay.  This
12496                    // also includes the "updating the same package" case, of course.
12497                    // "updating same package" could also involve key-rotation.
12498                    final boolean sigsOk;
12499                    if (bp.sourcePackage.equals(pkg.packageName)
12500                            && (bp.packageSetting instanceof PackageSetting)
12501                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12502                                    scanFlags))) {
12503                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12504                    } else {
12505                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12506                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12507                    }
12508                    if (!sigsOk) {
12509                        // If the owning package is the system itself, we log but allow
12510                        // install to proceed; we fail the install on all other permission
12511                        // redefinitions.
12512                        if (!bp.sourcePackage.equals("android")) {
12513                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12514                                    + pkg.packageName + " attempting to redeclare permission "
12515                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12516                            res.origPermission = perm.info.name;
12517                            res.origPackage = bp.sourcePackage;
12518                            return;
12519                        } else {
12520                            Slog.w(TAG, "Package " + pkg.packageName
12521                                    + " attempting to redeclare system permission "
12522                                    + perm.info.name + "; ignoring new declaration");
12523                            pkg.permissions.remove(i);
12524                        }
12525                    }
12526                }
12527            }
12528
12529        }
12530
12531        if (systemApp && onExternal) {
12532            // Disable updates to system apps on sdcard
12533            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12534                    "Cannot install updates to system apps on sdcard");
12535            return;
12536        }
12537
12538        if (args.move != null) {
12539            // We did an in-place move, so dex is ready to roll
12540            scanFlags |= SCAN_NO_DEX;
12541            scanFlags |= SCAN_MOVE;
12542
12543            synchronized (mPackages) {
12544                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12545                if (ps == null) {
12546                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12547                            "Missing settings for moved package " + pkgName);
12548                }
12549
12550                // We moved the entire application as-is, so bring over the
12551                // previously derived ABI information.
12552                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12553                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12554            }
12555
12556        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12557            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12558            scanFlags |= SCAN_NO_DEX;
12559
12560            try {
12561                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12562                        true /* extract libs */);
12563            } catch (PackageManagerException pme) {
12564                Slog.e(TAG, "Error deriving application ABI", pme);
12565                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12566                return;
12567            }
12568
12569            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12570            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
12571
12572            int result = mPackageDexOptimizer
12573                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12574                            false /* defer */, false /* inclDependencies */,
12575                            true /* boot complete */);
12576
12577            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12578            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12579                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12580                return;
12581            }
12582        }
12583
12584        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12585            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12586            return;
12587        }
12588
12589        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12590
12591        if (replace) {
12592            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12593                    installerPackageName, volumeUuid, res);
12594        } else {
12595            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12596                    args.user, installerPackageName, volumeUuid, res);
12597        }
12598        synchronized (mPackages) {
12599            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12600            if (ps != null) {
12601                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12602            }
12603        }
12604    }
12605
12606    private void startIntentFilterVerifications(int userId, boolean replacing,
12607            PackageParser.Package pkg) {
12608        if (mIntentFilterVerifierComponent == null) {
12609            Slog.w(TAG, "No IntentFilter verification will not be done as "
12610                    + "there is no IntentFilterVerifier available!");
12611            return;
12612        }
12613
12614        final int verifierUid = getPackageUid(
12615                mIntentFilterVerifierComponent.getPackageName(),
12616                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12617
12618        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12619        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12620        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12621        mHandler.sendMessage(msg);
12622    }
12623
12624    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12625            PackageParser.Package pkg) {
12626        int size = pkg.activities.size();
12627        if (size == 0) {
12628            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12629                    "No activity, so no need to verify any IntentFilter!");
12630            return;
12631        }
12632
12633        final boolean hasDomainURLs = hasDomainURLs(pkg);
12634        if (!hasDomainURLs) {
12635            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12636                    "No domain URLs, so no need to verify any IntentFilter!");
12637            return;
12638        }
12639
12640        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12641                + " if any IntentFilter from the " + size
12642                + " Activities needs verification ...");
12643
12644        int count = 0;
12645        final String packageName = pkg.packageName;
12646
12647        synchronized (mPackages) {
12648            // If this is a new install and we see that we've already run verification for this
12649            // package, we have nothing to do: it means the state was restored from backup.
12650            if (!replacing) {
12651                IntentFilterVerificationInfo ivi =
12652                        mSettings.getIntentFilterVerificationLPr(packageName);
12653                if (ivi != null) {
12654                    if (DEBUG_DOMAIN_VERIFICATION) {
12655                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12656                                + ivi.getStatusString());
12657                    }
12658                    return;
12659                }
12660            }
12661
12662            // If any filters need to be verified, then all need to be.
12663            boolean needToVerify = false;
12664            for (PackageParser.Activity a : pkg.activities) {
12665                for (ActivityIntentInfo filter : a.intents) {
12666                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12667                        if (DEBUG_DOMAIN_VERIFICATION) {
12668                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12669                        }
12670                        needToVerify = true;
12671                        break;
12672                    }
12673                }
12674            }
12675
12676            if (needToVerify) {
12677                final int verificationId = mIntentFilterVerificationToken++;
12678                for (PackageParser.Activity a : pkg.activities) {
12679                    for (ActivityIntentInfo filter : a.intents) {
12680                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12681                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12682                                    "Verification needed for IntentFilter:" + filter.toString());
12683                            mIntentFilterVerifier.addOneIntentFilterVerification(
12684                                    verifierUid, userId, verificationId, filter, packageName);
12685                            count++;
12686                        }
12687                    }
12688                }
12689            }
12690        }
12691
12692        if (count > 0) {
12693            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12694                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12695                    +  " for userId:" + userId);
12696            mIntentFilterVerifier.startVerifications(userId);
12697        } else {
12698            if (DEBUG_DOMAIN_VERIFICATION) {
12699                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12700            }
12701        }
12702    }
12703
12704    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12705        final ComponentName cn  = filter.activity.getComponentName();
12706        final String packageName = cn.getPackageName();
12707
12708        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12709                packageName);
12710        if (ivi == null) {
12711            return true;
12712        }
12713        int status = ivi.getStatus();
12714        switch (status) {
12715            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12716            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12717                return true;
12718
12719            default:
12720                // Nothing to do
12721                return false;
12722        }
12723    }
12724
12725    private static boolean isMultiArch(PackageSetting ps) {
12726        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12727    }
12728
12729    private static boolean isMultiArch(ApplicationInfo info) {
12730        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12731    }
12732
12733    private static boolean isExternal(PackageParser.Package pkg) {
12734        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12735    }
12736
12737    private static boolean isExternal(PackageSetting ps) {
12738        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12739    }
12740
12741    private static boolean isExternal(ApplicationInfo info) {
12742        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12743    }
12744
12745    private static boolean isSystemApp(PackageParser.Package pkg) {
12746        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12747    }
12748
12749    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12750        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12751    }
12752
12753    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12754        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12755    }
12756
12757    private static boolean isSystemApp(PackageSetting ps) {
12758        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12759    }
12760
12761    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12762        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12763    }
12764
12765    private int packageFlagsToInstallFlags(PackageSetting ps) {
12766        int installFlags = 0;
12767        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12768            // This existing package was an external ASEC install when we have
12769            // the external flag without a UUID
12770            installFlags |= PackageManager.INSTALL_EXTERNAL;
12771        }
12772        if (ps.isForwardLocked()) {
12773            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12774        }
12775        return installFlags;
12776    }
12777
12778    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12779        if (isExternal(pkg)) {
12780            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12781                return mSettings.getExternalVersion();
12782            } else {
12783                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12784            }
12785        } else {
12786            return mSettings.getInternalVersion();
12787        }
12788    }
12789
12790    private void deleteTempPackageFiles() {
12791        final FilenameFilter filter = new FilenameFilter() {
12792            public boolean accept(File dir, String name) {
12793                return name.startsWith("vmdl") && name.endsWith(".tmp");
12794            }
12795        };
12796        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12797            file.delete();
12798        }
12799    }
12800
12801    @Override
12802    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12803            int flags) {
12804        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12805                flags);
12806    }
12807
12808    @Override
12809    public void deletePackage(final String packageName,
12810            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12811        mContext.enforceCallingOrSelfPermission(
12812                android.Manifest.permission.DELETE_PACKAGES, null);
12813        Preconditions.checkNotNull(packageName);
12814        Preconditions.checkNotNull(observer);
12815        final int uid = Binder.getCallingUid();
12816        if (UserHandle.getUserId(uid) != userId) {
12817            mContext.enforceCallingPermission(
12818                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12819                    "deletePackage for user " + userId);
12820        }
12821        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12822            try {
12823                observer.onPackageDeleted(packageName,
12824                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12825            } catch (RemoteException re) {
12826            }
12827            return;
12828        }
12829
12830        boolean uninstallBlocked = false;
12831        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12832            int[] users = sUserManager.getUserIds();
12833            for (int i = 0; i < users.length; ++i) {
12834                if (getBlockUninstallForUser(packageName, users[i])) {
12835                    uninstallBlocked = true;
12836                    break;
12837                }
12838            }
12839        } else {
12840            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12841        }
12842        if (uninstallBlocked) {
12843            try {
12844                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12845                        null);
12846            } catch (RemoteException re) {
12847            }
12848            return;
12849        }
12850
12851        if (DEBUG_REMOVE) {
12852            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12853        }
12854        // Queue up an async operation since the package deletion may take a little while.
12855        mHandler.post(new Runnable() {
12856            public void run() {
12857                mHandler.removeCallbacks(this);
12858                final int returnCode = deletePackageX(packageName, userId, flags);
12859                if (observer != null) {
12860                    try {
12861                        observer.onPackageDeleted(packageName, returnCode, null);
12862                    } catch (RemoteException e) {
12863                        Log.i(TAG, "Observer no longer exists.");
12864                    } //end catch
12865                } //end if
12866            } //end run
12867        });
12868    }
12869
12870    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12871        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12872                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12873        try {
12874            if (dpm != null) {
12875                if (dpm.isDeviceOwner(packageName)) {
12876                    return true;
12877                }
12878                int[] users;
12879                if (userId == UserHandle.USER_ALL) {
12880                    users = sUserManager.getUserIds();
12881                } else {
12882                    users = new int[]{userId};
12883                }
12884                for (int i = 0; i < users.length; ++i) {
12885                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12886                        return true;
12887                    }
12888                }
12889            }
12890        } catch (RemoteException e) {
12891        }
12892        return false;
12893    }
12894
12895    /**
12896     *  This method is an internal method that could be get invoked either
12897     *  to delete an installed package or to clean up a failed installation.
12898     *  After deleting an installed package, a broadcast is sent to notify any
12899     *  listeners that the package has been installed. For cleaning up a failed
12900     *  installation, the broadcast is not necessary since the package's
12901     *  installation wouldn't have sent the initial broadcast either
12902     *  The key steps in deleting a package are
12903     *  deleting the package information in internal structures like mPackages,
12904     *  deleting the packages base directories through installd
12905     *  updating mSettings to reflect current status
12906     *  persisting settings for later use
12907     *  sending a broadcast if necessary
12908     */
12909    private int deletePackageX(String packageName, int userId, int flags) {
12910        final PackageRemovedInfo info = new PackageRemovedInfo();
12911        final boolean res;
12912
12913        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12914                ? UserHandle.ALL : new UserHandle(userId);
12915
12916        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12917            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12918            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12919        }
12920
12921        boolean removedForAllUsers = false;
12922        boolean systemUpdate = false;
12923
12924        // for the uninstall-updates case and restricted profiles, remember the per-
12925        // userhandle installed state
12926        int[] allUsers;
12927        boolean[] perUserInstalled;
12928        synchronized (mPackages) {
12929            PackageSetting ps = mSettings.mPackages.get(packageName);
12930            allUsers = sUserManager.getUserIds();
12931            perUserInstalled = new boolean[allUsers.length];
12932            for (int i = 0; i < allUsers.length; i++) {
12933                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12934            }
12935        }
12936
12937        synchronized (mInstallLock) {
12938            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12939            res = deletePackageLI(packageName, removeForUser,
12940                    true, allUsers, perUserInstalled,
12941                    flags | REMOVE_CHATTY, info, true);
12942            systemUpdate = info.isRemovedPackageSystemUpdate;
12943            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12944                removedForAllUsers = true;
12945            }
12946            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12947                    + " removedForAllUsers=" + removedForAllUsers);
12948        }
12949
12950        if (res) {
12951            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12952
12953            // If the removed package was a system update, the old system package
12954            // was re-enabled; we need to broadcast this information
12955            if (systemUpdate) {
12956                Bundle extras = new Bundle(1);
12957                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12958                        ? info.removedAppId : info.uid);
12959                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12960
12961                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12962                        extras, null, null, null);
12963                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12964                        extras, null, null, null);
12965                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12966                        null, packageName, null, null);
12967            }
12968        }
12969        // Force a gc here.
12970        Runtime.getRuntime().gc();
12971        // Delete the resources here after sending the broadcast to let
12972        // other processes clean up before deleting resources.
12973        if (info.args != null) {
12974            synchronized (mInstallLock) {
12975                info.args.doPostDeleteLI(true);
12976            }
12977        }
12978
12979        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12980    }
12981
12982    class PackageRemovedInfo {
12983        String removedPackage;
12984        int uid = -1;
12985        int removedAppId = -1;
12986        int[] removedUsers = null;
12987        boolean isRemovedPackageSystemUpdate = false;
12988        // Clean up resources deleted packages.
12989        InstallArgs args = null;
12990
12991        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12992            Bundle extras = new Bundle(1);
12993            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12994            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12995            if (replacing) {
12996                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12997            }
12998            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12999            if (removedPackage != null) {
13000                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13001                        extras, null, null, removedUsers);
13002                if (fullRemove && !replacing) {
13003                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13004                            extras, null, null, removedUsers);
13005                }
13006            }
13007            if (removedAppId >= 0) {
13008                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
13009                        removedUsers);
13010            }
13011        }
13012    }
13013
13014    /*
13015     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13016     * flag is not set, the data directory is removed as well.
13017     * make sure this flag is set for partially installed apps. If not its meaningless to
13018     * delete a partially installed application.
13019     */
13020    private void removePackageDataLI(PackageSetting ps,
13021            int[] allUserHandles, boolean[] perUserInstalled,
13022            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13023        String packageName = ps.name;
13024        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13025        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13026        // Retrieve object to delete permissions for shared user later on
13027        final PackageSetting deletedPs;
13028        // reader
13029        synchronized (mPackages) {
13030            deletedPs = mSettings.mPackages.get(packageName);
13031            if (outInfo != null) {
13032                outInfo.removedPackage = packageName;
13033                outInfo.removedUsers = deletedPs != null
13034                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13035                        : null;
13036            }
13037        }
13038        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13039            removeDataDirsLI(ps.volumeUuid, packageName);
13040            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13041        }
13042        // writer
13043        synchronized (mPackages) {
13044            if (deletedPs != null) {
13045                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13046                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13047                    clearDefaultBrowserIfNeeded(packageName);
13048                    if (outInfo != null) {
13049                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13050                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13051                    }
13052                    updatePermissionsLPw(deletedPs.name, null, 0);
13053                    if (deletedPs.sharedUser != null) {
13054                        // Remove permissions associated with package. Since runtime
13055                        // permissions are per user we have to kill the removed package
13056                        // or packages running under the shared user of the removed
13057                        // package if revoking the permissions requested only by the removed
13058                        // package is successful and this causes a change in gids.
13059                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13060                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13061                                    userId);
13062                            if (userIdToKill == UserHandle.USER_ALL
13063                                    || userIdToKill >= UserHandle.USER_OWNER) {
13064                                // If gids changed for this user, kill all affected packages.
13065                                mHandler.post(new Runnable() {
13066                                    @Override
13067                                    public void run() {
13068                                        // This has to happen with no lock held.
13069                                        killApplication(deletedPs.name, deletedPs.appId,
13070                                                KILL_APP_REASON_GIDS_CHANGED);
13071                                    }
13072                                });
13073                                break;
13074                            }
13075                        }
13076                    }
13077                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13078                }
13079                // make sure to preserve per-user disabled state if this removal was just
13080                // a downgrade of a system app to the factory package
13081                if (allUserHandles != null && perUserInstalled != null) {
13082                    if (DEBUG_REMOVE) {
13083                        Slog.d(TAG, "Propagating install state across downgrade");
13084                    }
13085                    for (int i = 0; i < allUserHandles.length; i++) {
13086                        if (DEBUG_REMOVE) {
13087                            Slog.d(TAG, "    user " + allUserHandles[i]
13088                                    + " => " + perUserInstalled[i]);
13089                        }
13090                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13091                    }
13092                }
13093            }
13094            // can downgrade to reader
13095            if (writeSettings) {
13096                // Save settings now
13097                mSettings.writeLPr();
13098            }
13099        }
13100        if (outInfo != null) {
13101            // A user ID was deleted here. Go through all users and remove it
13102            // from KeyStore.
13103            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13104        }
13105    }
13106
13107    static boolean locationIsPrivileged(File path) {
13108        try {
13109            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13110                    .getCanonicalPath();
13111            return path.getCanonicalPath().startsWith(privilegedAppDir);
13112        } catch (IOException e) {
13113            Slog.e(TAG, "Unable to access code path " + path);
13114        }
13115        return false;
13116    }
13117
13118    /*
13119     * Tries to delete system package.
13120     */
13121    private boolean deleteSystemPackageLI(PackageSetting newPs,
13122            int[] allUserHandles, boolean[] perUserInstalled,
13123            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13124        final boolean applyUserRestrictions
13125                = (allUserHandles != null) && (perUserInstalled != null);
13126        PackageSetting disabledPs = null;
13127        // Confirm if the system package has been updated
13128        // An updated system app can be deleted. This will also have to restore
13129        // the system pkg from system partition
13130        // reader
13131        synchronized (mPackages) {
13132            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13133        }
13134        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13135                + " disabledPs=" + disabledPs);
13136        if (disabledPs == null) {
13137            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13138            return false;
13139        } else if (DEBUG_REMOVE) {
13140            Slog.d(TAG, "Deleting system pkg from data partition");
13141        }
13142        if (DEBUG_REMOVE) {
13143            if (applyUserRestrictions) {
13144                Slog.d(TAG, "Remembering install states:");
13145                for (int i = 0; i < allUserHandles.length; i++) {
13146                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13147                }
13148            }
13149        }
13150        // Delete the updated package
13151        outInfo.isRemovedPackageSystemUpdate = true;
13152        if (disabledPs.versionCode < newPs.versionCode) {
13153            // Delete data for downgrades
13154            flags &= ~PackageManager.DELETE_KEEP_DATA;
13155        } else {
13156            // Preserve data by setting flag
13157            flags |= PackageManager.DELETE_KEEP_DATA;
13158        }
13159        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13160                allUserHandles, perUserInstalled, outInfo, writeSettings);
13161        if (!ret) {
13162            return false;
13163        }
13164        // writer
13165        synchronized (mPackages) {
13166            // Reinstate the old system package
13167            mSettings.enableSystemPackageLPw(newPs.name);
13168            // Remove any native libraries from the upgraded package.
13169            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13170        }
13171        // Install the system package
13172        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13173        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13174        if (locationIsPrivileged(disabledPs.codePath)) {
13175            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13176        }
13177
13178        final PackageParser.Package newPkg;
13179        try {
13180            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13181        } catch (PackageManagerException e) {
13182            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13183            return false;
13184        }
13185
13186        // writer
13187        synchronized (mPackages) {
13188            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13189
13190            // Propagate the permissions state as we do not want to drop on the floor
13191            // runtime permissions. The update permissions method below will take
13192            // care of removing obsolete permissions and grant install permissions.
13193            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13194            updatePermissionsLPw(newPkg.packageName, newPkg,
13195                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13196
13197            if (applyUserRestrictions) {
13198                if (DEBUG_REMOVE) {
13199                    Slog.d(TAG, "Propagating install state across reinstall");
13200                }
13201                for (int i = 0; i < allUserHandles.length; i++) {
13202                    if (DEBUG_REMOVE) {
13203                        Slog.d(TAG, "    user " + allUserHandles[i]
13204                                + " => " + perUserInstalled[i]);
13205                    }
13206                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13207
13208                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13209                }
13210                // Regardless of writeSettings we need to ensure that this restriction
13211                // state propagation is persisted
13212                mSettings.writeAllUsersPackageRestrictionsLPr();
13213            }
13214            // can downgrade to reader here
13215            if (writeSettings) {
13216                mSettings.writeLPr();
13217            }
13218        }
13219        return true;
13220    }
13221
13222    private boolean deleteInstalledPackageLI(PackageSetting ps,
13223            boolean deleteCodeAndResources, int flags,
13224            int[] allUserHandles, boolean[] perUserInstalled,
13225            PackageRemovedInfo outInfo, boolean writeSettings) {
13226        if (outInfo != null) {
13227            outInfo.uid = ps.appId;
13228        }
13229
13230        // Delete package data from internal structures and also remove data if flag is set
13231        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13232
13233        // Delete application code and resources
13234        if (deleteCodeAndResources && (outInfo != null)) {
13235            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13236                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13237            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13238        }
13239        return true;
13240    }
13241
13242    @Override
13243    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13244            int userId) {
13245        mContext.enforceCallingOrSelfPermission(
13246                android.Manifest.permission.DELETE_PACKAGES, null);
13247        synchronized (mPackages) {
13248            PackageSetting ps = mSettings.mPackages.get(packageName);
13249            if (ps == null) {
13250                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13251                return false;
13252            }
13253            if (!ps.getInstalled(userId)) {
13254                // Can't block uninstall for an app that is not installed or enabled.
13255                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13256                return false;
13257            }
13258            ps.setBlockUninstall(blockUninstall, userId);
13259            mSettings.writePackageRestrictionsLPr(userId);
13260        }
13261        return true;
13262    }
13263
13264    @Override
13265    public boolean getBlockUninstallForUser(String packageName, int userId) {
13266        synchronized (mPackages) {
13267            PackageSetting ps = mSettings.mPackages.get(packageName);
13268            if (ps == null) {
13269                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13270                return false;
13271            }
13272            return ps.getBlockUninstall(userId);
13273        }
13274    }
13275
13276    /*
13277     * This method handles package deletion in general
13278     */
13279    private boolean deletePackageLI(String packageName, UserHandle user,
13280            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13281            int flags, PackageRemovedInfo outInfo,
13282            boolean writeSettings) {
13283        if (packageName == null) {
13284            Slog.w(TAG, "Attempt to delete null packageName.");
13285            return false;
13286        }
13287        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13288        PackageSetting ps;
13289        boolean dataOnly = false;
13290        int removeUser = -1;
13291        int appId = -1;
13292        synchronized (mPackages) {
13293            ps = mSettings.mPackages.get(packageName);
13294            if (ps == null) {
13295                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13296                return false;
13297            }
13298            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13299                    && user.getIdentifier() != UserHandle.USER_ALL) {
13300                // The caller is asking that the package only be deleted for a single
13301                // user.  To do this, we just mark its uninstalled state and delete
13302                // its data.  If this is a system app, we only allow this to happen if
13303                // they have set the special DELETE_SYSTEM_APP which requests different
13304                // semantics than normal for uninstalling system apps.
13305                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13306                final int userId = user.getIdentifier();
13307                ps.setUserState(userId,
13308                        COMPONENT_ENABLED_STATE_DEFAULT,
13309                        false, //installed
13310                        true,  //stopped
13311                        true,  //notLaunched
13312                        false, //hidden
13313                        null, null, null,
13314                        false, // blockUninstall
13315                        ps.readUserState(userId).domainVerificationStatus, 0);
13316                if (!isSystemApp(ps)) {
13317                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13318                        // Other user still have this package installed, so all
13319                        // we need to do is clear this user's data and save that
13320                        // it is uninstalled.
13321                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13322                        removeUser = user.getIdentifier();
13323                        appId = ps.appId;
13324                        scheduleWritePackageRestrictionsLocked(removeUser);
13325                    } else {
13326                        // We need to set it back to 'installed' so the uninstall
13327                        // broadcasts will be sent correctly.
13328                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13329                        ps.setInstalled(true, user.getIdentifier());
13330                    }
13331                } else {
13332                    // This is a system app, so we assume that the
13333                    // other users still have this package installed, so all
13334                    // we need to do is clear this user's data and save that
13335                    // it is uninstalled.
13336                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13337                    removeUser = user.getIdentifier();
13338                    appId = ps.appId;
13339                    scheduleWritePackageRestrictionsLocked(removeUser);
13340                }
13341            }
13342        }
13343
13344        if (removeUser >= 0) {
13345            // From above, we determined that we are deleting this only
13346            // for a single user.  Continue the work here.
13347            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13348            if (outInfo != null) {
13349                outInfo.removedPackage = packageName;
13350                outInfo.removedAppId = appId;
13351                outInfo.removedUsers = new int[] {removeUser};
13352            }
13353            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13354            removeKeystoreDataIfNeeded(removeUser, appId);
13355            schedulePackageCleaning(packageName, removeUser, false);
13356            synchronized (mPackages) {
13357                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13358                    scheduleWritePackageRestrictionsLocked(removeUser);
13359                }
13360                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13361            }
13362            return true;
13363        }
13364
13365        if (dataOnly) {
13366            // Delete application data first
13367            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13368            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13369            return true;
13370        }
13371
13372        boolean ret = false;
13373        if (isSystemApp(ps)) {
13374            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13375            // When an updated system application is deleted we delete the existing resources as well and
13376            // fall back to existing code in system partition
13377            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13378                    flags, outInfo, writeSettings);
13379        } else {
13380            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13381            // Kill application pre-emptively especially for apps on sd.
13382            killApplication(packageName, ps.appId, "uninstall pkg");
13383            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13384                    allUserHandles, perUserInstalled,
13385                    outInfo, writeSettings);
13386        }
13387
13388        return ret;
13389    }
13390
13391    private final class ClearStorageConnection implements ServiceConnection {
13392        IMediaContainerService mContainerService;
13393
13394        @Override
13395        public void onServiceConnected(ComponentName name, IBinder service) {
13396            synchronized (this) {
13397                mContainerService = IMediaContainerService.Stub.asInterface(service);
13398                notifyAll();
13399            }
13400        }
13401
13402        @Override
13403        public void onServiceDisconnected(ComponentName name) {
13404        }
13405    }
13406
13407    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13408        final boolean mounted;
13409        if (Environment.isExternalStorageEmulated()) {
13410            mounted = true;
13411        } else {
13412            final String status = Environment.getExternalStorageState();
13413
13414            mounted = status.equals(Environment.MEDIA_MOUNTED)
13415                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13416        }
13417
13418        if (!mounted) {
13419            return;
13420        }
13421
13422        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13423        int[] users;
13424        if (userId == UserHandle.USER_ALL) {
13425            users = sUserManager.getUserIds();
13426        } else {
13427            users = new int[] { userId };
13428        }
13429        final ClearStorageConnection conn = new ClearStorageConnection();
13430        if (mContext.bindServiceAsUser(
13431                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13432            try {
13433                for (int curUser : users) {
13434                    long timeout = SystemClock.uptimeMillis() + 5000;
13435                    synchronized (conn) {
13436                        long now = SystemClock.uptimeMillis();
13437                        while (conn.mContainerService == null && now < timeout) {
13438                            try {
13439                                conn.wait(timeout - now);
13440                            } catch (InterruptedException e) {
13441                            }
13442                        }
13443                    }
13444                    if (conn.mContainerService == null) {
13445                        return;
13446                    }
13447
13448                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13449                    clearDirectory(conn.mContainerService,
13450                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13451                    if (allData) {
13452                        clearDirectory(conn.mContainerService,
13453                                userEnv.buildExternalStorageAppDataDirs(packageName));
13454                        clearDirectory(conn.mContainerService,
13455                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13456                    }
13457                }
13458            } finally {
13459                mContext.unbindService(conn);
13460            }
13461        }
13462    }
13463
13464    @Override
13465    public void clearApplicationUserData(final String packageName,
13466            final IPackageDataObserver observer, final int userId) {
13467        mContext.enforceCallingOrSelfPermission(
13468                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13469        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13470        // Queue up an async operation since the package deletion may take a little while.
13471        mHandler.post(new Runnable() {
13472            public void run() {
13473                mHandler.removeCallbacks(this);
13474                final boolean succeeded;
13475                synchronized (mInstallLock) {
13476                    succeeded = clearApplicationUserDataLI(packageName, userId);
13477                }
13478                clearExternalStorageDataSync(packageName, userId, true);
13479                if (succeeded) {
13480                    // invoke DeviceStorageMonitor's update method to clear any notifications
13481                    DeviceStorageMonitorInternal
13482                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13483                    if (dsm != null) {
13484                        dsm.checkMemory();
13485                    }
13486                }
13487                if(observer != null) {
13488                    try {
13489                        observer.onRemoveCompleted(packageName, succeeded);
13490                    } catch (RemoteException e) {
13491                        Log.i(TAG, "Observer no longer exists.");
13492                    }
13493                } //end if observer
13494            } //end run
13495        });
13496    }
13497
13498    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13499        if (packageName == null) {
13500            Slog.w(TAG, "Attempt to delete null packageName.");
13501            return false;
13502        }
13503
13504        // Try finding details about the requested package
13505        PackageParser.Package pkg;
13506        synchronized (mPackages) {
13507            pkg = mPackages.get(packageName);
13508            if (pkg == null) {
13509                final PackageSetting ps = mSettings.mPackages.get(packageName);
13510                if (ps != null) {
13511                    pkg = ps.pkg;
13512                }
13513            }
13514
13515            if (pkg == null) {
13516                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13517                return false;
13518            }
13519
13520            PackageSetting ps = (PackageSetting) pkg.mExtras;
13521            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13522        }
13523
13524        // Always delete data directories for package, even if we found no other
13525        // record of app. This helps users recover from UID mismatches without
13526        // resorting to a full data wipe.
13527        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13528        if (retCode < 0) {
13529            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13530            return false;
13531        }
13532
13533        final int appId = pkg.applicationInfo.uid;
13534        removeKeystoreDataIfNeeded(userId, appId);
13535
13536        // Create a native library symlink only if we have native libraries
13537        // and if the native libraries are 32 bit libraries. We do not provide
13538        // this symlink for 64 bit libraries.
13539        if (pkg.applicationInfo.primaryCpuAbi != null &&
13540                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13541            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13542            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13543                    nativeLibPath, userId) < 0) {
13544                Slog.w(TAG, "Failed linking native library dir");
13545                return false;
13546            }
13547        }
13548
13549        return true;
13550    }
13551
13552    /**
13553     * Reverts user permission state changes (permissions and flags) in
13554     * all packages for a given user.
13555     *
13556     * @param userId The device user for which to do a reset.
13557     */
13558    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13559        final int packageCount = mPackages.size();
13560        for (int i = 0; i < packageCount; i++) {
13561            PackageParser.Package pkg = mPackages.valueAt(i);
13562            PackageSetting ps = (PackageSetting) pkg.mExtras;
13563            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13564        }
13565    }
13566
13567    /**
13568     * Reverts user permission state changes (permissions and flags).
13569     *
13570     * @param ps The package for which to reset.
13571     * @param userId The device user for which to do a reset.
13572     */
13573    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13574            final PackageSetting ps, final int userId) {
13575        if (ps.pkg == null) {
13576            return;
13577        }
13578
13579        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13580                | FLAG_PERMISSION_USER_FIXED
13581                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13582
13583        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13584                | FLAG_PERMISSION_POLICY_FIXED;
13585
13586        boolean writeInstallPermissions = false;
13587        boolean writeRuntimePermissions = false;
13588
13589        final int permissionCount = ps.pkg.requestedPermissions.size();
13590        for (int i = 0; i < permissionCount; i++) {
13591            String permission = ps.pkg.requestedPermissions.get(i);
13592
13593            BasePermission bp = mSettings.mPermissions.get(permission);
13594            if (bp == null) {
13595                continue;
13596            }
13597
13598            // If shared user we just reset the state to which only this app contributed.
13599            if (ps.sharedUser != null) {
13600                boolean used = false;
13601                final int packageCount = ps.sharedUser.packages.size();
13602                for (int j = 0; j < packageCount; j++) {
13603                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13604                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13605                            && pkg.pkg.requestedPermissions.contains(permission)) {
13606                        used = true;
13607                        break;
13608                    }
13609                }
13610                if (used) {
13611                    continue;
13612                }
13613            }
13614
13615            PermissionsState permissionsState = ps.getPermissionsState();
13616
13617            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13618
13619            // Always clear the user settable flags.
13620            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13621                    bp.name) != null;
13622            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13623                if (hasInstallState) {
13624                    writeInstallPermissions = true;
13625                } else {
13626                    writeRuntimePermissions = true;
13627                }
13628            }
13629
13630            // Below is only runtime permission handling.
13631            if (!bp.isRuntime()) {
13632                continue;
13633            }
13634
13635            // Never clobber system or policy.
13636            if ((oldFlags & policyOrSystemFlags) != 0) {
13637                continue;
13638            }
13639
13640            // If this permission was granted by default, make sure it is.
13641            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13642                if (permissionsState.grantRuntimePermission(bp, userId)
13643                        != PERMISSION_OPERATION_FAILURE) {
13644                    writeRuntimePermissions = true;
13645                }
13646            } else {
13647                // Otherwise, reset the permission.
13648                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13649                switch (revokeResult) {
13650                    case PERMISSION_OPERATION_SUCCESS: {
13651                        writeRuntimePermissions = true;
13652                    } break;
13653
13654                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13655                        writeRuntimePermissions = true;
13656                        final int appId = ps.appId;
13657                        mHandler.post(new Runnable() {
13658                            @Override
13659                            public void run() {
13660                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13661                            }
13662                        });
13663                    } break;
13664                }
13665            }
13666        }
13667
13668        // Synchronously write as we are taking permissions away.
13669        if (writeRuntimePermissions) {
13670            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13671        }
13672
13673        // Synchronously write as we are taking permissions away.
13674        if (writeInstallPermissions) {
13675            mSettings.writeLPr();
13676        }
13677    }
13678
13679    /**
13680     * Remove entries from the keystore daemon. Will only remove it if the
13681     * {@code appId} is valid.
13682     */
13683    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13684        if (appId < 0) {
13685            return;
13686        }
13687
13688        final KeyStore keyStore = KeyStore.getInstance();
13689        if (keyStore != null) {
13690            if (userId == UserHandle.USER_ALL) {
13691                for (final int individual : sUserManager.getUserIds()) {
13692                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13693                }
13694            } else {
13695                keyStore.clearUid(UserHandle.getUid(userId, appId));
13696            }
13697        } else {
13698            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13699        }
13700    }
13701
13702    @Override
13703    public void deleteApplicationCacheFiles(final String packageName,
13704            final IPackageDataObserver observer) {
13705        mContext.enforceCallingOrSelfPermission(
13706                android.Manifest.permission.DELETE_CACHE_FILES, null);
13707        // Queue up an async operation since the package deletion may take a little while.
13708        final int userId = UserHandle.getCallingUserId();
13709        mHandler.post(new Runnable() {
13710            public void run() {
13711                mHandler.removeCallbacks(this);
13712                final boolean succeded;
13713                synchronized (mInstallLock) {
13714                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13715                }
13716                clearExternalStorageDataSync(packageName, userId, false);
13717                if (observer != null) {
13718                    try {
13719                        observer.onRemoveCompleted(packageName, succeded);
13720                    } catch (RemoteException e) {
13721                        Log.i(TAG, "Observer no longer exists.");
13722                    }
13723                } //end if observer
13724            } //end run
13725        });
13726    }
13727
13728    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13729        if (packageName == null) {
13730            Slog.w(TAG, "Attempt to delete null packageName.");
13731            return false;
13732        }
13733        PackageParser.Package p;
13734        synchronized (mPackages) {
13735            p = mPackages.get(packageName);
13736        }
13737        if (p == null) {
13738            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13739            return false;
13740        }
13741        final ApplicationInfo applicationInfo = p.applicationInfo;
13742        if (applicationInfo == null) {
13743            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13744            return false;
13745        }
13746        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13747        if (retCode < 0) {
13748            Slog.w(TAG, "Couldn't remove cache files for package: "
13749                       + packageName + " u" + userId);
13750            return false;
13751        }
13752        return true;
13753    }
13754
13755    @Override
13756    public void getPackageSizeInfo(final String packageName, int userHandle,
13757            final IPackageStatsObserver observer) {
13758        mContext.enforceCallingOrSelfPermission(
13759                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13760        if (packageName == null) {
13761            throw new IllegalArgumentException("Attempt to get size of null packageName");
13762        }
13763
13764        PackageStats stats = new PackageStats(packageName, userHandle);
13765
13766        /*
13767         * Queue up an async operation since the package measurement may take a
13768         * little while.
13769         */
13770        Message msg = mHandler.obtainMessage(INIT_COPY);
13771        msg.obj = new MeasureParams(stats, observer);
13772        mHandler.sendMessage(msg);
13773    }
13774
13775    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13776            PackageStats pStats) {
13777        if (packageName == null) {
13778            Slog.w(TAG, "Attempt to get size of null packageName.");
13779            return false;
13780        }
13781        PackageParser.Package p;
13782        boolean dataOnly = false;
13783        String libDirRoot = null;
13784        String asecPath = null;
13785        PackageSetting ps = null;
13786        synchronized (mPackages) {
13787            p = mPackages.get(packageName);
13788            ps = mSettings.mPackages.get(packageName);
13789            if(p == null) {
13790                dataOnly = true;
13791                if((ps == null) || (ps.pkg == null)) {
13792                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13793                    return false;
13794                }
13795                p = ps.pkg;
13796            }
13797            if (ps != null) {
13798                libDirRoot = ps.legacyNativeLibraryPathString;
13799            }
13800            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13801                final long token = Binder.clearCallingIdentity();
13802                try {
13803                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13804                    if (secureContainerId != null) {
13805                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13806                    }
13807                } finally {
13808                    Binder.restoreCallingIdentity(token);
13809                }
13810            }
13811        }
13812        String publicSrcDir = null;
13813        if(!dataOnly) {
13814            final ApplicationInfo applicationInfo = p.applicationInfo;
13815            if (applicationInfo == null) {
13816                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13817                return false;
13818            }
13819            if (p.isForwardLocked()) {
13820                publicSrcDir = applicationInfo.getBaseResourcePath();
13821            }
13822        }
13823        // TODO: extend to measure size of split APKs
13824        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13825        // not just the first level.
13826        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13827        // just the primary.
13828        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13829
13830        String apkPath;
13831        File packageDir = new File(p.codePath);
13832
13833        if (packageDir.isDirectory() && p.canHaveOatDir()) {
13834            apkPath = packageDir.getAbsolutePath();
13835            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
13836            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
13837                libDirRoot = null;
13838            }
13839        } else {
13840            apkPath = p.baseCodePath;
13841        }
13842
13843        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
13844                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13845        if (res < 0) {
13846            return false;
13847        }
13848
13849        // Fix-up for forward-locked applications in ASEC containers.
13850        if (!isExternal(p)) {
13851            pStats.codeSize += pStats.externalCodeSize;
13852            pStats.externalCodeSize = 0L;
13853        }
13854
13855        return true;
13856    }
13857
13858
13859    @Override
13860    public void addPackageToPreferred(String packageName) {
13861        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13862    }
13863
13864    @Override
13865    public void removePackageFromPreferred(String packageName) {
13866        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13867    }
13868
13869    @Override
13870    public List<PackageInfo> getPreferredPackages(int flags) {
13871        return new ArrayList<PackageInfo>();
13872    }
13873
13874    private int getUidTargetSdkVersionLockedLPr(int uid) {
13875        Object obj = mSettings.getUserIdLPr(uid);
13876        if (obj instanceof SharedUserSetting) {
13877            final SharedUserSetting sus = (SharedUserSetting) obj;
13878            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13879            final Iterator<PackageSetting> it = sus.packages.iterator();
13880            while (it.hasNext()) {
13881                final PackageSetting ps = it.next();
13882                if (ps.pkg != null) {
13883                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13884                    if (v < vers) vers = v;
13885                }
13886            }
13887            return vers;
13888        } else if (obj instanceof PackageSetting) {
13889            final PackageSetting ps = (PackageSetting) obj;
13890            if (ps.pkg != null) {
13891                return ps.pkg.applicationInfo.targetSdkVersion;
13892            }
13893        }
13894        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13895    }
13896
13897    @Override
13898    public void addPreferredActivity(IntentFilter filter, int match,
13899            ComponentName[] set, ComponentName activity, int userId) {
13900        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13901                "Adding preferred");
13902    }
13903
13904    private void addPreferredActivityInternal(IntentFilter filter, int match,
13905            ComponentName[] set, ComponentName activity, boolean always, int userId,
13906            String opname) {
13907        // writer
13908        int callingUid = Binder.getCallingUid();
13909        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13910        if (filter.countActions() == 0) {
13911            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13912            return;
13913        }
13914        synchronized (mPackages) {
13915            if (mContext.checkCallingOrSelfPermission(
13916                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13917                    != PackageManager.PERMISSION_GRANTED) {
13918                if (getUidTargetSdkVersionLockedLPr(callingUid)
13919                        < Build.VERSION_CODES.FROYO) {
13920                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13921                            + callingUid);
13922                    return;
13923                }
13924                mContext.enforceCallingOrSelfPermission(
13925                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13926            }
13927
13928            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13929            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13930                    + userId + ":");
13931            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13932            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13933            scheduleWritePackageRestrictionsLocked(userId);
13934        }
13935    }
13936
13937    @Override
13938    public void replacePreferredActivity(IntentFilter filter, int match,
13939            ComponentName[] set, ComponentName activity, int userId) {
13940        if (filter.countActions() != 1) {
13941            throw new IllegalArgumentException(
13942                    "replacePreferredActivity expects filter to have only 1 action.");
13943        }
13944        if (filter.countDataAuthorities() != 0
13945                || filter.countDataPaths() != 0
13946                || filter.countDataSchemes() > 1
13947                || filter.countDataTypes() != 0) {
13948            throw new IllegalArgumentException(
13949                    "replacePreferredActivity expects filter to have no data authorities, " +
13950                    "paths, or types; and at most one scheme.");
13951        }
13952
13953        final int callingUid = Binder.getCallingUid();
13954        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13955        synchronized (mPackages) {
13956            if (mContext.checkCallingOrSelfPermission(
13957                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13958                    != PackageManager.PERMISSION_GRANTED) {
13959                if (getUidTargetSdkVersionLockedLPr(callingUid)
13960                        < Build.VERSION_CODES.FROYO) {
13961                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13962                            + Binder.getCallingUid());
13963                    return;
13964                }
13965                mContext.enforceCallingOrSelfPermission(
13966                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13967            }
13968
13969            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13970            if (pir != null) {
13971                // Get all of the existing entries that exactly match this filter.
13972                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13973                if (existing != null && existing.size() == 1) {
13974                    PreferredActivity cur = existing.get(0);
13975                    if (DEBUG_PREFERRED) {
13976                        Slog.i(TAG, "Checking replace of preferred:");
13977                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13978                        if (!cur.mPref.mAlways) {
13979                            Slog.i(TAG, "  -- CUR; not mAlways!");
13980                        } else {
13981                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13982                            Slog.i(TAG, "  -- CUR: mSet="
13983                                    + Arrays.toString(cur.mPref.mSetComponents));
13984                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13985                            Slog.i(TAG, "  -- NEW: mMatch="
13986                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13987                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13988                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13989                        }
13990                    }
13991                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13992                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13993                            && cur.mPref.sameSet(set)) {
13994                        // Setting the preferred activity to what it happens to be already
13995                        if (DEBUG_PREFERRED) {
13996                            Slog.i(TAG, "Replacing with same preferred activity "
13997                                    + cur.mPref.mShortComponent + " for user "
13998                                    + userId + ":");
13999                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14000                        }
14001                        return;
14002                    }
14003                }
14004
14005                if (existing != null) {
14006                    if (DEBUG_PREFERRED) {
14007                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14008                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14009                    }
14010                    for (int i = 0; i < existing.size(); i++) {
14011                        PreferredActivity pa = existing.get(i);
14012                        if (DEBUG_PREFERRED) {
14013                            Slog.i(TAG, "Removing existing preferred activity "
14014                                    + pa.mPref.mComponent + ":");
14015                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14016                        }
14017                        pir.removeFilter(pa);
14018                    }
14019                }
14020            }
14021            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14022                    "Replacing preferred");
14023        }
14024    }
14025
14026    @Override
14027    public void clearPackagePreferredActivities(String packageName) {
14028        final int uid = Binder.getCallingUid();
14029        // writer
14030        synchronized (mPackages) {
14031            PackageParser.Package pkg = mPackages.get(packageName);
14032            if (pkg == null || pkg.applicationInfo.uid != uid) {
14033                if (mContext.checkCallingOrSelfPermission(
14034                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14035                        != PackageManager.PERMISSION_GRANTED) {
14036                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14037                            < Build.VERSION_CODES.FROYO) {
14038                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14039                                + Binder.getCallingUid());
14040                        return;
14041                    }
14042                    mContext.enforceCallingOrSelfPermission(
14043                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14044                }
14045            }
14046
14047            int user = UserHandle.getCallingUserId();
14048            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14049                scheduleWritePackageRestrictionsLocked(user);
14050            }
14051        }
14052    }
14053
14054    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14055    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14056        ArrayList<PreferredActivity> removed = null;
14057        boolean changed = false;
14058        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14059            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14060            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14061            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14062                continue;
14063            }
14064            Iterator<PreferredActivity> it = pir.filterIterator();
14065            while (it.hasNext()) {
14066                PreferredActivity pa = it.next();
14067                // Mark entry for removal only if it matches the package name
14068                // and the entry is of type "always".
14069                if (packageName == null ||
14070                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14071                                && pa.mPref.mAlways)) {
14072                    if (removed == null) {
14073                        removed = new ArrayList<PreferredActivity>();
14074                    }
14075                    removed.add(pa);
14076                }
14077            }
14078            if (removed != null) {
14079                for (int j=0; j<removed.size(); j++) {
14080                    PreferredActivity pa = removed.get(j);
14081                    pir.removeFilter(pa);
14082                }
14083                changed = true;
14084            }
14085        }
14086        return changed;
14087    }
14088
14089    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14090    private void clearIntentFilterVerificationsLPw(int userId) {
14091        final int packageCount = mPackages.size();
14092        for (int i = 0; i < packageCount; i++) {
14093            PackageParser.Package pkg = mPackages.valueAt(i);
14094            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14095        }
14096    }
14097
14098    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14099    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14100        if (userId == UserHandle.USER_ALL) {
14101            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14102                    sUserManager.getUserIds())) {
14103                for (int oneUserId : sUserManager.getUserIds()) {
14104                    scheduleWritePackageRestrictionsLocked(oneUserId);
14105                }
14106            }
14107        } else {
14108            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14109                scheduleWritePackageRestrictionsLocked(userId);
14110            }
14111        }
14112    }
14113
14114    void clearDefaultBrowserIfNeeded(String packageName) {
14115        for (int oneUserId : sUserManager.getUserIds()) {
14116            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14117            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14118            if (packageName.equals(defaultBrowserPackageName)) {
14119                setDefaultBrowserPackageName(null, oneUserId);
14120            }
14121        }
14122    }
14123
14124    @Override
14125    public void resetApplicationPreferences(int userId) {
14126        mContext.enforceCallingOrSelfPermission(
14127                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14128        // writer
14129        synchronized (mPackages) {
14130            final long identity = Binder.clearCallingIdentity();
14131            try {
14132                clearPackagePreferredActivitiesLPw(null, userId);
14133                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14134                // TODO: We have to reset the default SMS and Phone. This requires
14135                // significant refactoring to keep all default apps in the package
14136                // manager (cleaner but more work) or have the services provide
14137                // callbacks to the package manager to request a default app reset.
14138                applyFactoryDefaultBrowserLPw(userId);
14139                clearIntentFilterVerificationsLPw(userId);
14140                primeDomainVerificationsLPw(userId);
14141                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14142                scheduleWritePackageRestrictionsLocked(userId);
14143            } finally {
14144                Binder.restoreCallingIdentity(identity);
14145            }
14146        }
14147    }
14148
14149    @Override
14150    public int getPreferredActivities(List<IntentFilter> outFilters,
14151            List<ComponentName> outActivities, String packageName) {
14152
14153        int num = 0;
14154        final int userId = UserHandle.getCallingUserId();
14155        // reader
14156        synchronized (mPackages) {
14157            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14158            if (pir != null) {
14159                final Iterator<PreferredActivity> it = pir.filterIterator();
14160                while (it.hasNext()) {
14161                    final PreferredActivity pa = it.next();
14162                    if (packageName == null
14163                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14164                                    && pa.mPref.mAlways)) {
14165                        if (outFilters != null) {
14166                            outFilters.add(new IntentFilter(pa));
14167                        }
14168                        if (outActivities != null) {
14169                            outActivities.add(pa.mPref.mComponent);
14170                        }
14171                    }
14172                }
14173            }
14174        }
14175
14176        return num;
14177    }
14178
14179    @Override
14180    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14181            int userId) {
14182        int callingUid = Binder.getCallingUid();
14183        if (callingUid != Process.SYSTEM_UID) {
14184            throw new SecurityException(
14185                    "addPersistentPreferredActivity can only be run by the system");
14186        }
14187        if (filter.countActions() == 0) {
14188            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14189            return;
14190        }
14191        synchronized (mPackages) {
14192            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14193                    " :");
14194            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14195            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14196                    new PersistentPreferredActivity(filter, activity));
14197            scheduleWritePackageRestrictionsLocked(userId);
14198        }
14199    }
14200
14201    @Override
14202    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14203        int callingUid = Binder.getCallingUid();
14204        if (callingUid != Process.SYSTEM_UID) {
14205            throw new SecurityException(
14206                    "clearPackagePersistentPreferredActivities can only be run by the system");
14207        }
14208        ArrayList<PersistentPreferredActivity> removed = null;
14209        boolean changed = false;
14210        synchronized (mPackages) {
14211            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14212                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14213                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14214                        .valueAt(i);
14215                if (userId != thisUserId) {
14216                    continue;
14217                }
14218                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14219                while (it.hasNext()) {
14220                    PersistentPreferredActivity ppa = it.next();
14221                    // Mark entry for removal only if it matches the package name.
14222                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14223                        if (removed == null) {
14224                            removed = new ArrayList<PersistentPreferredActivity>();
14225                        }
14226                        removed.add(ppa);
14227                    }
14228                }
14229                if (removed != null) {
14230                    for (int j=0; j<removed.size(); j++) {
14231                        PersistentPreferredActivity ppa = removed.get(j);
14232                        ppir.removeFilter(ppa);
14233                    }
14234                    changed = true;
14235                }
14236            }
14237
14238            if (changed) {
14239                scheduleWritePackageRestrictionsLocked(userId);
14240            }
14241        }
14242    }
14243
14244    /**
14245     * Common machinery for picking apart a restored XML blob and passing
14246     * it to a caller-supplied functor to be applied to the running system.
14247     */
14248    private void restoreFromXml(XmlPullParser parser, int userId,
14249            String expectedStartTag, BlobXmlRestorer functor)
14250            throws IOException, XmlPullParserException {
14251        int type;
14252        while ((type = parser.next()) != XmlPullParser.START_TAG
14253                && type != XmlPullParser.END_DOCUMENT) {
14254        }
14255        if (type != XmlPullParser.START_TAG) {
14256            // oops didn't find a start tag?!
14257            if (DEBUG_BACKUP) {
14258                Slog.e(TAG, "Didn't find start tag during restore");
14259            }
14260            return;
14261        }
14262
14263        // this is supposed to be TAG_PREFERRED_BACKUP
14264        if (!expectedStartTag.equals(parser.getName())) {
14265            if (DEBUG_BACKUP) {
14266                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14267            }
14268            return;
14269        }
14270
14271        // skip interfering stuff, then we're aligned with the backing implementation
14272        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14273        functor.apply(parser, userId);
14274    }
14275
14276    private interface BlobXmlRestorer {
14277        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14278    }
14279
14280    /**
14281     * Non-Binder method, support for the backup/restore mechanism: write the
14282     * full set of preferred activities in its canonical XML format.  Returns the
14283     * XML output as a byte array, or null if there is none.
14284     */
14285    @Override
14286    public byte[] getPreferredActivityBackup(int userId) {
14287        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14288            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14289        }
14290
14291        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14292        try {
14293            final XmlSerializer serializer = new FastXmlSerializer();
14294            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14295            serializer.startDocument(null, true);
14296            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14297
14298            synchronized (mPackages) {
14299                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14300            }
14301
14302            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14303            serializer.endDocument();
14304            serializer.flush();
14305        } catch (Exception e) {
14306            if (DEBUG_BACKUP) {
14307                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14308            }
14309            return null;
14310        }
14311
14312        return dataStream.toByteArray();
14313    }
14314
14315    @Override
14316    public void restorePreferredActivities(byte[] backup, int userId) {
14317        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14318            throw new SecurityException("Only the system may call restorePreferredActivities()");
14319        }
14320
14321        try {
14322            final XmlPullParser parser = Xml.newPullParser();
14323            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14324            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14325                    new BlobXmlRestorer() {
14326                        @Override
14327                        public void apply(XmlPullParser parser, int userId)
14328                                throws XmlPullParserException, IOException {
14329                            synchronized (mPackages) {
14330                                mSettings.readPreferredActivitiesLPw(parser, userId);
14331                            }
14332                        }
14333                    } );
14334        } catch (Exception e) {
14335            if (DEBUG_BACKUP) {
14336                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14337            }
14338        }
14339    }
14340
14341    /**
14342     * Non-Binder method, support for the backup/restore mechanism: write the
14343     * default browser (etc) settings in its canonical XML format.  Returns the default
14344     * browser XML representation as a byte array, or null if there is none.
14345     */
14346    @Override
14347    public byte[] getDefaultAppsBackup(int userId) {
14348        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14349            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14350        }
14351
14352        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14353        try {
14354            final XmlSerializer serializer = new FastXmlSerializer();
14355            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14356            serializer.startDocument(null, true);
14357            serializer.startTag(null, TAG_DEFAULT_APPS);
14358
14359            synchronized (mPackages) {
14360                mSettings.writeDefaultAppsLPr(serializer, userId);
14361            }
14362
14363            serializer.endTag(null, TAG_DEFAULT_APPS);
14364            serializer.endDocument();
14365            serializer.flush();
14366        } catch (Exception e) {
14367            if (DEBUG_BACKUP) {
14368                Slog.e(TAG, "Unable to write default apps for backup", e);
14369            }
14370            return null;
14371        }
14372
14373        return dataStream.toByteArray();
14374    }
14375
14376    @Override
14377    public void restoreDefaultApps(byte[] backup, int userId) {
14378        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14379            throw new SecurityException("Only the system may call restoreDefaultApps()");
14380        }
14381
14382        try {
14383            final XmlPullParser parser = Xml.newPullParser();
14384            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14385            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14386                    new BlobXmlRestorer() {
14387                        @Override
14388                        public void apply(XmlPullParser parser, int userId)
14389                                throws XmlPullParserException, IOException {
14390                            synchronized (mPackages) {
14391                                mSettings.readDefaultAppsLPw(parser, userId);
14392                            }
14393                        }
14394                    } );
14395        } catch (Exception e) {
14396            if (DEBUG_BACKUP) {
14397                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14398            }
14399        }
14400    }
14401
14402    @Override
14403    public byte[] getIntentFilterVerificationBackup(int userId) {
14404        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14405            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14406        }
14407
14408        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14409        try {
14410            final XmlSerializer serializer = new FastXmlSerializer();
14411            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14412            serializer.startDocument(null, true);
14413            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14414
14415            synchronized (mPackages) {
14416                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14417            }
14418
14419            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14420            serializer.endDocument();
14421            serializer.flush();
14422        } catch (Exception e) {
14423            if (DEBUG_BACKUP) {
14424                Slog.e(TAG, "Unable to write default apps for backup", e);
14425            }
14426            return null;
14427        }
14428
14429        return dataStream.toByteArray();
14430    }
14431
14432    @Override
14433    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14434        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14435            throw new SecurityException("Only the system may call restorePreferredActivities()");
14436        }
14437
14438        try {
14439            final XmlPullParser parser = Xml.newPullParser();
14440            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14441            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14442                    new BlobXmlRestorer() {
14443                        @Override
14444                        public void apply(XmlPullParser parser, int userId)
14445                                throws XmlPullParserException, IOException {
14446                            synchronized (mPackages) {
14447                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14448                                mSettings.writeLPr();
14449                            }
14450                        }
14451                    } );
14452        } catch (Exception e) {
14453            if (DEBUG_BACKUP) {
14454                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14455            }
14456        }
14457    }
14458
14459    @Override
14460    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14461            int sourceUserId, int targetUserId, int flags) {
14462        mContext.enforceCallingOrSelfPermission(
14463                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14464        int callingUid = Binder.getCallingUid();
14465        enforceOwnerRights(ownerPackage, callingUid);
14466        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14467        if (intentFilter.countActions() == 0) {
14468            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14469            return;
14470        }
14471        synchronized (mPackages) {
14472            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14473                    ownerPackage, targetUserId, flags);
14474            CrossProfileIntentResolver resolver =
14475                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14476            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14477            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14478            if (existing != null) {
14479                int size = existing.size();
14480                for (int i = 0; i < size; i++) {
14481                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14482                        return;
14483                    }
14484                }
14485            }
14486            resolver.addFilter(newFilter);
14487            scheduleWritePackageRestrictionsLocked(sourceUserId);
14488        }
14489    }
14490
14491    @Override
14492    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14493        mContext.enforceCallingOrSelfPermission(
14494                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14495        int callingUid = Binder.getCallingUid();
14496        enforceOwnerRights(ownerPackage, callingUid);
14497        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14498        synchronized (mPackages) {
14499            CrossProfileIntentResolver resolver =
14500                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14501            ArraySet<CrossProfileIntentFilter> set =
14502                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14503            for (CrossProfileIntentFilter filter : set) {
14504                if (filter.getOwnerPackage().equals(ownerPackage)) {
14505                    resolver.removeFilter(filter);
14506                }
14507            }
14508            scheduleWritePackageRestrictionsLocked(sourceUserId);
14509        }
14510    }
14511
14512    // Enforcing that callingUid is owning pkg on userId
14513    private void enforceOwnerRights(String pkg, int callingUid) {
14514        // The system owns everything.
14515        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14516            return;
14517        }
14518        int callingUserId = UserHandle.getUserId(callingUid);
14519        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14520        if (pi == null) {
14521            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14522                    + callingUserId);
14523        }
14524        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14525            throw new SecurityException("Calling uid " + callingUid
14526                    + " does not own package " + pkg);
14527        }
14528    }
14529
14530    @Override
14531    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14532        Intent intent = new Intent(Intent.ACTION_MAIN);
14533        intent.addCategory(Intent.CATEGORY_HOME);
14534
14535        final int callingUserId = UserHandle.getCallingUserId();
14536        List<ResolveInfo> list = queryIntentActivities(intent, null,
14537                PackageManager.GET_META_DATA, callingUserId);
14538        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14539                true, false, false, callingUserId);
14540
14541        allHomeCandidates.clear();
14542        if (list != null) {
14543            for (ResolveInfo ri : list) {
14544                allHomeCandidates.add(ri);
14545            }
14546        }
14547        return (preferred == null || preferred.activityInfo == null)
14548                ? null
14549                : new ComponentName(preferred.activityInfo.packageName,
14550                        preferred.activityInfo.name);
14551    }
14552
14553    @Override
14554    public void setApplicationEnabledSetting(String appPackageName,
14555            int newState, int flags, int userId, String callingPackage) {
14556        if (!sUserManager.exists(userId)) return;
14557        if (callingPackage == null) {
14558            callingPackage = Integer.toString(Binder.getCallingUid());
14559        }
14560        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14561    }
14562
14563    @Override
14564    public void setComponentEnabledSetting(ComponentName componentName,
14565            int newState, int flags, int userId) {
14566        if (!sUserManager.exists(userId)) return;
14567        setEnabledSetting(componentName.getPackageName(),
14568                componentName.getClassName(), newState, flags, userId, null);
14569    }
14570
14571    private void setEnabledSetting(final String packageName, String className, int newState,
14572            final int flags, int userId, String callingPackage) {
14573        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14574              || newState == COMPONENT_ENABLED_STATE_ENABLED
14575              || newState == COMPONENT_ENABLED_STATE_DISABLED
14576              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14577              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14578            throw new IllegalArgumentException("Invalid new component state: "
14579                    + newState);
14580        }
14581        PackageSetting pkgSetting;
14582        final int uid = Binder.getCallingUid();
14583        final int permission = mContext.checkCallingOrSelfPermission(
14584                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14585        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14586        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14587        boolean sendNow = false;
14588        boolean isApp = (className == null);
14589        String componentName = isApp ? packageName : className;
14590        int packageUid = -1;
14591        ArrayList<String> components;
14592
14593        // writer
14594        synchronized (mPackages) {
14595            pkgSetting = mSettings.mPackages.get(packageName);
14596            if (pkgSetting == null) {
14597                if (className == null) {
14598                    throw new IllegalArgumentException(
14599                            "Unknown package: " + packageName);
14600                }
14601                throw new IllegalArgumentException(
14602                        "Unknown component: " + packageName
14603                        + "/" + className);
14604            }
14605            // Allow root and verify that userId is not being specified by a different user
14606            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14607                throw new SecurityException(
14608                        "Permission Denial: attempt to change component state from pid="
14609                        + Binder.getCallingPid()
14610                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14611            }
14612            if (className == null) {
14613                // We're dealing with an application/package level state change
14614                if (pkgSetting.getEnabled(userId) == newState) {
14615                    // Nothing to do
14616                    return;
14617                }
14618                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14619                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14620                    // Don't care about who enables an app.
14621                    callingPackage = null;
14622                }
14623                pkgSetting.setEnabled(newState, userId, callingPackage);
14624                // pkgSetting.pkg.mSetEnabled = newState;
14625            } else {
14626                // We're dealing with a component level state change
14627                // First, verify that this is a valid class name.
14628                PackageParser.Package pkg = pkgSetting.pkg;
14629                if (pkg == null || !pkg.hasComponentClassName(className)) {
14630                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14631                        throw new IllegalArgumentException("Component class " + className
14632                                + " does not exist in " + packageName);
14633                    } else {
14634                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14635                                + className + " does not exist in " + packageName);
14636                    }
14637                }
14638                switch (newState) {
14639                case COMPONENT_ENABLED_STATE_ENABLED:
14640                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14641                        return;
14642                    }
14643                    break;
14644                case COMPONENT_ENABLED_STATE_DISABLED:
14645                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14646                        return;
14647                    }
14648                    break;
14649                case COMPONENT_ENABLED_STATE_DEFAULT:
14650                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14651                        return;
14652                    }
14653                    break;
14654                default:
14655                    Slog.e(TAG, "Invalid new component state: " + newState);
14656                    return;
14657                }
14658            }
14659            scheduleWritePackageRestrictionsLocked(userId);
14660            components = mPendingBroadcasts.get(userId, packageName);
14661            final boolean newPackage = components == null;
14662            if (newPackage) {
14663                components = new ArrayList<String>();
14664            }
14665            if (!components.contains(componentName)) {
14666                components.add(componentName);
14667            }
14668            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14669                sendNow = true;
14670                // Purge entry from pending broadcast list if another one exists already
14671                // since we are sending one right away.
14672                mPendingBroadcasts.remove(userId, packageName);
14673            } else {
14674                if (newPackage) {
14675                    mPendingBroadcasts.put(userId, packageName, components);
14676                }
14677                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14678                    // Schedule a message
14679                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14680                }
14681            }
14682        }
14683
14684        long callingId = Binder.clearCallingIdentity();
14685        try {
14686            if (sendNow) {
14687                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14688                sendPackageChangedBroadcast(packageName,
14689                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14690            }
14691        } finally {
14692            Binder.restoreCallingIdentity(callingId);
14693        }
14694    }
14695
14696    private void sendPackageChangedBroadcast(String packageName,
14697            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14698        if (DEBUG_INSTALL)
14699            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14700                    + componentNames);
14701        Bundle extras = new Bundle(4);
14702        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14703        String nameList[] = new String[componentNames.size()];
14704        componentNames.toArray(nameList);
14705        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14706        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14707        extras.putInt(Intent.EXTRA_UID, packageUid);
14708        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14709                new int[] {UserHandle.getUserId(packageUid)});
14710    }
14711
14712    @Override
14713    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14714        if (!sUserManager.exists(userId)) return;
14715        final int uid = Binder.getCallingUid();
14716        final int permission = mContext.checkCallingOrSelfPermission(
14717                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14718        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14719        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14720        // writer
14721        synchronized (mPackages) {
14722            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14723                    allowedByPermission, uid, userId)) {
14724                scheduleWritePackageRestrictionsLocked(userId);
14725            }
14726        }
14727    }
14728
14729    @Override
14730    public String getInstallerPackageName(String packageName) {
14731        // reader
14732        synchronized (mPackages) {
14733            return mSettings.getInstallerPackageNameLPr(packageName);
14734        }
14735    }
14736
14737    @Override
14738    public int getApplicationEnabledSetting(String packageName, int userId) {
14739        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14740        int uid = Binder.getCallingUid();
14741        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14742        // reader
14743        synchronized (mPackages) {
14744            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14745        }
14746    }
14747
14748    @Override
14749    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14750        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14751        int uid = Binder.getCallingUid();
14752        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14753        // reader
14754        synchronized (mPackages) {
14755            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14756        }
14757    }
14758
14759    @Override
14760    public void enterSafeMode() {
14761        enforceSystemOrRoot("Only the system can request entering safe mode");
14762
14763        if (!mSystemReady) {
14764            mSafeMode = true;
14765        }
14766    }
14767
14768    @Override
14769    public void systemReady() {
14770        mSystemReady = true;
14771
14772        // Read the compatibilty setting when the system is ready.
14773        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14774                mContext.getContentResolver(),
14775                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14776        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14777        if (DEBUG_SETTINGS) {
14778            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14779        }
14780
14781        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14782
14783        synchronized (mPackages) {
14784            // Verify that all of the preferred activity components actually
14785            // exist.  It is possible for applications to be updated and at
14786            // that point remove a previously declared activity component that
14787            // had been set as a preferred activity.  We try to clean this up
14788            // the next time we encounter that preferred activity, but it is
14789            // possible for the user flow to never be able to return to that
14790            // situation so here we do a sanity check to make sure we haven't
14791            // left any junk around.
14792            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14793            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14794                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14795                removed.clear();
14796                for (PreferredActivity pa : pir.filterSet()) {
14797                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14798                        removed.add(pa);
14799                    }
14800                }
14801                if (removed.size() > 0) {
14802                    for (int r=0; r<removed.size(); r++) {
14803                        PreferredActivity pa = removed.get(r);
14804                        Slog.w(TAG, "Removing dangling preferred activity: "
14805                                + pa.mPref.mComponent);
14806                        pir.removeFilter(pa);
14807                    }
14808                    mSettings.writePackageRestrictionsLPr(
14809                            mSettings.mPreferredActivities.keyAt(i));
14810                }
14811            }
14812
14813            for (int userId : UserManagerService.getInstance().getUserIds()) {
14814                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14815                    grantPermissionsUserIds = ArrayUtils.appendInt(
14816                            grantPermissionsUserIds, userId);
14817                }
14818            }
14819        }
14820        sUserManager.systemReady();
14821
14822        // If we upgraded grant all default permissions before kicking off.
14823        for (int userId : grantPermissionsUserIds) {
14824            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14825        }
14826
14827        // Kick off any messages waiting for system ready
14828        if (mPostSystemReadyMessages != null) {
14829            for (Message msg : mPostSystemReadyMessages) {
14830                msg.sendToTarget();
14831            }
14832            mPostSystemReadyMessages = null;
14833        }
14834
14835        // Watch for external volumes that come and go over time
14836        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14837        storage.registerListener(mStorageListener);
14838
14839        mInstallerService.systemReady();
14840        mPackageDexOptimizer.systemReady();
14841
14842        MountServiceInternal mountServiceInternal = LocalServices.getService(
14843                MountServiceInternal.class);
14844        mountServiceInternal.addExternalStoragePolicy(
14845                new MountServiceInternal.ExternalStorageMountPolicy() {
14846            @Override
14847            public int getMountMode(int uid, String packageName) {
14848                if (Process.isIsolated(uid)) {
14849                    return Zygote.MOUNT_EXTERNAL_NONE;
14850                }
14851                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14852                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14853                }
14854                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14855                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14856                }
14857                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14858                    return Zygote.MOUNT_EXTERNAL_READ;
14859                }
14860                return Zygote.MOUNT_EXTERNAL_WRITE;
14861            }
14862
14863            @Override
14864            public boolean hasExternalStorage(int uid, String packageName) {
14865                return true;
14866            }
14867        });
14868    }
14869
14870    @Override
14871    public boolean isSafeMode() {
14872        return mSafeMode;
14873    }
14874
14875    @Override
14876    public boolean hasSystemUidErrors() {
14877        return mHasSystemUidErrors;
14878    }
14879
14880    static String arrayToString(int[] array) {
14881        StringBuffer buf = new StringBuffer(128);
14882        buf.append('[');
14883        if (array != null) {
14884            for (int i=0; i<array.length; i++) {
14885                if (i > 0) buf.append(", ");
14886                buf.append(array[i]);
14887            }
14888        }
14889        buf.append(']');
14890        return buf.toString();
14891    }
14892
14893    static class DumpState {
14894        public static final int DUMP_LIBS = 1 << 0;
14895        public static final int DUMP_FEATURES = 1 << 1;
14896        public static final int DUMP_RESOLVERS = 1 << 2;
14897        public static final int DUMP_PERMISSIONS = 1 << 3;
14898        public static final int DUMP_PACKAGES = 1 << 4;
14899        public static final int DUMP_SHARED_USERS = 1 << 5;
14900        public static final int DUMP_MESSAGES = 1 << 6;
14901        public static final int DUMP_PROVIDERS = 1 << 7;
14902        public static final int DUMP_VERIFIERS = 1 << 8;
14903        public static final int DUMP_PREFERRED = 1 << 9;
14904        public static final int DUMP_PREFERRED_XML = 1 << 10;
14905        public static final int DUMP_KEYSETS = 1 << 11;
14906        public static final int DUMP_VERSION = 1 << 12;
14907        public static final int DUMP_INSTALLS = 1 << 13;
14908        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14909        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14910
14911        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14912
14913        private int mTypes;
14914
14915        private int mOptions;
14916
14917        private boolean mTitlePrinted;
14918
14919        private SharedUserSetting mSharedUser;
14920
14921        public boolean isDumping(int type) {
14922            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14923                return true;
14924            }
14925
14926            return (mTypes & type) != 0;
14927        }
14928
14929        public void setDump(int type) {
14930            mTypes |= type;
14931        }
14932
14933        public boolean isOptionEnabled(int option) {
14934            return (mOptions & option) != 0;
14935        }
14936
14937        public void setOptionEnabled(int option) {
14938            mOptions |= option;
14939        }
14940
14941        public boolean onTitlePrinted() {
14942            final boolean printed = mTitlePrinted;
14943            mTitlePrinted = true;
14944            return printed;
14945        }
14946
14947        public boolean getTitlePrinted() {
14948            return mTitlePrinted;
14949        }
14950
14951        public void setTitlePrinted(boolean enabled) {
14952            mTitlePrinted = enabled;
14953        }
14954
14955        public SharedUserSetting getSharedUser() {
14956            return mSharedUser;
14957        }
14958
14959        public void setSharedUser(SharedUserSetting user) {
14960            mSharedUser = user;
14961        }
14962    }
14963
14964    @Override
14965    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14966        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14967                != PackageManager.PERMISSION_GRANTED) {
14968            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14969                    + Binder.getCallingPid()
14970                    + ", uid=" + Binder.getCallingUid()
14971                    + " without permission "
14972                    + android.Manifest.permission.DUMP);
14973            return;
14974        }
14975
14976        DumpState dumpState = new DumpState();
14977        boolean fullPreferred = false;
14978        boolean checkin = false;
14979
14980        String packageName = null;
14981        ArraySet<String> permissionNames = null;
14982
14983        int opti = 0;
14984        while (opti < args.length) {
14985            String opt = args[opti];
14986            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14987                break;
14988            }
14989            opti++;
14990
14991            if ("-a".equals(opt)) {
14992                // Right now we only know how to print all.
14993            } else if ("-h".equals(opt)) {
14994                pw.println("Package manager dump options:");
14995                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14996                pw.println("    --checkin: dump for a checkin");
14997                pw.println("    -f: print details of intent filters");
14998                pw.println("    -h: print this help");
14999                pw.println("  cmd may be one of:");
15000                pw.println("    l[ibraries]: list known shared libraries");
15001                pw.println("    f[ibraries]: list device features");
15002                pw.println("    k[eysets]: print known keysets");
15003                pw.println("    r[esolvers]: dump intent resolvers");
15004                pw.println("    perm[issions]: dump permissions");
15005                pw.println("    permission [name ...]: dump declaration and use of given permission");
15006                pw.println("    pref[erred]: print preferred package settings");
15007                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15008                pw.println("    prov[iders]: dump content providers");
15009                pw.println("    p[ackages]: dump installed packages");
15010                pw.println("    s[hared-users]: dump shared user IDs");
15011                pw.println("    m[essages]: print collected runtime messages");
15012                pw.println("    v[erifiers]: print package verifier info");
15013                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15014                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15015                pw.println("    version: print database version info");
15016                pw.println("    write: write current settings now");
15017                pw.println("    installs: details about install sessions");
15018                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15019                pw.println("    <package.name>: info about given package");
15020                return;
15021            } else if ("--checkin".equals(opt)) {
15022                checkin = true;
15023            } else if ("-f".equals(opt)) {
15024                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15025            } else {
15026                pw.println("Unknown argument: " + opt + "; use -h for help");
15027            }
15028        }
15029
15030        // Is the caller requesting to dump a particular piece of data?
15031        if (opti < args.length) {
15032            String cmd = args[opti];
15033            opti++;
15034            // Is this a package name?
15035            if ("android".equals(cmd) || cmd.contains(".")) {
15036                packageName = cmd;
15037                // When dumping a single package, we always dump all of its
15038                // filter information since the amount of data will be reasonable.
15039                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15040            } else if ("check-permission".equals(cmd)) {
15041                if (opti >= args.length) {
15042                    pw.println("Error: check-permission missing permission argument");
15043                    return;
15044                }
15045                String perm = args[opti];
15046                opti++;
15047                if (opti >= args.length) {
15048                    pw.println("Error: check-permission missing package argument");
15049                    return;
15050                }
15051                String pkg = args[opti];
15052                opti++;
15053                int user = UserHandle.getUserId(Binder.getCallingUid());
15054                if (opti < args.length) {
15055                    try {
15056                        user = Integer.parseInt(args[opti]);
15057                    } catch (NumberFormatException e) {
15058                        pw.println("Error: check-permission user argument is not a number: "
15059                                + args[opti]);
15060                        return;
15061                    }
15062                }
15063                pw.println(checkPermission(perm, pkg, user));
15064                return;
15065            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15066                dumpState.setDump(DumpState.DUMP_LIBS);
15067            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15068                dumpState.setDump(DumpState.DUMP_FEATURES);
15069            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15070                dumpState.setDump(DumpState.DUMP_RESOLVERS);
15071            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15072                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15073            } else if ("permission".equals(cmd)) {
15074                if (opti >= args.length) {
15075                    pw.println("Error: permission requires permission name");
15076                    return;
15077                }
15078                permissionNames = new ArraySet<>();
15079                while (opti < args.length) {
15080                    permissionNames.add(args[opti]);
15081                    opti++;
15082                }
15083                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15084                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15085            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15086                dumpState.setDump(DumpState.DUMP_PREFERRED);
15087            } else if ("preferred-xml".equals(cmd)) {
15088                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15089                if (opti < args.length && "--full".equals(args[opti])) {
15090                    fullPreferred = true;
15091                    opti++;
15092                }
15093            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15094                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15095            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15096                dumpState.setDump(DumpState.DUMP_PACKAGES);
15097            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15098                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15099            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15100                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15101            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15102                dumpState.setDump(DumpState.DUMP_MESSAGES);
15103            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15104                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15105            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15106                    || "intent-filter-verifiers".equals(cmd)) {
15107                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15108            } else if ("version".equals(cmd)) {
15109                dumpState.setDump(DumpState.DUMP_VERSION);
15110            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15111                dumpState.setDump(DumpState.DUMP_KEYSETS);
15112            } else if ("installs".equals(cmd)) {
15113                dumpState.setDump(DumpState.DUMP_INSTALLS);
15114            } else if ("write".equals(cmd)) {
15115                synchronized (mPackages) {
15116                    mSettings.writeLPr();
15117                    pw.println("Settings written.");
15118                    return;
15119                }
15120            }
15121        }
15122
15123        if (checkin) {
15124            pw.println("vers,1");
15125        }
15126
15127        // reader
15128        synchronized (mPackages) {
15129            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15130                if (!checkin) {
15131                    if (dumpState.onTitlePrinted())
15132                        pw.println();
15133                    pw.println("Database versions:");
15134                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15135                }
15136            }
15137
15138            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15139                if (!checkin) {
15140                    if (dumpState.onTitlePrinted())
15141                        pw.println();
15142                    pw.println("Verifiers:");
15143                    pw.print("  Required: ");
15144                    pw.print(mRequiredVerifierPackage);
15145                    pw.print(" (uid=");
15146                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15147                    pw.println(")");
15148                } else if (mRequiredVerifierPackage != null) {
15149                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15150                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15151                }
15152            }
15153
15154            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15155                    packageName == null) {
15156                if (mIntentFilterVerifierComponent != null) {
15157                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15158                    if (!checkin) {
15159                        if (dumpState.onTitlePrinted())
15160                            pw.println();
15161                        pw.println("Intent Filter Verifier:");
15162                        pw.print("  Using: ");
15163                        pw.print(verifierPackageName);
15164                        pw.print(" (uid=");
15165                        pw.print(getPackageUid(verifierPackageName, 0));
15166                        pw.println(")");
15167                    } else if (verifierPackageName != null) {
15168                        pw.print("ifv,"); pw.print(verifierPackageName);
15169                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15170                    }
15171                } else {
15172                    pw.println();
15173                    pw.println("No Intent Filter Verifier available!");
15174                }
15175            }
15176
15177            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15178                boolean printedHeader = false;
15179                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15180                while (it.hasNext()) {
15181                    String name = it.next();
15182                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15183                    if (!checkin) {
15184                        if (!printedHeader) {
15185                            if (dumpState.onTitlePrinted())
15186                                pw.println();
15187                            pw.println("Libraries:");
15188                            printedHeader = true;
15189                        }
15190                        pw.print("  ");
15191                    } else {
15192                        pw.print("lib,");
15193                    }
15194                    pw.print(name);
15195                    if (!checkin) {
15196                        pw.print(" -> ");
15197                    }
15198                    if (ent.path != null) {
15199                        if (!checkin) {
15200                            pw.print("(jar) ");
15201                            pw.print(ent.path);
15202                        } else {
15203                            pw.print(",jar,");
15204                            pw.print(ent.path);
15205                        }
15206                    } else {
15207                        if (!checkin) {
15208                            pw.print("(apk) ");
15209                            pw.print(ent.apk);
15210                        } else {
15211                            pw.print(",apk,");
15212                            pw.print(ent.apk);
15213                        }
15214                    }
15215                    pw.println();
15216                }
15217            }
15218
15219            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15220                if (dumpState.onTitlePrinted())
15221                    pw.println();
15222                if (!checkin) {
15223                    pw.println("Features:");
15224                }
15225                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15226                while (it.hasNext()) {
15227                    String name = it.next();
15228                    if (!checkin) {
15229                        pw.print("  ");
15230                    } else {
15231                        pw.print("feat,");
15232                    }
15233                    pw.println(name);
15234                }
15235            }
15236
15237            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
15238                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15239                        : "Activity Resolver Table:", "  ", packageName,
15240                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15241                    dumpState.setTitlePrinted(true);
15242                }
15243                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15244                        : "Receiver Resolver Table:", "  ", packageName,
15245                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15246                    dumpState.setTitlePrinted(true);
15247                }
15248                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15249                        : "Service Resolver Table:", "  ", packageName,
15250                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15251                    dumpState.setTitlePrinted(true);
15252                }
15253                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15254                        : "Provider Resolver Table:", "  ", packageName,
15255                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15256                    dumpState.setTitlePrinted(true);
15257                }
15258            }
15259
15260            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15261                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15262                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15263                    int user = mSettings.mPreferredActivities.keyAt(i);
15264                    if (pir.dump(pw,
15265                            dumpState.getTitlePrinted()
15266                                ? "\nPreferred Activities User " + user + ":"
15267                                : "Preferred Activities User " + user + ":", "  ",
15268                            packageName, true, false)) {
15269                        dumpState.setTitlePrinted(true);
15270                    }
15271                }
15272            }
15273
15274            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15275                pw.flush();
15276                FileOutputStream fout = new FileOutputStream(fd);
15277                BufferedOutputStream str = new BufferedOutputStream(fout);
15278                XmlSerializer serializer = new FastXmlSerializer();
15279                try {
15280                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15281                    serializer.startDocument(null, true);
15282                    serializer.setFeature(
15283                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15284                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15285                    serializer.endDocument();
15286                    serializer.flush();
15287                } catch (IllegalArgumentException e) {
15288                    pw.println("Failed writing: " + e);
15289                } catch (IllegalStateException e) {
15290                    pw.println("Failed writing: " + e);
15291                } catch (IOException e) {
15292                    pw.println("Failed writing: " + e);
15293                }
15294            }
15295
15296            if (!checkin
15297                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15298                    && packageName == null) {
15299                pw.println();
15300                int count = mSettings.mPackages.size();
15301                if (count == 0) {
15302                    pw.println("No applications!");
15303                    pw.println();
15304                } else {
15305                    final String prefix = "  ";
15306                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15307                    if (allPackageSettings.size() == 0) {
15308                        pw.println("No domain preferred apps!");
15309                        pw.println();
15310                    } else {
15311                        pw.println("App verification status:");
15312                        pw.println();
15313                        count = 0;
15314                        for (PackageSetting ps : allPackageSettings) {
15315                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15316                            if (ivi == null || ivi.getPackageName() == null) continue;
15317                            pw.println(prefix + "Package: " + ivi.getPackageName());
15318                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15319                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15320                            pw.println();
15321                            count++;
15322                        }
15323                        if (count == 0) {
15324                            pw.println(prefix + "No app verification established.");
15325                            pw.println();
15326                        }
15327                        for (int userId : sUserManager.getUserIds()) {
15328                            pw.println("App linkages for user " + userId + ":");
15329                            pw.println();
15330                            count = 0;
15331                            for (PackageSetting ps : allPackageSettings) {
15332                                final long status = ps.getDomainVerificationStatusForUser(userId);
15333                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15334                                    continue;
15335                                }
15336                                pw.println(prefix + "Package: " + ps.name);
15337                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15338                                String statusStr = IntentFilterVerificationInfo.
15339                                        getStatusStringFromValue(status);
15340                                pw.println(prefix + "Status:  " + statusStr);
15341                                pw.println();
15342                                count++;
15343                            }
15344                            if (count == 0) {
15345                                pw.println(prefix + "No configured app linkages.");
15346                                pw.println();
15347                            }
15348                        }
15349                    }
15350                }
15351            }
15352
15353            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15354                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15355                if (packageName == null && permissionNames == null) {
15356                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15357                        if (iperm == 0) {
15358                            if (dumpState.onTitlePrinted())
15359                                pw.println();
15360                            pw.println("AppOp Permissions:");
15361                        }
15362                        pw.print("  AppOp Permission ");
15363                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15364                        pw.println(":");
15365                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15366                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15367                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15368                        }
15369                    }
15370                }
15371            }
15372
15373            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15374                boolean printedSomething = false;
15375                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15376                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15377                        continue;
15378                    }
15379                    if (!printedSomething) {
15380                        if (dumpState.onTitlePrinted())
15381                            pw.println();
15382                        pw.println("Registered ContentProviders:");
15383                        printedSomething = true;
15384                    }
15385                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15386                    pw.print("    "); pw.println(p.toString());
15387                }
15388                printedSomething = false;
15389                for (Map.Entry<String, PackageParser.Provider> entry :
15390                        mProvidersByAuthority.entrySet()) {
15391                    PackageParser.Provider p = entry.getValue();
15392                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15393                        continue;
15394                    }
15395                    if (!printedSomething) {
15396                        if (dumpState.onTitlePrinted())
15397                            pw.println();
15398                        pw.println("ContentProvider Authorities:");
15399                        printedSomething = true;
15400                    }
15401                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15402                    pw.print("    "); pw.println(p.toString());
15403                    if (p.info != null && p.info.applicationInfo != null) {
15404                        final String appInfo = p.info.applicationInfo.toString();
15405                        pw.print("      applicationInfo="); pw.println(appInfo);
15406                    }
15407                }
15408            }
15409
15410            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15411                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15412            }
15413
15414            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15415                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15416            }
15417
15418            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15419                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15420            }
15421
15422            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15423                // XXX should handle packageName != null by dumping only install data that
15424                // the given package is involved with.
15425                if (dumpState.onTitlePrinted()) pw.println();
15426                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15427            }
15428
15429            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15430                if (dumpState.onTitlePrinted()) pw.println();
15431                mSettings.dumpReadMessagesLPr(pw, dumpState);
15432
15433                pw.println();
15434                pw.println("Package warning messages:");
15435                BufferedReader in = null;
15436                String line = null;
15437                try {
15438                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15439                    while ((line = in.readLine()) != null) {
15440                        if (line.contains("ignored: updated version")) continue;
15441                        pw.println(line);
15442                    }
15443                } catch (IOException ignored) {
15444                } finally {
15445                    IoUtils.closeQuietly(in);
15446                }
15447            }
15448
15449            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15450                BufferedReader in = null;
15451                String line = null;
15452                try {
15453                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15454                    while ((line = in.readLine()) != null) {
15455                        if (line.contains("ignored: updated version")) continue;
15456                        pw.print("msg,");
15457                        pw.println(line);
15458                    }
15459                } catch (IOException ignored) {
15460                } finally {
15461                    IoUtils.closeQuietly(in);
15462                }
15463            }
15464        }
15465    }
15466
15467    private String dumpDomainString(String packageName) {
15468        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15469        List<IntentFilter> filters = getAllIntentFilters(packageName);
15470
15471        ArraySet<String> result = new ArraySet<>();
15472        if (iviList.size() > 0) {
15473            for (IntentFilterVerificationInfo ivi : iviList) {
15474                for (String host : ivi.getDomains()) {
15475                    result.add(host);
15476                }
15477            }
15478        }
15479        if (filters != null && filters.size() > 0) {
15480            for (IntentFilter filter : filters) {
15481                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15482                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15483                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15484                    result.addAll(filter.getHostsList());
15485                }
15486            }
15487        }
15488
15489        StringBuilder sb = new StringBuilder(result.size() * 16);
15490        for (String domain : result) {
15491            if (sb.length() > 0) sb.append(" ");
15492            sb.append(domain);
15493        }
15494        return sb.toString();
15495    }
15496
15497    // ------- apps on sdcard specific code -------
15498    static final boolean DEBUG_SD_INSTALL = false;
15499
15500    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15501
15502    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15503
15504    private boolean mMediaMounted = false;
15505
15506    static String getEncryptKey() {
15507        try {
15508            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15509                    SD_ENCRYPTION_KEYSTORE_NAME);
15510            if (sdEncKey == null) {
15511                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15512                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15513                if (sdEncKey == null) {
15514                    Slog.e(TAG, "Failed to create encryption keys");
15515                    return null;
15516                }
15517            }
15518            return sdEncKey;
15519        } catch (NoSuchAlgorithmException nsae) {
15520            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15521            return null;
15522        } catch (IOException ioe) {
15523            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15524            return null;
15525        }
15526    }
15527
15528    /*
15529     * Update media status on PackageManager.
15530     */
15531    @Override
15532    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15533        int callingUid = Binder.getCallingUid();
15534        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15535            throw new SecurityException("Media status can only be updated by the system");
15536        }
15537        // reader; this apparently protects mMediaMounted, but should probably
15538        // be a different lock in that case.
15539        synchronized (mPackages) {
15540            Log.i(TAG, "Updating external media status from "
15541                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15542                    + (mediaStatus ? "mounted" : "unmounted"));
15543            if (DEBUG_SD_INSTALL)
15544                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15545                        + ", mMediaMounted=" + mMediaMounted);
15546            if (mediaStatus == mMediaMounted) {
15547                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15548                        : 0, -1);
15549                mHandler.sendMessage(msg);
15550                return;
15551            }
15552            mMediaMounted = mediaStatus;
15553        }
15554        // Queue up an async operation since the package installation may take a
15555        // little while.
15556        mHandler.post(new Runnable() {
15557            public void run() {
15558                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15559            }
15560        });
15561    }
15562
15563    /**
15564     * Called by MountService when the initial ASECs to scan are available.
15565     * Should block until all the ASEC containers are finished being scanned.
15566     */
15567    public void scanAvailableAsecs() {
15568        updateExternalMediaStatusInner(true, false, false);
15569        if (mShouldRestoreconData) {
15570            SELinuxMMAC.setRestoreconDone();
15571            mShouldRestoreconData = false;
15572        }
15573    }
15574
15575    /*
15576     * Collect information of applications on external media, map them against
15577     * existing containers and update information based on current mount status.
15578     * Please note that we always have to report status if reportStatus has been
15579     * set to true especially when unloading packages.
15580     */
15581    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15582            boolean externalStorage) {
15583        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15584        int[] uidArr = EmptyArray.INT;
15585
15586        final String[] list = PackageHelper.getSecureContainerList();
15587        if (ArrayUtils.isEmpty(list)) {
15588            Log.i(TAG, "No secure containers found");
15589        } else {
15590            // Process list of secure containers and categorize them
15591            // as active or stale based on their package internal state.
15592
15593            // reader
15594            synchronized (mPackages) {
15595                for (String cid : list) {
15596                    // Leave stages untouched for now; installer service owns them
15597                    if (PackageInstallerService.isStageName(cid)) continue;
15598
15599                    if (DEBUG_SD_INSTALL)
15600                        Log.i(TAG, "Processing container " + cid);
15601                    String pkgName = getAsecPackageName(cid);
15602                    if (pkgName == null) {
15603                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15604                        continue;
15605                    }
15606                    if (DEBUG_SD_INSTALL)
15607                        Log.i(TAG, "Looking for pkg : " + pkgName);
15608
15609                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15610                    if (ps == null) {
15611                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15612                        continue;
15613                    }
15614
15615                    /*
15616                     * Skip packages that are not external if we're unmounting
15617                     * external storage.
15618                     */
15619                    if (externalStorage && !isMounted && !isExternal(ps)) {
15620                        continue;
15621                    }
15622
15623                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15624                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15625                    // The package status is changed only if the code path
15626                    // matches between settings and the container id.
15627                    if (ps.codePathString != null
15628                            && ps.codePathString.startsWith(args.getCodePath())) {
15629                        if (DEBUG_SD_INSTALL) {
15630                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15631                                    + " at code path: " + ps.codePathString);
15632                        }
15633
15634                        // We do have a valid package installed on sdcard
15635                        processCids.put(args, ps.codePathString);
15636                        final int uid = ps.appId;
15637                        if (uid != -1) {
15638                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15639                        }
15640                    } else {
15641                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15642                                + ps.codePathString);
15643                    }
15644                }
15645            }
15646
15647            Arrays.sort(uidArr);
15648        }
15649
15650        // Process packages with valid entries.
15651        if (isMounted) {
15652            if (DEBUG_SD_INSTALL)
15653                Log.i(TAG, "Loading packages");
15654            loadMediaPackages(processCids, uidArr);
15655            startCleaningPackages();
15656            mInstallerService.onSecureContainersAvailable();
15657        } else {
15658            if (DEBUG_SD_INSTALL)
15659                Log.i(TAG, "Unloading packages");
15660            unloadMediaPackages(processCids, uidArr, reportStatus);
15661        }
15662    }
15663
15664    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15665            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15666        final int size = infos.size();
15667        final String[] packageNames = new String[size];
15668        final int[] packageUids = new int[size];
15669        for (int i = 0; i < size; i++) {
15670            final ApplicationInfo info = infos.get(i);
15671            packageNames[i] = info.packageName;
15672            packageUids[i] = info.uid;
15673        }
15674        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15675                finishedReceiver);
15676    }
15677
15678    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15679            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15680        sendResourcesChangedBroadcast(mediaStatus, replacing,
15681                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15682    }
15683
15684    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15685            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15686        int size = pkgList.length;
15687        if (size > 0) {
15688            // Send broadcasts here
15689            Bundle extras = new Bundle();
15690            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15691            if (uidArr != null) {
15692                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15693            }
15694            if (replacing) {
15695                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15696            }
15697            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15698                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15699            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15700        }
15701    }
15702
15703   /*
15704     * Look at potentially valid container ids from processCids If package
15705     * information doesn't match the one on record or package scanning fails,
15706     * the cid is added to list of removeCids. We currently don't delete stale
15707     * containers.
15708     */
15709    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15710        ArrayList<String> pkgList = new ArrayList<String>();
15711        Set<AsecInstallArgs> keys = processCids.keySet();
15712
15713        for (AsecInstallArgs args : keys) {
15714            String codePath = processCids.get(args);
15715            if (DEBUG_SD_INSTALL)
15716                Log.i(TAG, "Loading container : " + args.cid);
15717            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15718            try {
15719                // Make sure there are no container errors first.
15720                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15721                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15722                            + " when installing from sdcard");
15723                    continue;
15724                }
15725                // Check code path here.
15726                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15727                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15728                            + " does not match one in settings " + codePath);
15729                    continue;
15730                }
15731                // Parse package
15732                int parseFlags = mDefParseFlags;
15733                if (args.isExternalAsec()) {
15734                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15735                }
15736                if (args.isFwdLocked()) {
15737                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15738                }
15739
15740                synchronized (mInstallLock) {
15741                    PackageParser.Package pkg = null;
15742                    try {
15743                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
15744                    } catch (PackageManagerException e) {
15745                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15746                    }
15747                    // Scan the package
15748                    if (pkg != null) {
15749                        /*
15750                         * TODO why is the lock being held? doPostInstall is
15751                         * called in other places without the lock. This needs
15752                         * to be straightened out.
15753                         */
15754                        // writer
15755                        synchronized (mPackages) {
15756                            retCode = PackageManager.INSTALL_SUCCEEDED;
15757                            pkgList.add(pkg.packageName);
15758                            // Post process args
15759                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15760                                    pkg.applicationInfo.uid);
15761                        }
15762                    } else {
15763                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15764                    }
15765                }
15766
15767            } finally {
15768                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15769                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15770                }
15771            }
15772        }
15773        // writer
15774        synchronized (mPackages) {
15775            // If the platform SDK has changed since the last time we booted,
15776            // we need to re-grant app permission to catch any new ones that
15777            // appear. This is really a hack, and means that apps can in some
15778            // cases get permissions that the user didn't initially explicitly
15779            // allow... it would be nice to have some better way to handle
15780            // this situation.
15781            final VersionInfo ver = mSettings.getExternalVersion();
15782
15783            int updateFlags = UPDATE_PERMISSIONS_ALL;
15784            if (ver.sdkVersion != mSdkVersion) {
15785                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15786                        + mSdkVersion + "; regranting permissions for external");
15787                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15788            }
15789            updatePermissionsLPw(null, null, updateFlags);
15790
15791            // Yay, everything is now upgraded
15792            ver.forceCurrent();
15793
15794            // can downgrade to reader
15795            // Persist settings
15796            mSettings.writeLPr();
15797        }
15798        // Send a broadcast to let everyone know we are done processing
15799        if (pkgList.size() > 0) {
15800            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15801        }
15802    }
15803
15804   /*
15805     * Utility method to unload a list of specified containers
15806     */
15807    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15808        // Just unmount all valid containers.
15809        for (AsecInstallArgs arg : cidArgs) {
15810            synchronized (mInstallLock) {
15811                arg.doPostDeleteLI(false);
15812           }
15813       }
15814   }
15815
15816    /*
15817     * Unload packages mounted on external media. This involves deleting package
15818     * data from internal structures, sending broadcasts about diabled packages,
15819     * gc'ing to free up references, unmounting all secure containers
15820     * corresponding to packages on external media, and posting a
15821     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15822     * that we always have to post this message if status has been requested no
15823     * matter what.
15824     */
15825    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15826            final boolean reportStatus) {
15827        if (DEBUG_SD_INSTALL)
15828            Log.i(TAG, "unloading media packages");
15829        ArrayList<String> pkgList = new ArrayList<String>();
15830        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15831        final Set<AsecInstallArgs> keys = processCids.keySet();
15832        for (AsecInstallArgs args : keys) {
15833            String pkgName = args.getPackageName();
15834            if (DEBUG_SD_INSTALL)
15835                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15836            // Delete package internally
15837            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15838            synchronized (mInstallLock) {
15839                boolean res = deletePackageLI(pkgName, null, false, null, null,
15840                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15841                if (res) {
15842                    pkgList.add(pkgName);
15843                } else {
15844                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15845                    failedList.add(args);
15846                }
15847            }
15848        }
15849
15850        // reader
15851        synchronized (mPackages) {
15852            // We didn't update the settings after removing each package;
15853            // write them now for all packages.
15854            mSettings.writeLPr();
15855        }
15856
15857        // We have to absolutely send UPDATED_MEDIA_STATUS only
15858        // after confirming that all the receivers processed the ordered
15859        // broadcast when packages get disabled, force a gc to clean things up.
15860        // and unload all the containers.
15861        if (pkgList.size() > 0) {
15862            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15863                    new IIntentReceiver.Stub() {
15864                public void performReceive(Intent intent, int resultCode, String data,
15865                        Bundle extras, boolean ordered, boolean sticky,
15866                        int sendingUser) throws RemoteException {
15867                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15868                            reportStatus ? 1 : 0, 1, keys);
15869                    mHandler.sendMessage(msg);
15870                }
15871            });
15872        } else {
15873            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15874                    keys);
15875            mHandler.sendMessage(msg);
15876        }
15877    }
15878
15879    private void loadPrivatePackages(final VolumeInfo vol) {
15880        mHandler.post(new Runnable() {
15881            @Override
15882            public void run() {
15883                loadPrivatePackagesInner(vol);
15884            }
15885        });
15886    }
15887
15888    private void loadPrivatePackagesInner(VolumeInfo vol) {
15889        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15890        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15891
15892        final VersionInfo ver;
15893        final List<PackageSetting> packages;
15894        synchronized (mPackages) {
15895            ver = mSettings.findOrCreateVersion(vol.fsUuid);
15896            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15897        }
15898
15899        for (PackageSetting ps : packages) {
15900            synchronized (mInstallLock) {
15901                final PackageParser.Package pkg;
15902                try {
15903                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15904                    loaded.add(pkg.applicationInfo);
15905                } catch (PackageManagerException e) {
15906                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15907                }
15908
15909                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15910                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15911                }
15912            }
15913        }
15914
15915        synchronized (mPackages) {
15916            int updateFlags = UPDATE_PERMISSIONS_ALL;
15917            if (ver.sdkVersion != mSdkVersion) {
15918                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15919                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15920                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15921            }
15922            updatePermissionsLPw(null, null, updateFlags);
15923
15924            // Yay, everything is now upgraded
15925            ver.forceCurrent();
15926
15927            mSettings.writeLPr();
15928        }
15929
15930        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15931        sendResourcesChangedBroadcast(true, false, loaded, null);
15932    }
15933
15934    private void unloadPrivatePackages(final VolumeInfo vol) {
15935        mHandler.post(new Runnable() {
15936            @Override
15937            public void run() {
15938                unloadPrivatePackagesInner(vol);
15939            }
15940        });
15941    }
15942
15943    private void unloadPrivatePackagesInner(VolumeInfo vol) {
15944        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15945        synchronized (mInstallLock) {
15946        synchronized (mPackages) {
15947            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15948            for (PackageSetting ps : packages) {
15949                if (ps.pkg == null) continue;
15950
15951                final ApplicationInfo info = ps.pkg.applicationInfo;
15952                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15953                if (deletePackageLI(ps.name, null, false, null, null,
15954                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15955                    unloaded.add(info);
15956                } else {
15957                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15958                }
15959            }
15960
15961            mSettings.writeLPr();
15962        }
15963        }
15964
15965        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15966        sendResourcesChangedBroadcast(false, false, unloaded, null);
15967    }
15968
15969    /**
15970     * Examine all users present on given mounted volume, and destroy data
15971     * belonging to users that are no longer valid, or whose user ID has been
15972     * recycled.
15973     */
15974    private void reconcileUsers(String volumeUuid) {
15975        final File[] files = FileUtils
15976                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15977        for (File file : files) {
15978            if (!file.isDirectory()) continue;
15979
15980            final int userId;
15981            final UserInfo info;
15982            try {
15983                userId = Integer.parseInt(file.getName());
15984                info = sUserManager.getUserInfo(userId);
15985            } catch (NumberFormatException e) {
15986                Slog.w(TAG, "Invalid user directory " + file);
15987                continue;
15988            }
15989
15990            boolean destroyUser = false;
15991            if (info == null) {
15992                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15993                        + " because no matching user was found");
15994                destroyUser = true;
15995            } else {
15996                try {
15997                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15998                } catch (IOException e) {
15999                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16000                            + " because we failed to enforce serial number: " + e);
16001                    destroyUser = true;
16002                }
16003            }
16004
16005            if (destroyUser) {
16006                synchronized (mInstallLock) {
16007                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16008                }
16009            }
16010        }
16011
16012        final UserManager um = mContext.getSystemService(UserManager.class);
16013        for (UserInfo user : um.getUsers()) {
16014            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16015            if (userDir.exists()) continue;
16016
16017            try {
16018                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
16019                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16020            } catch (IOException e) {
16021                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16022            }
16023        }
16024    }
16025
16026    /**
16027     * Examine all apps present on given mounted volume, and destroy apps that
16028     * aren't expected, either due to uninstallation or reinstallation on
16029     * another volume.
16030     */
16031    private void reconcileApps(String volumeUuid) {
16032        final File[] files = FileUtils
16033                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16034        for (File file : files) {
16035            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16036                    && !PackageInstallerService.isStageName(file.getName());
16037            if (!isPackage) {
16038                // Ignore entries which are not packages
16039                continue;
16040            }
16041
16042            boolean destroyApp = false;
16043            String packageName = null;
16044            try {
16045                final PackageLite pkg = PackageParser.parsePackageLite(file,
16046                        PackageParser.PARSE_MUST_BE_APK);
16047                packageName = pkg.packageName;
16048
16049                synchronized (mPackages) {
16050                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16051                    if (ps == null) {
16052                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16053                                + volumeUuid + " because we found no install record");
16054                        destroyApp = true;
16055                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16056                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16057                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16058                        destroyApp = true;
16059                    }
16060                }
16061
16062            } catch (PackageParserException e) {
16063                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16064                destroyApp = true;
16065            }
16066
16067            if (destroyApp) {
16068                synchronized (mInstallLock) {
16069                    if (packageName != null) {
16070                        removeDataDirsLI(volumeUuid, packageName);
16071                    }
16072                    if (file.isDirectory()) {
16073                        mInstaller.rmPackageDir(file.getAbsolutePath());
16074                    } else {
16075                        file.delete();
16076                    }
16077                }
16078            }
16079        }
16080    }
16081
16082    private void unfreezePackage(String packageName) {
16083        synchronized (mPackages) {
16084            final PackageSetting ps = mSettings.mPackages.get(packageName);
16085            if (ps != null) {
16086                ps.frozen = false;
16087            }
16088        }
16089    }
16090
16091    @Override
16092    public int movePackage(final String packageName, final String volumeUuid) {
16093        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16094
16095        final int moveId = mNextMoveId.getAndIncrement();
16096        try {
16097            movePackageInternal(packageName, volumeUuid, moveId);
16098        } catch (PackageManagerException e) {
16099            Slog.w(TAG, "Failed to move " + packageName, e);
16100            mMoveCallbacks.notifyStatusChanged(moveId,
16101                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16102        }
16103        return moveId;
16104    }
16105
16106    private void movePackageInternal(final String packageName, final String volumeUuid,
16107            final int moveId) throws PackageManagerException {
16108        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16109        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16110        final PackageManager pm = mContext.getPackageManager();
16111
16112        final boolean currentAsec;
16113        final String currentVolumeUuid;
16114        final File codeFile;
16115        final String installerPackageName;
16116        final String packageAbiOverride;
16117        final int appId;
16118        final String seinfo;
16119        final String label;
16120
16121        // reader
16122        synchronized (mPackages) {
16123            final PackageParser.Package pkg = mPackages.get(packageName);
16124            final PackageSetting ps = mSettings.mPackages.get(packageName);
16125            if (pkg == null || ps == null) {
16126                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16127            }
16128
16129            if (pkg.applicationInfo.isSystemApp()) {
16130                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16131                        "Cannot move system application");
16132            }
16133
16134            if (pkg.applicationInfo.isExternalAsec()) {
16135                currentAsec = true;
16136                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16137            } else if (pkg.applicationInfo.isForwardLocked()) {
16138                currentAsec = true;
16139                currentVolumeUuid = "forward_locked";
16140            } else {
16141                currentAsec = false;
16142                currentVolumeUuid = ps.volumeUuid;
16143
16144                final File probe = new File(pkg.codePath);
16145                final File probeOat = new File(probe, "oat");
16146                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16147                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16148                            "Move only supported for modern cluster style installs");
16149                }
16150            }
16151
16152            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16153                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16154                        "Package already moved to " + volumeUuid);
16155            }
16156
16157            if (ps.frozen) {
16158                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16159                        "Failed to move already frozen package");
16160            }
16161            ps.frozen = true;
16162
16163            codeFile = new File(pkg.codePath);
16164            installerPackageName = ps.installerPackageName;
16165            packageAbiOverride = ps.cpuAbiOverrideString;
16166            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16167            seinfo = pkg.applicationInfo.seinfo;
16168            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16169        }
16170
16171        // Now that we're guarded by frozen state, kill app during move
16172        final long token = Binder.clearCallingIdentity();
16173        try {
16174            killApplication(packageName, appId, "move pkg");
16175        } finally {
16176            Binder.restoreCallingIdentity(token);
16177        }
16178
16179        final Bundle extras = new Bundle();
16180        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16181        extras.putString(Intent.EXTRA_TITLE, label);
16182        mMoveCallbacks.notifyCreated(moveId, extras);
16183
16184        int installFlags;
16185        final boolean moveCompleteApp;
16186        final File measurePath;
16187
16188        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16189            installFlags = INSTALL_INTERNAL;
16190            moveCompleteApp = !currentAsec;
16191            measurePath = Environment.getDataAppDirectory(volumeUuid);
16192        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16193            installFlags = INSTALL_EXTERNAL;
16194            moveCompleteApp = false;
16195            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16196        } else {
16197            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16198            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16199                    || !volume.isMountedWritable()) {
16200                unfreezePackage(packageName);
16201                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16202                        "Move location not mounted private volume");
16203            }
16204
16205            Preconditions.checkState(!currentAsec);
16206
16207            installFlags = INSTALL_INTERNAL;
16208            moveCompleteApp = true;
16209            measurePath = Environment.getDataAppDirectory(volumeUuid);
16210        }
16211
16212        final PackageStats stats = new PackageStats(null, -1);
16213        synchronized (mInstaller) {
16214            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16215                unfreezePackage(packageName);
16216                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16217                        "Failed to measure package size");
16218            }
16219        }
16220
16221        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16222                + stats.dataSize);
16223
16224        final long startFreeBytes = measurePath.getFreeSpace();
16225        final long sizeBytes;
16226        if (moveCompleteApp) {
16227            sizeBytes = stats.codeSize + stats.dataSize;
16228        } else {
16229            sizeBytes = stats.codeSize;
16230        }
16231
16232        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16233            unfreezePackage(packageName);
16234            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16235                    "Not enough free space to move");
16236        }
16237
16238        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16239
16240        final CountDownLatch installedLatch = new CountDownLatch(1);
16241        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16242            @Override
16243            public void onUserActionRequired(Intent intent) throws RemoteException {
16244                throw new IllegalStateException();
16245            }
16246
16247            @Override
16248            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16249                    Bundle extras) throws RemoteException {
16250                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16251                        + PackageManager.installStatusToString(returnCode, msg));
16252
16253                installedLatch.countDown();
16254
16255                // Regardless of success or failure of the move operation,
16256                // always unfreeze the package
16257                unfreezePackage(packageName);
16258
16259                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16260                switch (status) {
16261                    case PackageInstaller.STATUS_SUCCESS:
16262                        mMoveCallbacks.notifyStatusChanged(moveId,
16263                                PackageManager.MOVE_SUCCEEDED);
16264                        break;
16265                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16266                        mMoveCallbacks.notifyStatusChanged(moveId,
16267                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16268                        break;
16269                    default:
16270                        mMoveCallbacks.notifyStatusChanged(moveId,
16271                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16272                        break;
16273                }
16274            }
16275        };
16276
16277        final MoveInfo move;
16278        if (moveCompleteApp) {
16279            // Kick off a thread to report progress estimates
16280            new Thread() {
16281                @Override
16282                public void run() {
16283                    while (true) {
16284                        try {
16285                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16286                                break;
16287                            }
16288                        } catch (InterruptedException ignored) {
16289                        }
16290
16291                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16292                        final int progress = 10 + (int) MathUtils.constrain(
16293                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16294                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16295                    }
16296                }
16297            }.start();
16298
16299            final String dataAppName = codeFile.getName();
16300            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16301                    dataAppName, appId, seinfo);
16302        } else {
16303            move = null;
16304        }
16305
16306        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16307
16308        final Message msg = mHandler.obtainMessage(INIT_COPY);
16309        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16310        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16311                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16312        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16313        msg.obj = params;
16314
16315        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16316                System.identityHashCode(msg.obj));
16317        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16318                System.identityHashCode(msg.obj));
16319
16320        mHandler.sendMessage(msg);
16321    }
16322
16323    @Override
16324    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16325        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16326
16327        final int realMoveId = mNextMoveId.getAndIncrement();
16328        final Bundle extras = new Bundle();
16329        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16330        mMoveCallbacks.notifyCreated(realMoveId, extras);
16331
16332        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16333            @Override
16334            public void onCreated(int moveId, Bundle extras) {
16335                // Ignored
16336            }
16337
16338            @Override
16339            public void onStatusChanged(int moveId, int status, long estMillis) {
16340                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16341            }
16342        };
16343
16344        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16345        storage.setPrimaryStorageUuid(volumeUuid, callback);
16346        return realMoveId;
16347    }
16348
16349    @Override
16350    public int getMoveStatus(int moveId) {
16351        mContext.enforceCallingOrSelfPermission(
16352                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16353        return mMoveCallbacks.mLastStatus.get(moveId);
16354    }
16355
16356    @Override
16357    public void registerMoveCallback(IPackageMoveObserver callback) {
16358        mContext.enforceCallingOrSelfPermission(
16359                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16360        mMoveCallbacks.register(callback);
16361    }
16362
16363    @Override
16364    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16365        mContext.enforceCallingOrSelfPermission(
16366                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16367        mMoveCallbacks.unregister(callback);
16368    }
16369
16370    @Override
16371    public boolean setInstallLocation(int loc) {
16372        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16373                null);
16374        if (getInstallLocation() == loc) {
16375            return true;
16376        }
16377        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16378                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16379            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16380                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16381            return true;
16382        }
16383        return false;
16384   }
16385
16386    @Override
16387    public int getInstallLocation() {
16388        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16389                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16390                PackageHelper.APP_INSTALL_AUTO);
16391    }
16392
16393    /** Called by UserManagerService */
16394    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16395        mDirtyUsers.remove(userHandle);
16396        mSettings.removeUserLPw(userHandle);
16397        mPendingBroadcasts.remove(userHandle);
16398        if (mInstaller != null) {
16399            // Technically, we shouldn't be doing this with the package lock
16400            // held.  However, this is very rare, and there is already so much
16401            // other disk I/O going on, that we'll let it slide for now.
16402            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16403            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16404                final String volumeUuid = vol.getFsUuid();
16405                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16406                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16407            }
16408        }
16409        mUserNeedsBadging.delete(userHandle);
16410        removeUnusedPackagesLILPw(userManager, userHandle);
16411    }
16412
16413    /**
16414     * We're removing userHandle and would like to remove any downloaded packages
16415     * that are no longer in use by any other user.
16416     * @param userHandle the user being removed
16417     */
16418    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16419        final boolean DEBUG_CLEAN_APKS = false;
16420        int [] users = userManager.getUserIdsLPr();
16421        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16422        while (psit.hasNext()) {
16423            PackageSetting ps = psit.next();
16424            if (ps.pkg == null) {
16425                continue;
16426            }
16427            final String packageName = ps.pkg.packageName;
16428            // Skip over if system app
16429            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16430                continue;
16431            }
16432            if (DEBUG_CLEAN_APKS) {
16433                Slog.i(TAG, "Checking package " + packageName);
16434            }
16435            boolean keep = false;
16436            for (int i = 0; i < users.length; i++) {
16437                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16438                    keep = true;
16439                    if (DEBUG_CLEAN_APKS) {
16440                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16441                                + users[i]);
16442                    }
16443                    break;
16444                }
16445            }
16446            if (!keep) {
16447                if (DEBUG_CLEAN_APKS) {
16448                    Slog.i(TAG, "  Removing package " + packageName);
16449                }
16450                mHandler.post(new Runnable() {
16451                    public void run() {
16452                        deletePackageX(packageName, userHandle, 0);
16453                    } //end run
16454                });
16455            }
16456        }
16457    }
16458
16459    /** Called by UserManagerService */
16460    void createNewUserLILPw(int userHandle) {
16461        if (mInstaller != null) {
16462            mInstaller.createUserConfig(userHandle);
16463            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16464            applyFactoryDefaultBrowserLPw(userHandle);
16465            primeDomainVerificationsLPw(userHandle);
16466        }
16467    }
16468
16469    void newUserCreated(final int userHandle) {
16470        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16471    }
16472
16473    @Override
16474    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16475        mContext.enforceCallingOrSelfPermission(
16476                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16477                "Only package verification agents can read the verifier device identity");
16478
16479        synchronized (mPackages) {
16480            return mSettings.getVerifierDeviceIdentityLPw();
16481        }
16482    }
16483
16484    @Override
16485    public void setPermissionEnforced(String permission, boolean enforced) {
16486        // TODO: Now that we no longer change GID for storage, this should to away.
16487        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16488                "setPermissionEnforced");
16489        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16490            synchronized (mPackages) {
16491                if (mSettings.mReadExternalStorageEnforced == null
16492                        || mSettings.mReadExternalStorageEnforced != enforced) {
16493                    mSettings.mReadExternalStorageEnforced = enforced;
16494                    mSettings.writeLPr();
16495                }
16496            }
16497            // kill any non-foreground processes so we restart them and
16498            // grant/revoke the GID.
16499            final IActivityManager am = ActivityManagerNative.getDefault();
16500            if (am != null) {
16501                final long token = Binder.clearCallingIdentity();
16502                try {
16503                    am.killProcessesBelowForeground("setPermissionEnforcement");
16504                } catch (RemoteException e) {
16505                } finally {
16506                    Binder.restoreCallingIdentity(token);
16507                }
16508            }
16509        } else {
16510            throw new IllegalArgumentException("No selective enforcement for " + permission);
16511        }
16512    }
16513
16514    @Override
16515    @Deprecated
16516    public boolean isPermissionEnforced(String permission) {
16517        return true;
16518    }
16519
16520    @Override
16521    public boolean isStorageLow() {
16522        final long token = Binder.clearCallingIdentity();
16523        try {
16524            final DeviceStorageMonitorInternal
16525                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16526            if (dsm != null) {
16527                return dsm.isMemoryLow();
16528            } else {
16529                return false;
16530            }
16531        } finally {
16532            Binder.restoreCallingIdentity(token);
16533        }
16534    }
16535
16536    @Override
16537    public IPackageInstaller getPackageInstaller() {
16538        return mInstallerService;
16539    }
16540
16541    private boolean userNeedsBadging(int userId) {
16542        int index = mUserNeedsBadging.indexOfKey(userId);
16543        if (index < 0) {
16544            final UserInfo userInfo;
16545            final long token = Binder.clearCallingIdentity();
16546            try {
16547                userInfo = sUserManager.getUserInfo(userId);
16548            } finally {
16549                Binder.restoreCallingIdentity(token);
16550            }
16551            final boolean b;
16552            if (userInfo != null && userInfo.isManagedProfile()) {
16553                b = true;
16554            } else {
16555                b = false;
16556            }
16557            mUserNeedsBadging.put(userId, b);
16558            return b;
16559        }
16560        return mUserNeedsBadging.valueAt(index);
16561    }
16562
16563    @Override
16564    public KeySet getKeySetByAlias(String packageName, String alias) {
16565        if (packageName == null || alias == null) {
16566            return null;
16567        }
16568        synchronized(mPackages) {
16569            final PackageParser.Package pkg = mPackages.get(packageName);
16570            if (pkg == null) {
16571                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16572                throw new IllegalArgumentException("Unknown package: " + packageName);
16573            }
16574            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16575            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16576        }
16577    }
16578
16579    @Override
16580    public KeySet getSigningKeySet(String packageName) {
16581        if (packageName == null) {
16582            return null;
16583        }
16584        synchronized(mPackages) {
16585            final PackageParser.Package pkg = mPackages.get(packageName);
16586            if (pkg == null) {
16587                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16588                throw new IllegalArgumentException("Unknown package: " + packageName);
16589            }
16590            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16591                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16592                throw new SecurityException("May not access signing KeySet of other apps.");
16593            }
16594            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16595            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16596        }
16597    }
16598
16599    @Override
16600    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16601        if (packageName == null || ks == null) {
16602            return false;
16603        }
16604        synchronized(mPackages) {
16605            final PackageParser.Package pkg = mPackages.get(packageName);
16606            if (pkg == null) {
16607                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16608                throw new IllegalArgumentException("Unknown package: " + packageName);
16609            }
16610            IBinder ksh = ks.getToken();
16611            if (ksh instanceof KeySetHandle) {
16612                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16613                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16614            }
16615            return false;
16616        }
16617    }
16618
16619    @Override
16620    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16621        if (packageName == null || ks == null) {
16622            return false;
16623        }
16624        synchronized(mPackages) {
16625            final PackageParser.Package pkg = mPackages.get(packageName);
16626            if (pkg == null) {
16627                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16628                throw new IllegalArgumentException("Unknown package: " + packageName);
16629            }
16630            IBinder ksh = ks.getToken();
16631            if (ksh instanceof KeySetHandle) {
16632                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16633                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16634            }
16635            return false;
16636        }
16637    }
16638
16639    public void getUsageStatsIfNoPackageUsageInfo() {
16640        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16641            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16642            if (usm == null) {
16643                throw new IllegalStateException("UsageStatsManager must be initialized");
16644            }
16645            long now = System.currentTimeMillis();
16646            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16647            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16648                String packageName = entry.getKey();
16649                PackageParser.Package pkg = mPackages.get(packageName);
16650                if (pkg == null) {
16651                    continue;
16652                }
16653                UsageStats usage = entry.getValue();
16654                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16655                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16656            }
16657        }
16658    }
16659
16660    /**
16661     * Check and throw if the given before/after packages would be considered a
16662     * downgrade.
16663     */
16664    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16665            throws PackageManagerException {
16666        if (after.versionCode < before.mVersionCode) {
16667            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16668                    "Update version code " + after.versionCode + " is older than current "
16669                    + before.mVersionCode);
16670        } else if (after.versionCode == before.mVersionCode) {
16671            if (after.baseRevisionCode < before.baseRevisionCode) {
16672                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16673                        "Update base revision code " + after.baseRevisionCode
16674                        + " is older than current " + before.baseRevisionCode);
16675            }
16676
16677            if (!ArrayUtils.isEmpty(after.splitNames)) {
16678                for (int i = 0; i < after.splitNames.length; i++) {
16679                    final String splitName = after.splitNames[i];
16680                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16681                    if (j != -1) {
16682                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16683                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16684                                    "Update split " + splitName + " revision code "
16685                                    + after.splitRevisionCodes[i] + " is older than current "
16686                                    + before.splitRevisionCodes[j]);
16687                        }
16688                    }
16689                }
16690            }
16691        }
16692    }
16693
16694    private static class MoveCallbacks extends Handler {
16695        private static final int MSG_CREATED = 1;
16696        private static final int MSG_STATUS_CHANGED = 2;
16697
16698        private final RemoteCallbackList<IPackageMoveObserver>
16699                mCallbacks = new RemoteCallbackList<>();
16700
16701        private final SparseIntArray mLastStatus = new SparseIntArray();
16702
16703        public MoveCallbacks(Looper looper) {
16704            super(looper);
16705        }
16706
16707        public void register(IPackageMoveObserver callback) {
16708            mCallbacks.register(callback);
16709        }
16710
16711        public void unregister(IPackageMoveObserver callback) {
16712            mCallbacks.unregister(callback);
16713        }
16714
16715        @Override
16716        public void handleMessage(Message msg) {
16717            final SomeArgs args = (SomeArgs) msg.obj;
16718            final int n = mCallbacks.beginBroadcast();
16719            for (int i = 0; i < n; i++) {
16720                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16721                try {
16722                    invokeCallback(callback, msg.what, args);
16723                } catch (RemoteException ignored) {
16724                }
16725            }
16726            mCallbacks.finishBroadcast();
16727            args.recycle();
16728        }
16729
16730        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16731                throws RemoteException {
16732            switch (what) {
16733                case MSG_CREATED: {
16734                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16735                    break;
16736                }
16737                case MSG_STATUS_CHANGED: {
16738                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16739                    break;
16740                }
16741            }
16742        }
16743
16744        private void notifyCreated(int moveId, Bundle extras) {
16745            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16746
16747            final SomeArgs args = SomeArgs.obtain();
16748            args.argi1 = moveId;
16749            args.arg2 = extras;
16750            obtainMessage(MSG_CREATED, args).sendToTarget();
16751        }
16752
16753        private void notifyStatusChanged(int moveId, int status) {
16754            notifyStatusChanged(moveId, status, -1);
16755        }
16756
16757        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16758            Slog.v(TAG, "Move " + moveId + " status " + status);
16759
16760            final SomeArgs args = SomeArgs.obtain();
16761            args.argi1 = moveId;
16762            args.argi2 = status;
16763            args.arg3 = estMillis;
16764            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16765
16766            synchronized (mLastStatus) {
16767                mLastStatus.put(moveId, status);
16768            }
16769        }
16770    }
16771
16772    private final class OnPermissionChangeListeners extends Handler {
16773        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16774
16775        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16776                new RemoteCallbackList<>();
16777
16778        public OnPermissionChangeListeners(Looper looper) {
16779            super(looper);
16780        }
16781
16782        @Override
16783        public void handleMessage(Message msg) {
16784            switch (msg.what) {
16785                case MSG_ON_PERMISSIONS_CHANGED: {
16786                    final int uid = msg.arg1;
16787                    handleOnPermissionsChanged(uid);
16788                } break;
16789            }
16790        }
16791
16792        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16793            mPermissionListeners.register(listener);
16794
16795        }
16796
16797        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16798            mPermissionListeners.unregister(listener);
16799        }
16800
16801        public void onPermissionsChanged(int uid) {
16802            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16803                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16804            }
16805        }
16806
16807        private void handleOnPermissionsChanged(int uid) {
16808            final int count = mPermissionListeners.beginBroadcast();
16809            try {
16810                for (int i = 0; i < count; i++) {
16811                    IOnPermissionsChangeListener callback = mPermissionListeners
16812                            .getBroadcastItem(i);
16813                    try {
16814                        callback.onPermissionsChanged(uid);
16815                    } catch (RemoteException e) {
16816                        Log.e(TAG, "Permission listener is dead", e);
16817                    }
16818                }
16819            } finally {
16820                mPermissionListeners.finishBroadcast();
16821            }
16822        }
16823    }
16824
16825    private class PackageManagerInternalImpl extends PackageManagerInternal {
16826        @Override
16827        public void setLocationPackagesProvider(PackagesProvider provider) {
16828            synchronized (mPackages) {
16829                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16830            }
16831        }
16832
16833        @Override
16834        public void setImePackagesProvider(PackagesProvider provider) {
16835            synchronized (mPackages) {
16836                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16837            }
16838        }
16839
16840        @Override
16841        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16842            synchronized (mPackages) {
16843                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16844            }
16845        }
16846
16847        @Override
16848        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16849            synchronized (mPackages) {
16850                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16851            }
16852        }
16853
16854        @Override
16855        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16856            synchronized (mPackages) {
16857                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16858            }
16859        }
16860
16861        @Override
16862        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16863            synchronized (mPackages) {
16864                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16865            }
16866        }
16867
16868        @Override
16869        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16870            synchronized (mPackages) {
16871                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16872            }
16873        }
16874
16875        @Override
16876        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16877            synchronized (mPackages) {
16878                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16879                        packageName, userId);
16880            }
16881        }
16882
16883        @Override
16884        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16885            synchronized (mPackages) {
16886                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16887                        packageName, userId);
16888            }
16889        }
16890        @Override
16891        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16892            synchronized (mPackages) {
16893                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16894                        packageName, userId);
16895            }
16896        }
16897    }
16898
16899    @Override
16900    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16901        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16902        synchronized (mPackages) {
16903            final long identity = Binder.clearCallingIdentity();
16904            try {
16905                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16906                        packageNames, userId);
16907            } finally {
16908                Binder.restoreCallingIdentity(identity);
16909            }
16910        }
16911    }
16912
16913    private static void enforceSystemOrPhoneCaller(String tag) {
16914        int callingUid = Binder.getCallingUid();
16915        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16916            throw new SecurityException(
16917                    "Cannot call " + tag + " from UID " + callingUid);
16918        }
16919    }
16920}
16921