PackageManagerService.java revision 4c515357e5aad1b500ac07ebdbee9d08dc37c927
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
33import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
53import static android.content.pm.PackageManager.INSTALL_INTERNAL;
54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
60import static android.content.pm.PackageManager.MATCH_ALL;
61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
65import static android.content.pm.PackageManager.PERMISSION_DENIED;
66import static android.content.pm.PackageManager.PERMISSION_GRANTED;
67import static android.content.pm.PackageParser.isApkFile;
68import static android.os.Process.PACKAGE_INFO_GID;
69import static android.os.Process.SYSTEM_UID;
70import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
71import static android.system.OsConstants.O_CREAT;
72import static android.system.OsConstants.O_RDWR;
73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
74import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
75import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
76import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
77import static com.android.internal.util.ArrayUtils.appendInt;
78import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
79import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
80import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
81import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
82import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
83import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
87
88import android.Manifest;
89import android.app.ActivityManager;
90import android.app.ActivityManagerNative;
91import android.app.AppGlobals;
92import android.app.IActivityManager;
93import android.app.admin.IDevicePolicyManager;
94import android.app.backup.IBackupManager;
95import android.app.usage.UsageStats;
96import android.app.usage.UsageStatsManager;
97import android.content.BroadcastReceiver;
98import android.content.ComponentName;
99import android.content.Context;
100import android.content.IIntentReceiver;
101import android.content.Intent;
102import android.content.IntentFilter;
103import android.content.IntentSender;
104import android.content.IntentSender.SendIntentException;
105import android.content.ServiceConnection;
106import android.content.pm.ActivityInfo;
107import android.content.pm.ApplicationInfo;
108import android.content.pm.FeatureInfo;
109import android.content.pm.IOnPermissionsChangeListener;
110import android.content.pm.IPackageDataObserver;
111import android.content.pm.IPackageDeleteObserver;
112import android.content.pm.IPackageDeleteObserver2;
113import android.content.pm.IPackageInstallObserver2;
114import android.content.pm.IPackageInstaller;
115import android.content.pm.IPackageManager;
116import android.content.pm.IPackageMoveObserver;
117import android.content.pm.IPackageStatsObserver;
118import android.content.pm.InstrumentationInfo;
119import android.content.pm.IntentFilterVerificationInfo;
120import android.content.pm.KeySet;
121import android.content.pm.ManifestDigest;
122import android.content.pm.PackageCleanItem;
123import android.content.pm.PackageInfo;
124import android.content.pm.PackageInfoLite;
125import android.content.pm.PackageInstaller;
126import android.content.pm.PackageManager;
127import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
128import android.content.pm.PackageManagerInternal;
129import android.content.pm.PackageParser;
130import android.content.pm.PackageParser.ActivityIntentInfo;
131import android.content.pm.PackageParser.PackageLite;
132import android.content.pm.PackageParser.PackageParserException;
133import android.content.pm.PackageStats;
134import android.content.pm.PackageUserState;
135import android.content.pm.ParceledListSlice;
136import android.content.pm.PermissionGroupInfo;
137import android.content.pm.PermissionInfo;
138import android.content.pm.ProviderInfo;
139import android.content.pm.ResolveInfo;
140import android.content.pm.ServiceInfo;
141import android.content.pm.Signature;
142import android.content.pm.UserInfo;
143import android.content.pm.VerificationParams;
144import android.content.pm.VerifierDeviceIdentity;
145import android.content.pm.VerifierInfo;
146import android.content.res.Resources;
147import android.hardware.display.DisplayManager;
148import android.net.Uri;
149import android.os.Debug;
150import android.os.Binder;
151import android.os.Build;
152import android.os.Bundle;
153import android.os.Environment;
154import android.os.Environment.UserEnvironment;
155import android.os.FileUtils;
156import android.os.Handler;
157import android.os.IBinder;
158import android.os.Looper;
159import android.os.Message;
160import android.os.Parcel;
161import android.os.ParcelFileDescriptor;
162import android.os.Process;
163import android.os.RemoteCallbackList;
164import android.os.RemoteException;
165import android.os.ResultReceiver;
166import android.os.SELinux;
167import android.os.ServiceManager;
168import android.os.SystemClock;
169import android.os.SystemProperties;
170import android.os.Trace;
171import android.os.UserHandle;
172import android.os.UserManager;
173import android.os.storage.IMountService;
174import android.os.storage.MountServiceInternal;
175import android.os.storage.StorageEventListener;
176import android.os.storage.StorageManager;
177import android.os.storage.VolumeInfo;
178import android.os.storage.VolumeRecord;
179import android.security.KeyStore;
180import android.security.SystemKeyStore;
181import android.system.ErrnoException;
182import android.system.Os;
183import android.system.StructStat;
184import android.text.TextUtils;
185import android.text.format.DateUtils;
186import android.util.ArrayMap;
187import android.util.ArraySet;
188import android.util.AtomicFile;
189import android.util.DisplayMetrics;
190import android.util.EventLog;
191import android.util.ExceptionUtils;
192import android.util.Log;
193import android.util.LogPrinter;
194import android.util.MathUtils;
195import android.util.PrintStreamPrinter;
196import android.util.Slog;
197import android.util.SparseArray;
198import android.util.SparseBooleanArray;
199import android.util.SparseIntArray;
200import android.util.Xml;
201import android.view.Display;
202
203import dalvik.system.DexFile;
204import dalvik.system.VMRuntime;
205
206import libcore.io.IoUtils;
207import libcore.util.EmptyArray;
208
209import com.android.internal.R;
210import com.android.internal.annotations.GuardedBy;
211import com.android.internal.app.IMediaContainerService;
212import com.android.internal.app.ResolverActivity;
213import com.android.internal.content.NativeLibraryHelper;
214import com.android.internal.content.PackageHelper;
215import com.android.internal.os.IParcelFileDescriptorFactory;
216import com.android.internal.os.SomeArgs;
217import com.android.internal.os.Zygote;
218import com.android.internal.util.ArrayUtils;
219import com.android.internal.util.FastPrintWriter;
220import com.android.internal.util.FastXmlSerializer;
221import com.android.internal.util.IndentingPrintWriter;
222import com.android.internal.util.Preconditions;
223import com.android.server.EventLogTags;
224import com.android.server.FgThread;
225import com.android.server.IntentResolver;
226import com.android.server.LocalServices;
227import com.android.server.ServiceThread;
228import com.android.server.SystemConfig;
229import com.android.server.Watchdog;
230import com.android.server.pm.PermissionsState.PermissionState;
231import com.android.server.pm.Settings.DatabaseVersion;
232import com.android.server.pm.Settings.VersionInfo;
233import com.android.server.storage.DeviceStorageMonitorInternal;
234
235import org.xmlpull.v1.XmlPullParser;
236import org.xmlpull.v1.XmlPullParserException;
237import org.xmlpull.v1.XmlSerializer;
238
239import java.io.BufferedInputStream;
240import java.io.BufferedOutputStream;
241import java.io.BufferedReader;
242import java.io.ByteArrayInputStream;
243import java.io.ByteArrayOutputStream;
244import java.io.File;
245import java.io.FileDescriptor;
246import java.io.FileNotFoundException;
247import java.io.FileOutputStream;
248import java.io.FileReader;
249import java.io.FilenameFilter;
250import java.io.IOException;
251import java.io.InputStream;
252import java.io.PrintWriter;
253import java.nio.charset.StandardCharsets;
254import java.security.NoSuchAlgorithmException;
255import java.security.PublicKey;
256import java.security.cert.CertificateEncodingException;
257import java.security.cert.CertificateException;
258import java.text.SimpleDateFormat;
259import java.util.ArrayList;
260import java.util.Arrays;
261import java.util.Collection;
262import java.util.Collections;
263import java.util.Comparator;
264import java.util.Date;
265import java.util.Iterator;
266import java.util.List;
267import java.util.Map;
268import java.util.Objects;
269import java.util.Set;
270import java.util.concurrent.CountDownLatch;
271import java.util.concurrent.TimeUnit;
272import java.util.concurrent.atomic.AtomicBoolean;
273import java.util.concurrent.atomic.AtomicInteger;
274import java.util.concurrent.atomic.AtomicLong;
275
276/**
277 * Keep track of all those .apks everywhere.
278 *
279 * This is very central to the platform's security; please run the unit
280 * tests whenever making modifications here:
281 *
282runtest -c android.content.pm.PackageManagerTests frameworks-core
283 *
284 * {@hide}
285 */
286public class PackageManagerService extends IPackageManager.Stub {
287    static final String TAG = "PackageManager";
288    static final boolean DEBUG_SETTINGS = false;
289    static final boolean DEBUG_PREFERRED = false;
290    static final boolean DEBUG_UPGRADE = false;
291    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
292    private static final boolean DEBUG_BACKUP = false;
293    private static final boolean DEBUG_INSTALL = false;
294    private static final boolean DEBUG_REMOVE = false;
295    private static final boolean DEBUG_BROADCASTS = false;
296    private static final boolean DEBUG_SHOW_INFO = false;
297    private static final boolean DEBUG_PACKAGE_INFO = false;
298    private static final boolean DEBUG_INTENT_MATCHING = false;
299    private static final boolean DEBUG_PACKAGE_SCANNING = false;
300    private static final boolean DEBUG_VERIFY = false;
301    private static final boolean DEBUG_DEXOPT = false;
302    private static final boolean DEBUG_ABI_SELECTION = false;
303
304    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
305
306    private static final int RADIO_UID = Process.PHONE_UID;
307    private static final int LOG_UID = Process.LOG_UID;
308    private static final int NFC_UID = Process.NFC_UID;
309    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
310    private static final int SHELL_UID = Process.SHELL_UID;
311
312    // Cap the size of permission trees that 3rd party apps can define
313    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
314
315    // Suffix used during package installation when copying/moving
316    // package apks to install directory.
317    private static final String INSTALL_PACKAGE_SUFFIX = "-";
318
319    static final int SCAN_NO_DEX = 1<<1;
320    static final int SCAN_FORCE_DEX = 1<<2;
321    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
322    static final int SCAN_NEW_INSTALL = 1<<4;
323    static final int SCAN_NO_PATHS = 1<<5;
324    static final int SCAN_UPDATE_TIME = 1<<6;
325    static final int SCAN_DEFER_DEX = 1<<7;
326    static final int SCAN_BOOTING = 1<<8;
327    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
328    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
329    static final int SCAN_REPLACING = 1<<11;
330    static final int SCAN_REQUIRE_KNOWN = 1<<12;
331    static final int SCAN_MOVE = 1<<13;
332    static final int SCAN_INITIAL = 1<<14;
333
334    static final int REMOVE_CHATTY = 1<<16;
335
336    private static final int[] EMPTY_INT_ARRAY = new int[0];
337
338    /**
339     * Timeout (in milliseconds) after which the watchdog should declare that
340     * our handler thread is wedged.  The usual default for such things is one
341     * minute but we sometimes do very lengthy I/O operations on this thread,
342     * such as installing multi-gigabyte applications, so ours needs to be longer.
343     */
344    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
345
346    /**
347     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
348     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
349     * settings entry if available, otherwise we use the hardcoded default.  If it's been
350     * more than this long since the last fstrim, we force one during the boot sequence.
351     *
352     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
353     * one gets run at the next available charging+idle time.  This final mandatory
354     * no-fstrim check kicks in only of the other scheduling criteria is never met.
355     */
356    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
357
358    /**
359     * Whether verification is enabled by default.
360     */
361    private static final boolean DEFAULT_VERIFY_ENABLE = true;
362
363    /**
364     * The default maximum time to wait for the verification agent to return in
365     * milliseconds.
366     */
367    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
368
369    /**
370     * The default response for package verification timeout.
371     *
372     * This can be either PackageManager.VERIFICATION_ALLOW or
373     * PackageManager.VERIFICATION_REJECT.
374     */
375    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
376
377    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
378
379    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
380            DEFAULT_CONTAINER_PACKAGE,
381            "com.android.defcontainer.DefaultContainerService");
382
383    private static final String KILL_APP_REASON_GIDS_CHANGED =
384            "permission grant or revoke changed gids";
385
386    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
387            "permissions revoked";
388
389    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
390
391    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
392
393    /** Permission grant: not grant the permission. */
394    private static final int GRANT_DENIED = 1;
395
396    /** Permission grant: grant the permission as an install permission. */
397    private static final int GRANT_INSTALL = 2;
398
399    /** Permission grant: grant the permission as an install permission for a legacy app. */
400    private static final int GRANT_INSTALL_LEGACY = 3;
401
402    /** Permission grant: grant the permission as a runtime one. */
403    private static final int GRANT_RUNTIME = 4;
404
405    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
406    private static final int GRANT_UPGRADE = 5;
407
408    /** Canonical intent used to identify what counts as a "web browser" app */
409    private static final Intent sBrowserIntent;
410    static {
411        sBrowserIntent = new Intent();
412        sBrowserIntent.setAction(Intent.ACTION_VIEW);
413        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
414        sBrowserIntent.setData(Uri.parse("http:"));
415    }
416
417    final ServiceThread mHandlerThread;
418
419    final PackageHandler mHandler;
420
421    /**
422     * Messages for {@link #mHandler} that need to wait for system ready before
423     * being dispatched.
424     */
425    private ArrayList<Message> mPostSystemReadyMessages;
426
427    final int mSdkVersion = Build.VERSION.SDK_INT;
428
429    final Context mContext;
430    final boolean mFactoryTest;
431    final boolean mOnlyCore;
432    final boolean mLazyDexOpt;
433    final long mDexOptLRUThresholdInMills;
434    final DisplayMetrics mMetrics;
435    final int mDefParseFlags;
436    final String[] mSeparateProcesses;
437    final boolean mIsUpgrade;
438
439    // This is where all application persistent data goes.
440    final File mAppDataDir;
441
442    // This is where all application persistent data goes for secondary users.
443    final File mUserAppDataDir;
444
445    /** The location for ASEC container files on internal storage. */
446    final String mAsecInternalPath;
447
448    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
449    // LOCK HELD.  Can be called with mInstallLock held.
450    @GuardedBy("mInstallLock")
451    final Installer mInstaller;
452
453    /** Directory where installed third-party apps stored */
454    final File mAppInstallDir;
455
456    /**
457     * Directory to which applications installed internally have their
458     * 32 bit native libraries copied.
459     */
460    private File mAppLib32InstallDir;
461
462    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
463    // apps.
464    final File mDrmAppPrivateInstallDir;
465
466    // ----------------------------------------------------------------
467
468    // Lock for state used when installing and doing other long running
469    // operations.  Methods that must be called with this lock held have
470    // the suffix "LI".
471    final Object mInstallLock = new Object();
472
473    // ----------------------------------------------------------------
474
475    // Keys are String (package name), values are Package.  This also serves
476    // as the lock for the global state.  Methods that must be called with
477    // this lock held have the prefix "LP".
478    @GuardedBy("mPackages")
479    final ArrayMap<String, PackageParser.Package> mPackages =
480            new ArrayMap<String, PackageParser.Package>();
481
482    // Tracks available target package names -> overlay package paths.
483    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
484        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
485
486    /**
487     * Tracks new system packages [received in an OTA] that we expect to
488     * find updated user-installed versions. Keys are package name, values
489     * are package location.
490     */
491    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
492
493    /**
494     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
495     */
496    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
497    /**
498     * Whether or not system app permissions should be promoted from install to runtime.
499     */
500    boolean mPromoteSystemApps;
501
502    final Settings mSettings;
503    boolean mRestoredSettings;
504
505    // System configuration read by SystemConfig.
506    final int[] mGlobalGids;
507    final SparseArray<ArraySet<String>> mSystemPermissions;
508    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
509
510    // If mac_permissions.xml was found for seinfo labeling.
511    boolean mFoundPolicyFile;
512
513    // If a recursive restorecon of /data/data/<pkg> is needed.
514    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
515
516    public static final class SharedLibraryEntry {
517        public final String path;
518        public final String apk;
519
520        SharedLibraryEntry(String _path, String _apk) {
521            path = _path;
522            apk = _apk;
523        }
524    }
525
526    // Currently known shared libraries.
527    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
528            new ArrayMap<String, SharedLibraryEntry>();
529
530    // All available activities, for your resolving pleasure.
531    final ActivityIntentResolver mActivities =
532            new ActivityIntentResolver();
533
534    // All available receivers, for your resolving pleasure.
535    final ActivityIntentResolver mReceivers =
536            new ActivityIntentResolver();
537
538    // All available services, for your resolving pleasure.
539    final ServiceIntentResolver mServices = new ServiceIntentResolver();
540
541    // All available providers, for your resolving pleasure.
542    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
543
544    // Mapping from provider base names (first directory in content URI codePath)
545    // to the provider information.
546    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
547            new ArrayMap<String, PackageParser.Provider>();
548
549    // Mapping from instrumentation class names to info about them.
550    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
551            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
552
553    // Mapping from permission names to info about them.
554    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
555            new ArrayMap<String, PackageParser.PermissionGroup>();
556
557    // Packages whose data we have transfered into another package, thus
558    // should no longer exist.
559    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
560
561    // Broadcast actions that are only available to the system.
562    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
563
564    /** List of packages waiting for verification. */
565    final SparseArray<PackageVerificationState> mPendingVerification
566            = new SparseArray<PackageVerificationState>();
567
568    /** Set of packages associated with each app op permission. */
569    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
570
571    final PackageInstallerService mInstallerService;
572
573    private final PackageDexOptimizer mPackageDexOptimizer;
574
575    private AtomicInteger mNextMoveId = new AtomicInteger();
576    private final MoveCallbacks mMoveCallbacks;
577
578    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
579
580    // Cache of users who need badging.
581    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
582
583    /** Token for keys in mPendingVerification. */
584    private int mPendingVerificationToken = 0;
585
586    volatile boolean mSystemReady;
587    volatile boolean mSafeMode;
588    volatile boolean mHasSystemUidErrors;
589
590    ApplicationInfo mAndroidApplication;
591    final ActivityInfo mResolveActivity = new ActivityInfo();
592    final ResolveInfo mResolveInfo = new ResolveInfo();
593    ComponentName mResolveComponentName;
594    PackageParser.Package mPlatformPackage;
595    ComponentName mCustomResolverComponentName;
596
597    boolean mResolverReplaced = false;
598
599    private final ComponentName mIntentFilterVerifierComponent;
600    private int mIntentFilterVerificationToken = 0;
601
602    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
603            = new SparseArray<IntentFilterVerificationState>();
604
605    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
606            new DefaultPermissionGrantPolicy(this);
607
608    private static class IFVerificationParams {
609        PackageParser.Package pkg;
610        boolean replacing;
611        int userId;
612        int verifierUid;
613
614        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
615                int _userId, int _verifierUid) {
616            pkg = _pkg;
617            replacing = _replacing;
618            userId = _userId;
619            replacing = _replacing;
620            verifierUid = _verifierUid;
621        }
622    }
623
624    private interface IntentFilterVerifier<T extends IntentFilter> {
625        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
626                                               T filter, String packageName);
627        void startVerifications(int userId);
628        void receiveVerificationResponse(int verificationId);
629    }
630
631    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
632        private Context mContext;
633        private ComponentName mIntentFilterVerifierComponent;
634        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
635
636        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
637            mContext = context;
638            mIntentFilterVerifierComponent = verifierComponent;
639        }
640
641        private String getDefaultScheme() {
642            return IntentFilter.SCHEME_HTTPS;
643        }
644
645        @Override
646        public void startVerifications(int userId) {
647            // Launch verifications requests
648            int count = mCurrentIntentFilterVerifications.size();
649            for (int n=0; n<count; n++) {
650                int verificationId = mCurrentIntentFilterVerifications.get(n);
651                final IntentFilterVerificationState ivs =
652                        mIntentFilterVerificationStates.get(verificationId);
653
654                String packageName = ivs.getPackageName();
655
656                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
657                final int filterCount = filters.size();
658                ArraySet<String> domainsSet = new ArraySet<>();
659                for (int m=0; m<filterCount; m++) {
660                    PackageParser.ActivityIntentInfo filter = filters.get(m);
661                    domainsSet.addAll(filter.getHostsList());
662                }
663                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
664                synchronized (mPackages) {
665                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
666                            packageName, domainsList) != null) {
667                        scheduleWriteSettingsLocked();
668                    }
669                }
670                sendVerificationRequest(userId, verificationId, ivs);
671            }
672            mCurrentIntentFilterVerifications.clear();
673        }
674
675        private void sendVerificationRequest(int userId, int verificationId,
676                IntentFilterVerificationState ivs) {
677
678            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
679            verificationIntent.putExtra(
680                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
681                    verificationId);
682            verificationIntent.putExtra(
683                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
684                    getDefaultScheme());
685            verificationIntent.putExtra(
686                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
687                    ivs.getHostsString());
688            verificationIntent.putExtra(
689                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
690                    ivs.getPackageName());
691            verificationIntent.setComponent(mIntentFilterVerifierComponent);
692            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
693
694            UserHandle user = new UserHandle(userId);
695            mContext.sendBroadcastAsUser(verificationIntent, user);
696            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
697                    "Sending IntentFilter verification broadcast");
698        }
699
700        public void receiveVerificationResponse(int verificationId) {
701            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
702
703            final boolean verified = ivs.isVerified();
704
705            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
706            final int count = filters.size();
707            if (DEBUG_DOMAIN_VERIFICATION) {
708                Slog.i(TAG, "Received verification response " + verificationId
709                        + " for " + count + " filters, verified=" + verified);
710            }
711            for (int n=0; n<count; n++) {
712                PackageParser.ActivityIntentInfo filter = filters.get(n);
713                filter.setVerified(verified);
714
715                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
716                        + " verified with result:" + verified + " and hosts:"
717                        + ivs.getHostsString());
718            }
719
720            mIntentFilterVerificationStates.remove(verificationId);
721
722            final String packageName = ivs.getPackageName();
723            IntentFilterVerificationInfo ivi = null;
724
725            synchronized (mPackages) {
726                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
727            }
728            if (ivi == null) {
729                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
730                        + verificationId + " packageName:" + packageName);
731                return;
732            }
733            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
734                    "Updating IntentFilterVerificationInfo for package " + packageName
735                            +" verificationId:" + verificationId);
736
737            synchronized (mPackages) {
738                if (verified) {
739                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
740                } else {
741                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
742                }
743                scheduleWriteSettingsLocked();
744
745                final int userId = ivs.getUserId();
746                if (userId != UserHandle.USER_ALL) {
747                    final int userStatus =
748                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
749
750                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
751                    boolean needUpdate = false;
752
753                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
754                    // already been set by the User thru the Disambiguation dialog
755                    switch (userStatus) {
756                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
757                            if (verified) {
758                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
759                            } else {
760                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
761                            }
762                            needUpdate = true;
763                            break;
764
765                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
766                            if (verified) {
767                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
768                                needUpdate = true;
769                            }
770                            break;
771
772                        default:
773                            // Nothing to do
774                    }
775
776                    if (needUpdate) {
777                        mSettings.updateIntentFilterVerificationStatusLPw(
778                                packageName, updatedStatus, userId);
779                        scheduleWritePackageRestrictionsLocked(userId);
780                    }
781                }
782            }
783        }
784
785        @Override
786        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
787                    ActivityIntentInfo filter, String packageName) {
788            if (!hasValidDomains(filter)) {
789                return false;
790            }
791            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
792            if (ivs == null) {
793                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
794                        packageName);
795            }
796            if (DEBUG_DOMAIN_VERIFICATION) {
797                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
798            }
799            ivs.addFilter(filter);
800            return true;
801        }
802
803        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
804                int userId, int verificationId, String packageName) {
805            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
806                    verifierUid, userId, packageName);
807            ivs.setPendingState();
808            synchronized (mPackages) {
809                mIntentFilterVerificationStates.append(verificationId, ivs);
810                mCurrentIntentFilterVerifications.add(verificationId);
811            }
812            return ivs;
813        }
814    }
815
816    private static boolean hasValidDomains(ActivityIntentInfo filter) {
817        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
818                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
819                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
820    }
821
822    private IntentFilterVerifier mIntentFilterVerifier;
823
824    // Set of pending broadcasts for aggregating enable/disable of components.
825    static class PendingPackageBroadcasts {
826        // for each user id, a map of <package name -> components within that package>
827        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
828
829        public PendingPackageBroadcasts() {
830            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
831        }
832
833        public ArrayList<String> get(int userId, String packageName) {
834            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
835            return packages.get(packageName);
836        }
837
838        public void put(int userId, String packageName, ArrayList<String> components) {
839            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
840            packages.put(packageName, components);
841        }
842
843        public void remove(int userId, String packageName) {
844            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
845            if (packages != null) {
846                packages.remove(packageName);
847            }
848        }
849
850        public void remove(int userId) {
851            mUidMap.remove(userId);
852        }
853
854        public int userIdCount() {
855            return mUidMap.size();
856        }
857
858        public int userIdAt(int n) {
859            return mUidMap.keyAt(n);
860        }
861
862        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
863            return mUidMap.get(userId);
864        }
865
866        public int size() {
867            // total number of pending broadcast entries across all userIds
868            int num = 0;
869            for (int i = 0; i< mUidMap.size(); i++) {
870                num += mUidMap.valueAt(i).size();
871            }
872            return num;
873        }
874
875        public void clear() {
876            mUidMap.clear();
877        }
878
879        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
880            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
881            if (map == null) {
882                map = new ArrayMap<String, ArrayList<String>>();
883                mUidMap.put(userId, map);
884            }
885            return map;
886        }
887    }
888    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
889
890    // Service Connection to remote media container service to copy
891    // package uri's from external media onto secure containers
892    // or internal storage.
893    private IMediaContainerService mContainerService = null;
894
895    static final int SEND_PENDING_BROADCAST = 1;
896    static final int MCS_BOUND = 3;
897    static final int END_COPY = 4;
898    static final int INIT_COPY = 5;
899    static final int MCS_UNBIND = 6;
900    static final int START_CLEANING_PACKAGE = 7;
901    static final int FIND_INSTALL_LOC = 8;
902    static final int POST_INSTALL = 9;
903    static final int MCS_RECONNECT = 10;
904    static final int MCS_GIVE_UP = 11;
905    static final int UPDATED_MEDIA_STATUS = 12;
906    static final int WRITE_SETTINGS = 13;
907    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
908    static final int PACKAGE_VERIFIED = 15;
909    static final int CHECK_PENDING_VERIFICATION = 16;
910    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
911    static final int INTENT_FILTER_VERIFIED = 18;
912
913    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
914
915    // Delay time in millisecs
916    static final int BROADCAST_DELAY = 10 * 1000;
917
918    static UserManagerService sUserManager;
919
920    // Stores a list of users whose package restrictions file needs to be updated
921    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
922
923    final private DefaultContainerConnection mDefContainerConn =
924            new DefaultContainerConnection();
925    class DefaultContainerConnection implements ServiceConnection {
926        public void onServiceConnected(ComponentName name, IBinder service) {
927            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
928            IMediaContainerService imcs =
929                IMediaContainerService.Stub.asInterface(service);
930            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
931        }
932
933        public void onServiceDisconnected(ComponentName name) {
934            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
935        }
936    }
937
938    // Recordkeeping of restore-after-install operations that are currently in flight
939    // between the Package Manager and the Backup Manager
940    class PostInstallData {
941        public InstallArgs args;
942        public PackageInstalledInfo res;
943
944        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
945            args = _a;
946            res = _r;
947        }
948    }
949
950    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
951    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
952
953    // XML tags for backup/restore of various bits of state
954    private static final String TAG_PREFERRED_BACKUP = "pa";
955    private static final String TAG_DEFAULT_APPS = "da";
956    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
957
958    final String mRequiredVerifierPackage;
959    final String mRequiredInstallerPackage;
960
961    private final PackageUsage mPackageUsage = new PackageUsage();
962
963    private class PackageUsage {
964        private static final int WRITE_INTERVAL
965            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
966
967        private final Object mFileLock = new Object();
968        private final AtomicLong mLastWritten = new AtomicLong(0);
969        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
970
971        private boolean mIsHistoricalPackageUsageAvailable = true;
972
973        boolean isHistoricalPackageUsageAvailable() {
974            return mIsHistoricalPackageUsageAvailable;
975        }
976
977        void write(boolean force) {
978            if (force) {
979                writeInternal();
980                return;
981            }
982            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
983                && !DEBUG_DEXOPT) {
984                return;
985            }
986            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
987                new Thread("PackageUsage_DiskWriter") {
988                    @Override
989                    public void run() {
990                        try {
991                            writeInternal();
992                        } finally {
993                            mBackgroundWriteRunning.set(false);
994                        }
995                    }
996                }.start();
997            }
998        }
999
1000        private void writeInternal() {
1001            synchronized (mPackages) {
1002                synchronized (mFileLock) {
1003                    AtomicFile file = getFile();
1004                    FileOutputStream f = null;
1005                    try {
1006                        f = file.startWrite();
1007                        BufferedOutputStream out = new BufferedOutputStream(f);
1008                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1009                        StringBuilder sb = new StringBuilder();
1010                        for (PackageParser.Package pkg : mPackages.values()) {
1011                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1012                                continue;
1013                            }
1014                            sb.setLength(0);
1015                            sb.append(pkg.packageName);
1016                            sb.append(' ');
1017                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1018                            sb.append('\n');
1019                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1020                        }
1021                        out.flush();
1022                        file.finishWrite(f);
1023                    } catch (IOException e) {
1024                        if (f != null) {
1025                            file.failWrite(f);
1026                        }
1027                        Log.e(TAG, "Failed to write package usage times", e);
1028                    }
1029                }
1030            }
1031            mLastWritten.set(SystemClock.elapsedRealtime());
1032        }
1033
1034        void readLP() {
1035            synchronized (mFileLock) {
1036                AtomicFile file = getFile();
1037                BufferedInputStream in = null;
1038                try {
1039                    in = new BufferedInputStream(file.openRead());
1040                    StringBuffer sb = new StringBuffer();
1041                    while (true) {
1042                        String packageName = readToken(in, sb, ' ');
1043                        if (packageName == null) {
1044                            break;
1045                        }
1046                        String timeInMillisString = readToken(in, sb, '\n');
1047                        if (timeInMillisString == null) {
1048                            throw new IOException("Failed to find last usage time for package "
1049                                                  + packageName);
1050                        }
1051                        PackageParser.Package pkg = mPackages.get(packageName);
1052                        if (pkg == null) {
1053                            continue;
1054                        }
1055                        long timeInMillis;
1056                        try {
1057                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1058                        } catch (NumberFormatException e) {
1059                            throw new IOException("Failed to parse " + timeInMillisString
1060                                                  + " as a long.", e);
1061                        }
1062                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1063                    }
1064                } catch (FileNotFoundException expected) {
1065                    mIsHistoricalPackageUsageAvailable = false;
1066                } catch (IOException e) {
1067                    Log.w(TAG, "Failed to read package usage times", e);
1068                } finally {
1069                    IoUtils.closeQuietly(in);
1070                }
1071            }
1072            mLastWritten.set(SystemClock.elapsedRealtime());
1073        }
1074
1075        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1076                throws IOException {
1077            sb.setLength(0);
1078            while (true) {
1079                int ch = in.read();
1080                if (ch == -1) {
1081                    if (sb.length() == 0) {
1082                        return null;
1083                    }
1084                    throw new IOException("Unexpected EOF");
1085                }
1086                if (ch == endOfToken) {
1087                    return sb.toString();
1088                }
1089                sb.append((char)ch);
1090            }
1091        }
1092
1093        private AtomicFile getFile() {
1094            File dataDir = Environment.getDataDirectory();
1095            File systemDir = new File(dataDir, "system");
1096            File fname = new File(systemDir, "package-usage.list");
1097            return new AtomicFile(fname);
1098        }
1099    }
1100
1101    class PackageHandler extends Handler {
1102        private boolean mBound = false;
1103        final ArrayList<HandlerParams> mPendingInstalls =
1104            new ArrayList<HandlerParams>();
1105
1106        private boolean connectToService() {
1107            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1108                    " DefaultContainerService");
1109            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1110            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1111            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1112                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1113                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1114                mBound = true;
1115                return true;
1116            }
1117            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1118            return false;
1119        }
1120
1121        private void disconnectService() {
1122            mContainerService = null;
1123            mBound = false;
1124            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1125            mContext.unbindService(mDefContainerConn);
1126            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1127        }
1128
1129        PackageHandler(Looper looper) {
1130            super(looper);
1131        }
1132
1133        public void handleMessage(Message msg) {
1134            try {
1135                doHandleMessage(msg);
1136            } finally {
1137                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1138            }
1139        }
1140
1141        void doHandleMessage(Message msg) {
1142            switch (msg.what) {
1143                case INIT_COPY: {
1144                    HandlerParams params = (HandlerParams) msg.obj;
1145                    int idx = mPendingInstalls.size();
1146                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1147                    // If a bind was already initiated we dont really
1148                    // need to do anything. The pending install
1149                    // will be processed later on.
1150                    if (!mBound) {
1151                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1152                                System.identityHashCode(mHandler));
1153                        // If this is the only one pending we might
1154                        // have to bind to the service again.
1155                        if (!connectToService()) {
1156                            Slog.e(TAG, "Failed to bind to media container service");
1157                            params.serviceError();
1158                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1159                                    System.identityHashCode(mHandler));
1160                            if (params.traceMethod != null) {
1161                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1162                                        params.traceCookie);
1163                            }
1164                            return;
1165                        } else {
1166                            // Once we bind to the service, the first
1167                            // pending request will be processed.
1168                            mPendingInstalls.add(idx, params);
1169                        }
1170                    } else {
1171                        mPendingInstalls.add(idx, params);
1172                        // Already bound to the service. Just make
1173                        // sure we trigger off processing the first request.
1174                        if (idx == 0) {
1175                            mHandler.sendEmptyMessage(MCS_BOUND);
1176                        }
1177                    }
1178                    break;
1179                }
1180                case MCS_BOUND: {
1181                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1182                    if (msg.obj != null) {
1183                        mContainerService = (IMediaContainerService) msg.obj;
1184                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1185                                System.identityHashCode(mHandler));
1186                    }
1187                    if (mContainerService == null) {
1188                        if (!mBound) {
1189                            // Something seriously wrong since we are not bound and we are not
1190                            // waiting for connection. Bail out.
1191                            Slog.e(TAG, "Cannot bind to media container service");
1192                            for (HandlerParams params : mPendingInstalls) {
1193                                // Indicate service bind error
1194                                params.serviceError();
1195                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1196                                        System.identityHashCode(params));
1197                                if (params.traceMethod != null) {
1198                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1199                                            params.traceMethod, params.traceCookie);
1200                                }
1201                                return;
1202                            }
1203                            mPendingInstalls.clear();
1204                        } else {
1205                            Slog.w(TAG, "Waiting to connect to media container service");
1206                        }
1207                    } else if (mPendingInstalls.size() > 0) {
1208                        HandlerParams params = mPendingInstalls.get(0);
1209                        if (params != null) {
1210                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1211                                    System.identityHashCode(params));
1212                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1213                            if (params.startCopy()) {
1214                                // We are done...  look for more work or to
1215                                // go idle.
1216                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1217                                        "Checking for more work or unbind...");
1218                                // Delete pending install
1219                                if (mPendingInstalls.size() > 0) {
1220                                    mPendingInstalls.remove(0);
1221                                }
1222                                if (mPendingInstalls.size() == 0) {
1223                                    if (mBound) {
1224                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1225                                                "Posting delayed MCS_UNBIND");
1226                                        removeMessages(MCS_UNBIND);
1227                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1228                                        // Unbind after a little delay, to avoid
1229                                        // continual thrashing.
1230                                        sendMessageDelayed(ubmsg, 10000);
1231                                    }
1232                                } else {
1233                                    // There are more pending requests in queue.
1234                                    // Just post MCS_BOUND message to trigger processing
1235                                    // of next pending install.
1236                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1237                                            "Posting MCS_BOUND for next work");
1238                                    mHandler.sendEmptyMessage(MCS_BOUND);
1239                                }
1240                            }
1241                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1242                        }
1243                    } else {
1244                        // Should never happen ideally.
1245                        Slog.w(TAG, "Empty queue");
1246                    }
1247                    break;
1248                }
1249                case MCS_RECONNECT: {
1250                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1251                    if (mPendingInstalls.size() > 0) {
1252                        if (mBound) {
1253                            disconnectService();
1254                        }
1255                        if (!connectToService()) {
1256                            Slog.e(TAG, "Failed to bind to media container service");
1257                            for (HandlerParams params : mPendingInstalls) {
1258                                // Indicate service bind error
1259                                params.serviceError();
1260                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1261                                        System.identityHashCode(params));
1262                            }
1263                            mPendingInstalls.clear();
1264                        }
1265                    }
1266                    break;
1267                }
1268                case MCS_UNBIND: {
1269                    // If there is no actual work left, then time to unbind.
1270                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1271
1272                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1273                        if (mBound) {
1274                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1275
1276                            disconnectService();
1277                        }
1278                    } else if (mPendingInstalls.size() > 0) {
1279                        // There are more pending requests in queue.
1280                        // Just post MCS_BOUND message to trigger processing
1281                        // of next pending install.
1282                        mHandler.sendEmptyMessage(MCS_BOUND);
1283                    }
1284
1285                    break;
1286                }
1287                case MCS_GIVE_UP: {
1288                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1289                    HandlerParams params = mPendingInstalls.remove(0);
1290                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1291                            System.identityHashCode(params));
1292                    break;
1293                }
1294                case SEND_PENDING_BROADCAST: {
1295                    String packages[];
1296                    ArrayList<String> components[];
1297                    int size = 0;
1298                    int uids[];
1299                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1300                    synchronized (mPackages) {
1301                        if (mPendingBroadcasts == null) {
1302                            return;
1303                        }
1304                        size = mPendingBroadcasts.size();
1305                        if (size <= 0) {
1306                            // Nothing to be done. Just return
1307                            return;
1308                        }
1309                        packages = new String[size];
1310                        components = new ArrayList[size];
1311                        uids = new int[size];
1312                        int i = 0;  // filling out the above arrays
1313
1314                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1315                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1316                            Iterator<Map.Entry<String, ArrayList<String>>> it
1317                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1318                                            .entrySet().iterator();
1319                            while (it.hasNext() && i < size) {
1320                                Map.Entry<String, ArrayList<String>> ent = it.next();
1321                                packages[i] = ent.getKey();
1322                                components[i] = ent.getValue();
1323                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1324                                uids[i] = (ps != null)
1325                                        ? UserHandle.getUid(packageUserId, ps.appId)
1326                                        : -1;
1327                                i++;
1328                            }
1329                        }
1330                        size = i;
1331                        mPendingBroadcasts.clear();
1332                    }
1333                    // Send broadcasts
1334                    for (int i = 0; i < size; i++) {
1335                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1336                    }
1337                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1338                    break;
1339                }
1340                case START_CLEANING_PACKAGE: {
1341                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1342                    final String packageName = (String)msg.obj;
1343                    final int userId = msg.arg1;
1344                    final boolean andCode = msg.arg2 != 0;
1345                    synchronized (mPackages) {
1346                        if (userId == UserHandle.USER_ALL) {
1347                            int[] users = sUserManager.getUserIds();
1348                            for (int user : users) {
1349                                mSettings.addPackageToCleanLPw(
1350                                        new PackageCleanItem(user, packageName, andCode));
1351                            }
1352                        } else {
1353                            mSettings.addPackageToCleanLPw(
1354                                    new PackageCleanItem(userId, packageName, andCode));
1355                        }
1356                    }
1357                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1358                    startCleaningPackages();
1359                } break;
1360                case POST_INSTALL: {
1361                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1362                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1363                    mRunningInstalls.delete(msg.arg1);
1364                    boolean deleteOld = false;
1365
1366                    if (data != null) {
1367                        InstallArgs args = data.args;
1368                        PackageInstalledInfo res = data.res;
1369
1370                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1371                            final String packageName = res.pkg.applicationInfo.packageName;
1372                            res.removedInfo.sendBroadcast(false, true, false);
1373                            Bundle extras = new Bundle(1);
1374                            extras.putInt(Intent.EXTRA_UID, res.uid);
1375
1376                            // Now that we successfully installed the package, grant runtime
1377                            // permissions if requested before broadcasting the install.
1378                            if ((args.installFlags
1379                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1380                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1381                                        args.installGrantPermissions);
1382                            }
1383
1384                            // Determine the set of users who are adding this
1385                            // package for the first time vs. those who are seeing
1386                            // an update.
1387                            int[] firstUsers;
1388                            int[] updateUsers = new int[0];
1389                            if (res.origUsers == null || res.origUsers.length == 0) {
1390                                firstUsers = res.newUsers;
1391                            } else {
1392                                firstUsers = new int[0];
1393                                for (int i=0; i<res.newUsers.length; i++) {
1394                                    int user = res.newUsers[i];
1395                                    boolean isNew = true;
1396                                    for (int j=0; j<res.origUsers.length; j++) {
1397                                        if (res.origUsers[j] == user) {
1398                                            isNew = false;
1399                                            break;
1400                                        }
1401                                    }
1402                                    if (isNew) {
1403                                        int[] newFirst = new int[firstUsers.length+1];
1404                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1405                                                firstUsers.length);
1406                                        newFirst[firstUsers.length] = user;
1407                                        firstUsers = newFirst;
1408                                    } else {
1409                                        int[] newUpdate = new int[updateUsers.length+1];
1410                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1411                                                updateUsers.length);
1412                                        newUpdate[updateUsers.length] = user;
1413                                        updateUsers = newUpdate;
1414                                    }
1415                                }
1416                            }
1417                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1418                                    packageName, extras, null, null, firstUsers);
1419                            final boolean update = res.removedInfo.removedPackage != null;
1420                            if (update) {
1421                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1422                            }
1423                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1424                                    packageName, extras, null, null, updateUsers);
1425                            if (update) {
1426                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1427                                        packageName, extras, null, null, updateUsers);
1428                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1429                                        null, null, packageName, null, updateUsers);
1430
1431                                // treat asec-hosted packages like removable media on upgrade
1432                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1433                                    if (DEBUG_INSTALL) {
1434                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1435                                                + " is ASEC-hosted -> AVAILABLE");
1436                                    }
1437                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1438                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1439                                    pkgList.add(packageName);
1440                                    sendResourcesChangedBroadcast(true, true,
1441                                            pkgList,uidArray, null);
1442                                }
1443                            }
1444                            if (res.removedInfo.args != null) {
1445                                // Remove the replaced package's older resources safely now
1446                                deleteOld = true;
1447                            }
1448
1449                            // If this app is a browser and it's newly-installed for some
1450                            // users, clear any default-browser state in those users
1451                            if (firstUsers.length > 0) {
1452                                // the app's nature doesn't depend on the user, so we can just
1453                                // check its browser nature in any user and generalize.
1454                                if (packageIsBrowser(packageName, firstUsers[0])) {
1455                                    synchronized (mPackages) {
1456                                        for (int userId : firstUsers) {
1457                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1458                                        }
1459                                    }
1460                                }
1461                            }
1462                            // Log current value of "unknown sources" setting
1463                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1464                                getUnknownSourcesSettings());
1465                        }
1466                        // Force a gc to clear up things
1467                        Runtime.getRuntime().gc();
1468                        // We delete after a gc for applications  on sdcard.
1469                        if (deleteOld) {
1470                            synchronized (mInstallLock) {
1471                                res.removedInfo.args.doPostDeleteLI(true);
1472                            }
1473                        }
1474                        if (args.observer != null) {
1475                            try {
1476                                Bundle extras = extrasForInstallResult(res);
1477                                args.observer.onPackageInstalled(res.name, res.returnCode,
1478                                        res.returnMsg, extras);
1479                            } catch (RemoteException e) {
1480                                Slog.i(TAG, "Observer no longer exists.");
1481                            }
1482                        }
1483                        if (args.traceMethod != null) {
1484                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1485                                    args.traceCookie);
1486                        }
1487                        return;
1488                    } else {
1489                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1490                    }
1491
1492                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1493                } break;
1494                case UPDATED_MEDIA_STATUS: {
1495                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1496                    boolean reportStatus = msg.arg1 == 1;
1497                    boolean doGc = msg.arg2 == 1;
1498                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1499                    if (doGc) {
1500                        // Force a gc to clear up stale containers.
1501                        Runtime.getRuntime().gc();
1502                    }
1503                    if (msg.obj != null) {
1504                        @SuppressWarnings("unchecked")
1505                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1506                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1507                        // Unload containers
1508                        unloadAllContainers(args);
1509                    }
1510                    if (reportStatus) {
1511                        try {
1512                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1513                            PackageHelper.getMountService().finishMediaUpdate();
1514                        } catch (RemoteException e) {
1515                            Log.e(TAG, "MountService not running?");
1516                        }
1517                    }
1518                } break;
1519                case WRITE_SETTINGS: {
1520                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1521                    synchronized (mPackages) {
1522                        removeMessages(WRITE_SETTINGS);
1523                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1524                        mSettings.writeLPr();
1525                        mDirtyUsers.clear();
1526                    }
1527                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1528                } break;
1529                case WRITE_PACKAGE_RESTRICTIONS: {
1530                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1531                    synchronized (mPackages) {
1532                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1533                        for (int userId : mDirtyUsers) {
1534                            mSettings.writePackageRestrictionsLPr(userId);
1535                        }
1536                        mDirtyUsers.clear();
1537                    }
1538                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1539                } break;
1540                case CHECK_PENDING_VERIFICATION: {
1541                    final int verificationId = msg.arg1;
1542                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1543
1544                    if ((state != null) && !state.timeoutExtended()) {
1545                        final InstallArgs args = state.getInstallArgs();
1546                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1547
1548                        Slog.i(TAG, "Verification timed out for " + originUri);
1549                        mPendingVerification.remove(verificationId);
1550
1551                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1552
1553                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1554                            Slog.i(TAG, "Continuing with installation of " + originUri);
1555                            state.setVerifierResponse(Binder.getCallingUid(),
1556                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1557                            broadcastPackageVerified(verificationId, originUri,
1558                                    PackageManager.VERIFICATION_ALLOW,
1559                                    state.getInstallArgs().getUser());
1560                            try {
1561                                ret = args.copyApk(mContainerService, true);
1562                            } catch (RemoteException e) {
1563                                Slog.e(TAG, "Could not contact the ContainerService");
1564                            }
1565                        } else {
1566                            broadcastPackageVerified(verificationId, originUri,
1567                                    PackageManager.VERIFICATION_REJECT,
1568                                    state.getInstallArgs().getUser());
1569                        }
1570
1571                        Trace.asyncTraceEnd(
1572                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1573
1574                        processPendingInstall(args, ret);
1575                        mHandler.sendEmptyMessage(MCS_UNBIND);
1576                    }
1577                    break;
1578                }
1579                case PACKAGE_VERIFIED: {
1580                    final int verificationId = msg.arg1;
1581
1582                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1583                    if (state == null) {
1584                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1585                        break;
1586                    }
1587
1588                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1589
1590                    state.setVerifierResponse(response.callerUid, response.code);
1591
1592                    if (state.isVerificationComplete()) {
1593                        mPendingVerification.remove(verificationId);
1594
1595                        final InstallArgs args = state.getInstallArgs();
1596                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1597
1598                        int ret;
1599                        if (state.isInstallAllowed()) {
1600                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1601                            broadcastPackageVerified(verificationId, originUri,
1602                                    response.code, state.getInstallArgs().getUser());
1603                            try {
1604                                ret = args.copyApk(mContainerService, true);
1605                            } catch (RemoteException e) {
1606                                Slog.e(TAG, "Could not contact the ContainerService");
1607                            }
1608                        } else {
1609                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1610                        }
1611
1612                        Trace.asyncTraceEnd(
1613                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1614
1615                        processPendingInstall(args, ret);
1616                        mHandler.sendEmptyMessage(MCS_UNBIND);
1617                    }
1618
1619                    break;
1620                }
1621                case START_INTENT_FILTER_VERIFICATIONS: {
1622                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1623                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1624                            params.replacing, params.pkg);
1625                    break;
1626                }
1627                case INTENT_FILTER_VERIFIED: {
1628                    final int verificationId = msg.arg1;
1629
1630                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1631                            verificationId);
1632                    if (state == null) {
1633                        Slog.w(TAG, "Invalid IntentFilter verification token "
1634                                + verificationId + " received");
1635                        break;
1636                    }
1637
1638                    final int userId = state.getUserId();
1639
1640                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1641                            "Processing IntentFilter verification with token:"
1642                            + verificationId + " and userId:" + userId);
1643
1644                    final IntentFilterVerificationResponse response =
1645                            (IntentFilterVerificationResponse) msg.obj;
1646
1647                    state.setVerifierResponse(response.callerUid, response.code);
1648
1649                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1650                            "IntentFilter verification with token:" + verificationId
1651                            + " and userId:" + userId
1652                            + " is settings verifier response with response code:"
1653                            + response.code);
1654
1655                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1656                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1657                                + response.getFailedDomainsString());
1658                    }
1659
1660                    if (state.isVerificationComplete()) {
1661                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1662                    } else {
1663                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1664                                "IntentFilter verification with token:" + verificationId
1665                                + " was not said to be complete");
1666                    }
1667
1668                    break;
1669                }
1670            }
1671        }
1672    }
1673
1674    private StorageEventListener mStorageListener = new StorageEventListener() {
1675        @Override
1676        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1677            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1678                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1679                    final String volumeUuid = vol.getFsUuid();
1680
1681                    // Clean up any users or apps that were removed or recreated
1682                    // while this volume was missing
1683                    reconcileUsers(volumeUuid);
1684                    reconcileApps(volumeUuid);
1685
1686                    // Clean up any install sessions that expired or were
1687                    // cancelled while this volume was missing
1688                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1689
1690                    loadPrivatePackages(vol);
1691
1692                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1693                    unloadPrivatePackages(vol);
1694                }
1695            }
1696
1697            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1698                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1699                    updateExternalMediaStatus(true, false);
1700                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1701                    updateExternalMediaStatus(false, false);
1702                }
1703            }
1704        }
1705
1706        @Override
1707        public void onVolumeForgotten(String fsUuid) {
1708            if (TextUtils.isEmpty(fsUuid)) {
1709                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1710                return;
1711            }
1712
1713            // Remove any apps installed on the forgotten volume
1714            synchronized (mPackages) {
1715                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1716                for (PackageSetting ps : packages) {
1717                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1718                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1719                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1720                }
1721
1722                mSettings.onVolumeForgotten(fsUuid);
1723                mSettings.writeLPr();
1724            }
1725        }
1726    };
1727
1728    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1729            String[] grantedPermissions) {
1730        if (userId >= UserHandle.USER_SYSTEM) {
1731            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1732        } else if (userId == UserHandle.USER_ALL) {
1733            final int[] userIds;
1734            synchronized (mPackages) {
1735                userIds = UserManagerService.getInstance().getUserIds();
1736            }
1737            for (int someUserId : userIds) {
1738                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1739            }
1740        }
1741
1742        // We could have touched GID membership, so flush out packages.list
1743        synchronized (mPackages) {
1744            mSettings.writePackageListLPr();
1745        }
1746    }
1747
1748    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1749            String[] grantedPermissions) {
1750        SettingBase sb = (SettingBase) pkg.mExtras;
1751        if (sb == null) {
1752            return;
1753        }
1754
1755        PermissionsState permissionsState = sb.getPermissionsState();
1756
1757        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1758                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1759
1760        synchronized (mPackages) {
1761            for (String permission : pkg.requestedPermissions) {
1762                BasePermission bp = mSettings.mPermissions.get(permission);
1763                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1764                        && (grantedPermissions == null
1765                               || ArrayUtils.contains(grantedPermissions, permission))) {
1766                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1767                    // Installer cannot change immutable permissions.
1768                    if ((flags & immutableFlags) == 0) {
1769                        grantRuntimePermission(pkg.packageName, permission, userId);
1770                    }
1771                }
1772            }
1773        }
1774    }
1775
1776    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1777        Bundle extras = null;
1778        switch (res.returnCode) {
1779            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1780                extras = new Bundle();
1781                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1782                        res.origPermission);
1783                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1784                        res.origPackage);
1785                break;
1786            }
1787            case PackageManager.INSTALL_SUCCEEDED: {
1788                extras = new Bundle();
1789                extras.putBoolean(Intent.EXTRA_REPLACING,
1790                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1791                break;
1792            }
1793        }
1794        return extras;
1795    }
1796
1797    void scheduleWriteSettingsLocked() {
1798        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1799            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1800        }
1801    }
1802
1803    void scheduleWritePackageRestrictionsLocked(int userId) {
1804        if (!sUserManager.exists(userId)) return;
1805        mDirtyUsers.add(userId);
1806        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1807            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1808        }
1809    }
1810
1811    public static PackageManagerService main(Context context, Installer installer,
1812            boolean factoryTest, boolean onlyCore) {
1813        PackageManagerService m = new PackageManagerService(context, installer,
1814                factoryTest, onlyCore);
1815        ServiceManager.addService("package", m);
1816        return m;
1817    }
1818
1819    static String[] splitString(String str, char sep) {
1820        int count = 1;
1821        int i = 0;
1822        while ((i=str.indexOf(sep, i)) >= 0) {
1823            count++;
1824            i++;
1825        }
1826
1827        String[] res = new String[count];
1828        i=0;
1829        count = 0;
1830        int lastI=0;
1831        while ((i=str.indexOf(sep, i)) >= 0) {
1832            res[count] = str.substring(lastI, i);
1833            count++;
1834            i++;
1835            lastI = i;
1836        }
1837        res[count] = str.substring(lastI, str.length());
1838        return res;
1839    }
1840
1841    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1842        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1843                Context.DISPLAY_SERVICE);
1844        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1845    }
1846
1847    public PackageManagerService(Context context, Installer installer,
1848            boolean factoryTest, boolean onlyCore) {
1849        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1850                SystemClock.uptimeMillis());
1851
1852        if (mSdkVersion <= 0) {
1853            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1854        }
1855
1856        mContext = context;
1857        mFactoryTest = factoryTest;
1858        mOnlyCore = onlyCore;
1859        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1860        mMetrics = new DisplayMetrics();
1861        mSettings = new Settings(mPackages);
1862        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1863                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1864        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1865                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1866        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1867                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1868        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1869                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1870        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1871                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1872        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1873                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1874
1875        // TODO: add a property to control this?
1876        long dexOptLRUThresholdInMinutes;
1877        if (mLazyDexOpt) {
1878            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1879        } else {
1880            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1881        }
1882        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1883
1884        String separateProcesses = SystemProperties.get("debug.separate_processes");
1885        if (separateProcesses != null && separateProcesses.length() > 0) {
1886            if ("*".equals(separateProcesses)) {
1887                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1888                mSeparateProcesses = null;
1889                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1890            } else {
1891                mDefParseFlags = 0;
1892                mSeparateProcesses = separateProcesses.split(",");
1893                Slog.w(TAG, "Running with debug.separate_processes: "
1894                        + separateProcesses);
1895            }
1896        } else {
1897            mDefParseFlags = 0;
1898            mSeparateProcesses = null;
1899        }
1900
1901        mInstaller = installer;
1902        mPackageDexOptimizer = new PackageDexOptimizer(this);
1903        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1904
1905        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1906                FgThread.get().getLooper());
1907
1908        getDefaultDisplayMetrics(context, mMetrics);
1909
1910        SystemConfig systemConfig = SystemConfig.getInstance();
1911        mGlobalGids = systemConfig.getGlobalGids();
1912        mSystemPermissions = systemConfig.getSystemPermissions();
1913        mAvailableFeatures = systemConfig.getAvailableFeatures();
1914
1915        synchronized (mInstallLock) {
1916        // writer
1917        synchronized (mPackages) {
1918            mHandlerThread = new ServiceThread(TAG,
1919                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1920            mHandlerThread.start();
1921            mHandler = new PackageHandler(mHandlerThread.getLooper());
1922            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1923
1924            File dataDir = Environment.getDataDirectory();
1925            mAppDataDir = new File(dataDir, "data");
1926            mAppInstallDir = new File(dataDir, "app");
1927            mAppLib32InstallDir = new File(dataDir, "app-lib");
1928            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1929            mUserAppDataDir = new File(dataDir, "user");
1930            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1931
1932            sUserManager = new UserManagerService(context, this,
1933                    mInstallLock, mPackages);
1934
1935            // Propagate permission configuration in to package manager.
1936            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1937                    = systemConfig.getPermissions();
1938            for (int i=0; i<permConfig.size(); i++) {
1939                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1940                BasePermission bp = mSettings.mPermissions.get(perm.name);
1941                if (bp == null) {
1942                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1943                    mSettings.mPermissions.put(perm.name, bp);
1944                }
1945                if (perm.gids != null) {
1946                    bp.setGids(perm.gids, perm.perUser);
1947                }
1948            }
1949
1950            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1951            for (int i=0; i<libConfig.size(); i++) {
1952                mSharedLibraries.put(libConfig.keyAt(i),
1953                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1954            }
1955
1956            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1957
1958            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
1959
1960            String customResolverActivity = Resources.getSystem().getString(
1961                    R.string.config_customResolverActivity);
1962            if (TextUtils.isEmpty(customResolverActivity)) {
1963                customResolverActivity = null;
1964            } else {
1965                mCustomResolverComponentName = ComponentName.unflattenFromString(
1966                        customResolverActivity);
1967            }
1968
1969            long startTime = SystemClock.uptimeMillis();
1970
1971            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1972                    startTime);
1973
1974            // Set flag to monitor and not change apk file paths when
1975            // scanning install directories.
1976            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1977
1978            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1979
1980            /**
1981             * Add everything in the in the boot class path to the
1982             * list of process files because dexopt will have been run
1983             * if necessary during zygote startup.
1984             */
1985            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1986            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1987
1988            if (bootClassPath != null) {
1989                String[] bootClassPathElements = splitString(bootClassPath, ':');
1990                for (String element : bootClassPathElements) {
1991                    alreadyDexOpted.add(element);
1992                }
1993            } else {
1994                Slog.w(TAG, "No BOOTCLASSPATH found!");
1995            }
1996
1997            if (systemServerClassPath != null) {
1998                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1999                for (String element : systemServerClassPathElements) {
2000                    alreadyDexOpted.add(element);
2001                }
2002            } else {
2003                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2004            }
2005
2006            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2007            final String[] dexCodeInstructionSets =
2008                    getDexCodeInstructionSets(
2009                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2010
2011            /**
2012             * Ensure all external libraries have had dexopt run on them.
2013             */
2014            if (mSharedLibraries.size() > 0) {
2015                // NOTE: For now, we're compiling these system "shared libraries"
2016                // (and framework jars) into all available architectures. It's possible
2017                // to compile them only when we come across an app that uses them (there's
2018                // already logic for that in scanPackageLI) but that adds some complexity.
2019                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2020                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2021                        final String lib = libEntry.path;
2022                        if (lib == null) {
2023                            continue;
2024                        }
2025
2026                        try {
2027                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2028                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2029                                alreadyDexOpted.add(lib);
2030                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2031                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2032                            }
2033                        } catch (FileNotFoundException e) {
2034                            Slog.w(TAG, "Library not found: " + lib);
2035                        } catch (IOException e) {
2036                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2037                                    + e.getMessage());
2038                        }
2039                    }
2040                }
2041            }
2042
2043            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2044
2045            // Gross hack for now: we know this file doesn't contain any
2046            // code, so don't dexopt it to avoid the resulting log spew.
2047            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
2048
2049            // Gross hack for now: we know this file is only part of
2050            // the boot class path for art, so don't dexopt it to
2051            // avoid the resulting log spew.
2052            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
2053
2054            /**
2055             * There are a number of commands implemented in Java, which
2056             * we currently need to do the dexopt on so that they can be
2057             * run from a non-root shell.
2058             */
2059            String[] frameworkFiles = frameworkDir.list();
2060            if (frameworkFiles != null) {
2061                // TODO: We could compile these only for the most preferred ABI. We should
2062                // first double check that the dex files for these commands are not referenced
2063                // by other system apps.
2064                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2065                    for (int i=0; i<frameworkFiles.length; i++) {
2066                        File libPath = new File(frameworkDir, frameworkFiles[i]);
2067                        String path = libPath.getPath();
2068                        // Skip the file if we already did it.
2069                        if (alreadyDexOpted.contains(path)) {
2070                            continue;
2071                        }
2072                        // Skip the file if it is not a type we want to dexopt.
2073                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2074                            continue;
2075                        }
2076                        try {
2077                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2078                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2079                                mInstaller.dexopt(path, Process.SYSTEM_UID, dexCodeInstructionSet,
2080                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2081                            }
2082                        } catch (FileNotFoundException e) {
2083                            Slog.w(TAG, "Jar not found: " + path);
2084                        } catch (IOException e) {
2085                            Slog.w(TAG, "Exception reading jar: " + path, e);
2086                        }
2087                    }
2088                }
2089            }
2090
2091            final VersionInfo ver = mSettings.getInternalVersion();
2092            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2093            // when upgrading from pre-M, promote system app permissions from install to runtime
2094            mPromoteSystemApps =
2095                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2096
2097            // save off the names of pre-existing system packages prior to scanning; we don't
2098            // want to automatically grant runtime permissions for new system apps
2099            if (mPromoteSystemApps) {
2100                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2101                while (pkgSettingIter.hasNext()) {
2102                    PackageSetting ps = pkgSettingIter.next();
2103                    if (isSystemApp(ps)) {
2104                        mExistingSystemPackages.add(ps.name);
2105                    }
2106                }
2107            }
2108
2109            // Collect vendor overlay packages.
2110            // (Do this before scanning any apps.)
2111            // For security and version matching reason, only consider
2112            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2113            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2114            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2115                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2116
2117            // Find base frameworks (resource packages without code).
2118            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2119                    | PackageParser.PARSE_IS_SYSTEM_DIR
2120                    | PackageParser.PARSE_IS_PRIVILEGED,
2121                    scanFlags | SCAN_NO_DEX, 0);
2122
2123            // Collected privileged system packages.
2124            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2125            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2126                    | PackageParser.PARSE_IS_SYSTEM_DIR
2127                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2128
2129            // Collect ordinary system packages.
2130            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2131            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2132                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2133
2134            // Collect all vendor packages.
2135            File vendorAppDir = new File("/vendor/app");
2136            try {
2137                vendorAppDir = vendorAppDir.getCanonicalFile();
2138            } catch (IOException e) {
2139                // failed to look up canonical path, continue with original one
2140            }
2141            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2142                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2143
2144            // Collect all OEM packages.
2145            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2146            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2147                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2148
2149            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2150            mInstaller.moveFiles();
2151
2152            // Prune any system packages that no longer exist.
2153            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2154            if (!mOnlyCore) {
2155                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2156                while (psit.hasNext()) {
2157                    PackageSetting ps = psit.next();
2158
2159                    /*
2160                     * If this is not a system app, it can't be a
2161                     * disable system app.
2162                     */
2163                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2164                        continue;
2165                    }
2166
2167                    /*
2168                     * If the package is scanned, it's not erased.
2169                     */
2170                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2171                    if (scannedPkg != null) {
2172                        /*
2173                         * If the system app is both scanned and in the
2174                         * disabled packages list, then it must have been
2175                         * added via OTA. Remove it from the currently
2176                         * scanned package so the previously user-installed
2177                         * application can be scanned.
2178                         */
2179                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2180                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2181                                    + ps.name + "; removing system app.  Last known codePath="
2182                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2183                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2184                                    + scannedPkg.mVersionCode);
2185                            removePackageLI(ps, true);
2186                            mExpectingBetter.put(ps.name, ps.codePath);
2187                        }
2188
2189                        continue;
2190                    }
2191
2192                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2193                        psit.remove();
2194                        logCriticalInfo(Log.WARN, "System package " + ps.name
2195                                + " no longer exists; wiping its data");
2196                        removeDataDirsLI(null, ps.name);
2197                    } else {
2198                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2199                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2200                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2201                        }
2202                    }
2203                }
2204            }
2205
2206            //look for any incomplete package installations
2207            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2208            //clean up list
2209            for(int i = 0; i < deletePkgsList.size(); i++) {
2210                //clean up here
2211                cleanupInstallFailedPackage(deletePkgsList.get(i));
2212            }
2213            //delete tmp files
2214            deleteTempPackageFiles();
2215
2216            // Remove any shared userIDs that have no associated packages
2217            mSettings.pruneSharedUsersLPw();
2218
2219            if (!mOnlyCore) {
2220                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2221                        SystemClock.uptimeMillis());
2222                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2223
2224                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2225                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2226
2227                /**
2228                 * Remove disable package settings for any updated system
2229                 * apps that were removed via an OTA. If they're not a
2230                 * previously-updated app, remove them completely.
2231                 * Otherwise, just revoke their system-level permissions.
2232                 */
2233                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2234                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2235                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2236
2237                    String msg;
2238                    if (deletedPkg == null) {
2239                        msg = "Updated system package " + deletedAppName
2240                                + " no longer exists; wiping its data";
2241                        removeDataDirsLI(null, deletedAppName);
2242                    } else {
2243                        msg = "Updated system app + " + deletedAppName
2244                                + " no longer present; removing system privileges for "
2245                                + deletedAppName;
2246
2247                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2248
2249                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2250                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2251                    }
2252                    logCriticalInfo(Log.WARN, msg);
2253                }
2254
2255                /**
2256                 * Make sure all system apps that we expected to appear on
2257                 * the userdata partition actually showed up. If they never
2258                 * appeared, crawl back and revive the system version.
2259                 */
2260                for (int i = 0; i < mExpectingBetter.size(); i++) {
2261                    final String packageName = mExpectingBetter.keyAt(i);
2262                    if (!mPackages.containsKey(packageName)) {
2263                        final File scanFile = mExpectingBetter.valueAt(i);
2264
2265                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2266                                + " but never showed up; reverting to system");
2267
2268                        final int reparseFlags;
2269                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2270                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2271                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2272                                    | PackageParser.PARSE_IS_PRIVILEGED;
2273                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2274                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2275                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2276                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2277                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2278                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2279                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2280                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2281                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2282                        } else {
2283                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2284                            continue;
2285                        }
2286
2287                        mSettings.enableSystemPackageLPw(packageName);
2288
2289                        try {
2290                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2291                        } catch (PackageManagerException e) {
2292                            Slog.e(TAG, "Failed to parse original system package: "
2293                                    + e.getMessage());
2294                        }
2295                    }
2296                }
2297            }
2298            mExpectingBetter.clear();
2299
2300            // Now that we know all of the shared libraries, update all clients to have
2301            // the correct library paths.
2302            updateAllSharedLibrariesLPw();
2303
2304            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2305                // NOTE: We ignore potential failures here during a system scan (like
2306                // the rest of the commands above) because there's precious little we
2307                // can do about it. A settings error is reported, though.
2308                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2309                        false /* force dexopt */, false /* defer dexopt */,
2310                        false /* boot complete */);
2311            }
2312
2313            // Now that we know all the packages we are keeping,
2314            // read and update their last usage times.
2315            mPackageUsage.readLP();
2316
2317            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2318                    SystemClock.uptimeMillis());
2319            Slog.i(TAG, "Time to scan packages: "
2320                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2321                    + " seconds");
2322
2323            // If the platform SDK has changed since the last time we booted,
2324            // we need to re-grant app permission to catch any new ones that
2325            // appear.  This is really a hack, and means that apps can in some
2326            // cases get permissions that the user didn't initially explicitly
2327            // allow...  it would be nice to have some better way to handle
2328            // this situation.
2329            int updateFlags = UPDATE_PERMISSIONS_ALL;
2330            if (ver.sdkVersion != mSdkVersion) {
2331                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2332                        + mSdkVersion + "; regranting permissions for internal storage");
2333                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2334            }
2335            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2336            ver.sdkVersion = mSdkVersion;
2337
2338            // If this is the first boot or an update from pre-M, and it is a normal
2339            // boot, then we need to initialize the default preferred apps across
2340            // all defined users.
2341            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2342                for (UserInfo user : sUserManager.getUsers(true)) {
2343                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2344                    applyFactoryDefaultBrowserLPw(user.id);
2345                    primeDomainVerificationsLPw(user.id);
2346                }
2347            }
2348
2349            // If this is first boot after an OTA, and a normal boot, then
2350            // we need to clear code cache directories.
2351            if (mIsUpgrade && !onlyCore) {
2352                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2353                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2354                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2355                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2356                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2357                    }
2358                }
2359                ver.fingerprint = Build.FINGERPRINT;
2360            }
2361
2362            checkDefaultBrowser();
2363
2364            // clear only after permissions and other defaults have been updated
2365            mExistingSystemPackages.clear();
2366            mPromoteSystemApps = false;
2367
2368            // All the changes are done during package scanning.
2369            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2370
2371            // can downgrade to reader
2372            mSettings.writeLPr();
2373
2374            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2375                    SystemClock.uptimeMillis());
2376
2377            mRequiredVerifierPackage = getRequiredVerifierLPr();
2378            mRequiredInstallerPackage = getRequiredInstallerLPr();
2379
2380            mInstallerService = new PackageInstallerService(context, this);
2381
2382            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2383            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2384                    mIntentFilterVerifierComponent);
2385
2386        } // synchronized (mPackages)
2387        } // synchronized (mInstallLock)
2388
2389        // Now after opening every single application zip, make sure they
2390        // are all flushed.  Not really needed, but keeps things nice and
2391        // tidy.
2392        Runtime.getRuntime().gc();
2393
2394        // The initial scanning above does many calls into installd while
2395        // holding the mPackages lock, but we're mostly interested in yelling
2396        // once we have a booted system.
2397        mInstaller.setWarnIfHeld(mPackages);
2398
2399        // Expose private service for system components to use.
2400        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2401    }
2402
2403    @Override
2404    public boolean isFirstBoot() {
2405        return !mRestoredSettings;
2406    }
2407
2408    @Override
2409    public boolean isOnlyCoreApps() {
2410        return mOnlyCore;
2411    }
2412
2413    @Override
2414    public boolean isUpgrade() {
2415        return mIsUpgrade;
2416    }
2417
2418    private String getRequiredVerifierLPr() {
2419        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2420        // We only care about verifier that's installed under system user.
2421        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2422                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2423
2424        String requiredVerifier = null;
2425
2426        final int N = receivers.size();
2427        for (int i = 0; i < N; i++) {
2428            final ResolveInfo info = receivers.get(i);
2429
2430            if (info.activityInfo == null) {
2431                continue;
2432            }
2433
2434            final String packageName = info.activityInfo.packageName;
2435
2436            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2437                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2438                continue;
2439            }
2440
2441            if (requiredVerifier != null) {
2442                throw new RuntimeException("There can be only one required verifier");
2443            }
2444
2445            requiredVerifier = packageName;
2446        }
2447
2448        return requiredVerifier;
2449    }
2450
2451    private String getRequiredInstallerLPr() {
2452        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2453        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2454        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2455
2456        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2457                PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM);
2458
2459        String requiredInstaller = null;
2460
2461        final int N = installers.size();
2462        for (int i = 0; i < N; i++) {
2463            final ResolveInfo info = installers.get(i);
2464            final String packageName = info.activityInfo.packageName;
2465
2466            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2467                continue;
2468            }
2469
2470            if (requiredInstaller != null) {
2471                throw new RuntimeException("There must be one required installer");
2472            }
2473
2474            requiredInstaller = packageName;
2475        }
2476
2477        if (requiredInstaller == null) {
2478            throw new RuntimeException("There must be one required installer");
2479        }
2480
2481        return requiredInstaller;
2482    }
2483
2484    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2485        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2486        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2487                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2488
2489        ComponentName verifierComponentName = null;
2490
2491        int priority = -1000;
2492        final int N = receivers.size();
2493        for (int i = 0; i < N; i++) {
2494            final ResolveInfo info = receivers.get(i);
2495
2496            if (info.activityInfo == null) {
2497                continue;
2498            }
2499
2500            final String packageName = info.activityInfo.packageName;
2501
2502            final PackageSetting ps = mSettings.mPackages.get(packageName);
2503            if (ps == null) {
2504                continue;
2505            }
2506
2507            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2508                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2509                continue;
2510            }
2511
2512            // Select the IntentFilterVerifier with the highest priority
2513            if (priority < info.priority) {
2514                priority = info.priority;
2515                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2516                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2517                        + verifierComponentName + " with priority: " + info.priority);
2518            }
2519        }
2520
2521        return verifierComponentName;
2522    }
2523
2524    private void primeDomainVerificationsLPw(int userId) {
2525        if (DEBUG_DOMAIN_VERIFICATION) {
2526            Slog.d(TAG, "Priming domain verifications in user " + userId);
2527        }
2528
2529        SystemConfig systemConfig = SystemConfig.getInstance();
2530        ArraySet<String> packages = systemConfig.getLinkedApps();
2531        ArraySet<String> domains = new ArraySet<String>();
2532
2533        for (String packageName : packages) {
2534            PackageParser.Package pkg = mPackages.get(packageName);
2535            if (pkg != null) {
2536                if (!pkg.isSystemApp()) {
2537                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2538                    continue;
2539                }
2540
2541                domains.clear();
2542                for (PackageParser.Activity a : pkg.activities) {
2543                    for (ActivityIntentInfo filter : a.intents) {
2544                        if (hasValidDomains(filter)) {
2545                            domains.addAll(filter.getHostsList());
2546                        }
2547                    }
2548                }
2549
2550                if (domains.size() > 0) {
2551                    if (DEBUG_DOMAIN_VERIFICATION) {
2552                        Slog.v(TAG, "      + " + packageName);
2553                    }
2554                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2555                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2556                    // and then 'always' in the per-user state actually used for intent resolution.
2557                    final IntentFilterVerificationInfo ivi;
2558                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2559                            new ArrayList<String>(domains));
2560                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2561                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2562                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2563                } else {
2564                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2565                            + "' does not handle web links");
2566                }
2567            } else {
2568                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2569            }
2570        }
2571
2572        scheduleWritePackageRestrictionsLocked(userId);
2573        scheduleWriteSettingsLocked();
2574    }
2575
2576    private void applyFactoryDefaultBrowserLPw(int userId) {
2577        // The default browser app's package name is stored in a string resource,
2578        // with a product-specific overlay used for vendor customization.
2579        String browserPkg = mContext.getResources().getString(
2580                com.android.internal.R.string.default_browser);
2581        if (!TextUtils.isEmpty(browserPkg)) {
2582            // non-empty string => required to be a known package
2583            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2584            if (ps == null) {
2585                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2586                browserPkg = null;
2587            } else {
2588                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2589            }
2590        }
2591
2592        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2593        // default.  If there's more than one, just leave everything alone.
2594        if (browserPkg == null) {
2595            calculateDefaultBrowserLPw(userId);
2596        }
2597    }
2598
2599    private void calculateDefaultBrowserLPw(int userId) {
2600        List<String> allBrowsers = resolveAllBrowserApps(userId);
2601        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2602        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2603    }
2604
2605    private List<String> resolveAllBrowserApps(int userId) {
2606        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2607        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2608                PackageManager.MATCH_ALL, userId);
2609
2610        final int count = list.size();
2611        List<String> result = new ArrayList<String>(count);
2612        for (int i=0; i<count; i++) {
2613            ResolveInfo info = list.get(i);
2614            if (info.activityInfo == null
2615                    || !info.handleAllWebDataURI
2616                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2617                    || result.contains(info.activityInfo.packageName)) {
2618                continue;
2619            }
2620            result.add(info.activityInfo.packageName);
2621        }
2622
2623        return result;
2624    }
2625
2626    private boolean packageIsBrowser(String packageName, int userId) {
2627        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2628                PackageManager.MATCH_ALL, userId);
2629        final int N = list.size();
2630        for (int i = 0; i < N; i++) {
2631            ResolveInfo info = list.get(i);
2632            if (packageName.equals(info.activityInfo.packageName)) {
2633                return true;
2634            }
2635        }
2636        return false;
2637    }
2638
2639    private void checkDefaultBrowser() {
2640        final int myUserId = UserHandle.myUserId();
2641        final String packageName = getDefaultBrowserPackageName(myUserId);
2642        if (packageName != null) {
2643            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2644            if (info == null) {
2645                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2646                synchronized (mPackages) {
2647                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2648                }
2649            }
2650        }
2651    }
2652
2653    @Override
2654    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2655            throws RemoteException {
2656        try {
2657            return super.onTransact(code, data, reply, flags);
2658        } catch (RuntimeException e) {
2659            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2660                Slog.wtf(TAG, "Package Manager Crash", e);
2661            }
2662            throw e;
2663        }
2664    }
2665
2666    void cleanupInstallFailedPackage(PackageSetting ps) {
2667        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2668
2669        removeDataDirsLI(ps.volumeUuid, ps.name);
2670        if (ps.codePath != null) {
2671            if (ps.codePath.isDirectory()) {
2672                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2673            } else {
2674                ps.codePath.delete();
2675            }
2676        }
2677        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2678            if (ps.resourcePath.isDirectory()) {
2679                FileUtils.deleteContents(ps.resourcePath);
2680            }
2681            ps.resourcePath.delete();
2682        }
2683        mSettings.removePackageLPw(ps.name);
2684    }
2685
2686    static int[] appendInts(int[] cur, int[] add) {
2687        if (add == null) return cur;
2688        if (cur == null) return add;
2689        final int N = add.length;
2690        for (int i=0; i<N; i++) {
2691            cur = appendInt(cur, add[i]);
2692        }
2693        return cur;
2694    }
2695
2696    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2697        if (!sUserManager.exists(userId)) return null;
2698        final PackageSetting ps = (PackageSetting) p.mExtras;
2699        if (ps == null) {
2700            return null;
2701        }
2702
2703        final PermissionsState permissionsState = ps.getPermissionsState();
2704
2705        final int[] gids = permissionsState.computeGids(userId);
2706        final Set<String> permissions = permissionsState.getPermissions(userId);
2707        final PackageUserState state = ps.readUserState(userId);
2708
2709        return PackageParser.generatePackageInfo(p, gids, flags,
2710                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2711    }
2712
2713    @Override
2714    public boolean isPackageFrozen(String packageName) {
2715        synchronized (mPackages) {
2716            final PackageSetting ps = mSettings.mPackages.get(packageName);
2717            if (ps != null) {
2718                return ps.frozen;
2719            }
2720        }
2721        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2722        return true;
2723    }
2724
2725    @Override
2726    public boolean isPackageAvailable(String packageName, int userId) {
2727        if (!sUserManager.exists(userId)) return false;
2728        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2729        synchronized (mPackages) {
2730            PackageParser.Package p = mPackages.get(packageName);
2731            if (p != null) {
2732                final PackageSetting ps = (PackageSetting) p.mExtras;
2733                if (ps != null) {
2734                    final PackageUserState state = ps.readUserState(userId);
2735                    if (state != null) {
2736                        return PackageParser.isAvailable(state);
2737                    }
2738                }
2739            }
2740        }
2741        return false;
2742    }
2743
2744    @Override
2745    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2746        if (!sUserManager.exists(userId)) return null;
2747        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2748        // reader
2749        synchronized (mPackages) {
2750            PackageParser.Package p = mPackages.get(packageName);
2751            if (DEBUG_PACKAGE_INFO)
2752                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2753            if (p != null) {
2754                return generatePackageInfo(p, flags, userId);
2755            }
2756            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2757                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2758            }
2759        }
2760        return null;
2761    }
2762
2763    @Override
2764    public String[] currentToCanonicalPackageNames(String[] names) {
2765        String[] out = new String[names.length];
2766        // reader
2767        synchronized (mPackages) {
2768            for (int i=names.length-1; i>=0; i--) {
2769                PackageSetting ps = mSettings.mPackages.get(names[i]);
2770                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2771            }
2772        }
2773        return out;
2774    }
2775
2776    @Override
2777    public String[] canonicalToCurrentPackageNames(String[] names) {
2778        String[] out = new String[names.length];
2779        // reader
2780        synchronized (mPackages) {
2781            for (int i=names.length-1; i>=0; i--) {
2782                String cur = mSettings.mRenamedPackages.get(names[i]);
2783                out[i] = cur != null ? cur : names[i];
2784            }
2785        }
2786        return out;
2787    }
2788
2789    @Override
2790    public int getPackageUid(String packageName, int userId) {
2791        return getPackageUidEtc(packageName, 0, userId);
2792    }
2793
2794    @Override
2795    public int getPackageUidEtc(String packageName, int flags, int userId) {
2796        if (!sUserManager.exists(userId)) return -1;
2797        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2798
2799        // reader
2800        synchronized (mPackages) {
2801            final PackageParser.Package p = mPackages.get(packageName);
2802            if (p != null) {
2803                return UserHandle.getUid(userId, p.applicationInfo.uid);
2804            }
2805            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2806                final PackageSetting ps = mSettings.mPackages.get(packageName);
2807                if (ps != null) {
2808                    return UserHandle.getUid(userId, ps.appId);
2809                }
2810            }
2811        }
2812
2813        return -1;
2814    }
2815
2816    @Override
2817    public int[] getPackageGids(String packageName, int userId) {
2818        return getPackageGidsEtc(packageName, 0, userId);
2819    }
2820
2821    @Override
2822    public int[] getPackageGidsEtc(String packageName, int flags, int userId) {
2823        if (!sUserManager.exists(userId)) {
2824            return null;
2825        }
2826
2827        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2828                "getPackageGids");
2829
2830        // reader
2831        synchronized (mPackages) {
2832            final PackageParser.Package p = mPackages.get(packageName);
2833            if (p != null) {
2834                PackageSetting ps = (PackageSetting) p.mExtras;
2835                return ps.getPermissionsState().computeGids(userId);
2836            }
2837            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2838                final PackageSetting ps = mSettings.mPackages.get(packageName);
2839                if (ps != null) {
2840                    return ps.getPermissionsState().computeGids(userId);
2841                }
2842            }
2843        }
2844
2845        return null;
2846    }
2847
2848    static PermissionInfo generatePermissionInfo(
2849            BasePermission bp, int flags) {
2850        if (bp.perm != null) {
2851            return PackageParser.generatePermissionInfo(bp.perm, flags);
2852        }
2853        PermissionInfo pi = new PermissionInfo();
2854        pi.name = bp.name;
2855        pi.packageName = bp.sourcePackage;
2856        pi.nonLocalizedLabel = bp.name;
2857        pi.protectionLevel = bp.protectionLevel;
2858        return pi;
2859    }
2860
2861    @Override
2862    public PermissionInfo getPermissionInfo(String name, int flags) {
2863        // reader
2864        synchronized (mPackages) {
2865            final BasePermission p = mSettings.mPermissions.get(name);
2866            if (p != null) {
2867                return generatePermissionInfo(p, flags);
2868            }
2869            return null;
2870        }
2871    }
2872
2873    @Override
2874    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2875        // reader
2876        synchronized (mPackages) {
2877            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2878            for (BasePermission p : mSettings.mPermissions.values()) {
2879                if (group == null) {
2880                    if (p.perm == null || p.perm.info.group == null) {
2881                        out.add(generatePermissionInfo(p, flags));
2882                    }
2883                } else {
2884                    if (p.perm != null && group.equals(p.perm.info.group)) {
2885                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2886                    }
2887                }
2888            }
2889
2890            if (out.size() > 0) {
2891                return out;
2892            }
2893            return mPermissionGroups.containsKey(group) ? out : null;
2894        }
2895    }
2896
2897    @Override
2898    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2899        // reader
2900        synchronized (mPackages) {
2901            return PackageParser.generatePermissionGroupInfo(
2902                    mPermissionGroups.get(name), flags);
2903        }
2904    }
2905
2906    @Override
2907    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2908        // reader
2909        synchronized (mPackages) {
2910            final int N = mPermissionGroups.size();
2911            ArrayList<PermissionGroupInfo> out
2912                    = new ArrayList<PermissionGroupInfo>(N);
2913            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2914                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2915            }
2916            return out;
2917        }
2918    }
2919
2920    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2921            int userId) {
2922        if (!sUserManager.exists(userId)) return null;
2923        PackageSetting ps = mSettings.mPackages.get(packageName);
2924        if (ps != null) {
2925            if (ps.pkg == null) {
2926                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2927                        flags, userId);
2928                if (pInfo != null) {
2929                    return pInfo.applicationInfo;
2930                }
2931                return null;
2932            }
2933            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2934                    ps.readUserState(userId), userId);
2935        }
2936        return null;
2937    }
2938
2939    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2940            int userId) {
2941        if (!sUserManager.exists(userId)) return null;
2942        PackageSetting ps = mSettings.mPackages.get(packageName);
2943        if (ps != null) {
2944            PackageParser.Package pkg = ps.pkg;
2945            if (pkg == null) {
2946                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2947                    return null;
2948                }
2949                // Only data remains, so we aren't worried about code paths
2950                pkg = new PackageParser.Package(packageName);
2951                pkg.applicationInfo.packageName = packageName;
2952                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2953                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2954                pkg.applicationInfo.dataDir = Environment
2955                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2956                        .getAbsolutePath();
2957                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2958                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2959            }
2960            return generatePackageInfo(pkg, flags, userId);
2961        }
2962        return null;
2963    }
2964
2965    @Override
2966    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2967        if (!sUserManager.exists(userId)) return null;
2968        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2969        // writer
2970        synchronized (mPackages) {
2971            PackageParser.Package p = mPackages.get(packageName);
2972            if (DEBUG_PACKAGE_INFO) Log.v(
2973                    TAG, "getApplicationInfo " + packageName
2974                    + ": " + p);
2975            if (p != null) {
2976                PackageSetting ps = mSettings.mPackages.get(packageName);
2977                if (ps == null) return null;
2978                // Note: isEnabledLP() does not apply here - always return info
2979                return PackageParser.generateApplicationInfo(
2980                        p, flags, ps.readUserState(userId), userId);
2981            }
2982            if ("android".equals(packageName)||"system".equals(packageName)) {
2983                return mAndroidApplication;
2984            }
2985            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2986                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2987            }
2988        }
2989        return null;
2990    }
2991
2992    @Override
2993    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2994            final IPackageDataObserver observer) {
2995        mContext.enforceCallingOrSelfPermission(
2996                android.Manifest.permission.CLEAR_APP_CACHE, null);
2997        // Queue up an async operation since clearing cache may take a little while.
2998        mHandler.post(new Runnable() {
2999            public void run() {
3000                mHandler.removeCallbacks(this);
3001                int retCode = -1;
3002                synchronized (mInstallLock) {
3003                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3004                    if (retCode < 0) {
3005                        Slog.w(TAG, "Couldn't clear application caches");
3006                    }
3007                }
3008                if (observer != null) {
3009                    try {
3010                        observer.onRemoveCompleted(null, (retCode >= 0));
3011                    } catch (RemoteException e) {
3012                        Slog.w(TAG, "RemoveException when invoking call back");
3013                    }
3014                }
3015            }
3016        });
3017    }
3018
3019    @Override
3020    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3021            final IntentSender pi) {
3022        mContext.enforceCallingOrSelfPermission(
3023                android.Manifest.permission.CLEAR_APP_CACHE, null);
3024        // Queue up an async operation since clearing cache may take a little while.
3025        mHandler.post(new Runnable() {
3026            public void run() {
3027                mHandler.removeCallbacks(this);
3028                int retCode = -1;
3029                synchronized (mInstallLock) {
3030                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3031                    if (retCode < 0) {
3032                        Slog.w(TAG, "Couldn't clear application caches");
3033                    }
3034                }
3035                if(pi != null) {
3036                    try {
3037                        // Callback via pending intent
3038                        int code = (retCode >= 0) ? 1 : 0;
3039                        pi.sendIntent(null, code, null,
3040                                null, null);
3041                    } catch (SendIntentException e1) {
3042                        Slog.i(TAG, "Failed to send pending intent");
3043                    }
3044                }
3045            }
3046        });
3047    }
3048
3049    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3050        synchronized (mInstallLock) {
3051            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3052                throw new IOException("Failed to free enough space");
3053            }
3054        }
3055    }
3056
3057    @Override
3058    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3059        if (!sUserManager.exists(userId)) return null;
3060        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3061        synchronized (mPackages) {
3062            PackageParser.Activity a = mActivities.mActivities.get(component);
3063
3064            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3065            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3066                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3067                if (ps == null) return null;
3068                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3069                        userId);
3070            }
3071            if (mResolveComponentName.equals(component)) {
3072                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3073                        new PackageUserState(), userId);
3074            }
3075        }
3076        return null;
3077    }
3078
3079    @Override
3080    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3081            String resolvedType) {
3082        synchronized (mPackages) {
3083            if (component.equals(mResolveComponentName)) {
3084                // The resolver supports EVERYTHING!
3085                return true;
3086            }
3087            PackageParser.Activity a = mActivities.mActivities.get(component);
3088            if (a == null) {
3089                return false;
3090            }
3091            for (int i=0; i<a.intents.size(); i++) {
3092                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3093                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3094                    return true;
3095                }
3096            }
3097            return false;
3098        }
3099    }
3100
3101    @Override
3102    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3103        if (!sUserManager.exists(userId)) return null;
3104        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3105        synchronized (mPackages) {
3106            PackageParser.Activity a = mReceivers.mActivities.get(component);
3107            if (DEBUG_PACKAGE_INFO) Log.v(
3108                TAG, "getReceiverInfo " + component + ": " + a);
3109            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3110                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3111                if (ps == null) return null;
3112                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3113                        userId);
3114            }
3115        }
3116        return null;
3117    }
3118
3119    @Override
3120    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3121        if (!sUserManager.exists(userId)) return null;
3122        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3123        synchronized (mPackages) {
3124            PackageParser.Service s = mServices.mServices.get(component);
3125            if (DEBUG_PACKAGE_INFO) Log.v(
3126                TAG, "getServiceInfo " + component + ": " + s);
3127            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3128                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3129                if (ps == null) return null;
3130                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3131                        userId);
3132            }
3133        }
3134        return null;
3135    }
3136
3137    @Override
3138    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3139        if (!sUserManager.exists(userId)) return null;
3140        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3141        synchronized (mPackages) {
3142            PackageParser.Provider p = mProviders.mProviders.get(component);
3143            if (DEBUG_PACKAGE_INFO) Log.v(
3144                TAG, "getProviderInfo " + component + ": " + p);
3145            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3146                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3147                if (ps == null) return null;
3148                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3149                        userId);
3150            }
3151        }
3152        return null;
3153    }
3154
3155    @Override
3156    public String[] getSystemSharedLibraryNames() {
3157        Set<String> libSet;
3158        synchronized (mPackages) {
3159            libSet = mSharedLibraries.keySet();
3160            int size = libSet.size();
3161            if (size > 0) {
3162                String[] libs = new String[size];
3163                libSet.toArray(libs);
3164                return libs;
3165            }
3166        }
3167        return null;
3168    }
3169
3170    /**
3171     * @hide
3172     */
3173    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3174        synchronized (mPackages) {
3175            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3176            if (lib != null && lib.apk != null) {
3177                return mPackages.get(lib.apk);
3178            }
3179        }
3180        return null;
3181    }
3182
3183    @Override
3184    public FeatureInfo[] getSystemAvailableFeatures() {
3185        Collection<FeatureInfo> featSet;
3186        synchronized (mPackages) {
3187            featSet = mAvailableFeatures.values();
3188            int size = featSet.size();
3189            if (size > 0) {
3190                FeatureInfo[] features = new FeatureInfo[size+1];
3191                featSet.toArray(features);
3192                FeatureInfo fi = new FeatureInfo();
3193                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3194                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3195                features[size] = fi;
3196                return features;
3197            }
3198        }
3199        return null;
3200    }
3201
3202    @Override
3203    public boolean hasSystemFeature(String name) {
3204        synchronized (mPackages) {
3205            return mAvailableFeatures.containsKey(name);
3206        }
3207    }
3208
3209    private void checkValidCaller(int uid, int userId) {
3210        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3211            return;
3212
3213        throw new SecurityException("Caller uid=" + uid
3214                + " is not privileged to communicate with user=" + userId);
3215    }
3216
3217    @Override
3218    public int checkPermission(String permName, String pkgName, int userId) {
3219        if (!sUserManager.exists(userId)) {
3220            return PackageManager.PERMISSION_DENIED;
3221        }
3222
3223        synchronized (mPackages) {
3224            final PackageParser.Package p = mPackages.get(pkgName);
3225            if (p != null && p.mExtras != null) {
3226                final PackageSetting ps = (PackageSetting) p.mExtras;
3227                final PermissionsState permissionsState = ps.getPermissionsState();
3228                if (permissionsState.hasPermission(permName, userId)) {
3229                    return PackageManager.PERMISSION_GRANTED;
3230                }
3231                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3232                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3233                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3234                    return PackageManager.PERMISSION_GRANTED;
3235                }
3236            }
3237        }
3238
3239        return PackageManager.PERMISSION_DENIED;
3240    }
3241
3242    @Override
3243    public int checkUidPermission(String permName, int uid) {
3244        final int userId = UserHandle.getUserId(uid);
3245
3246        if (!sUserManager.exists(userId)) {
3247            return PackageManager.PERMISSION_DENIED;
3248        }
3249
3250        synchronized (mPackages) {
3251            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3252            if (obj != null) {
3253                final SettingBase ps = (SettingBase) obj;
3254                final PermissionsState permissionsState = ps.getPermissionsState();
3255                if (permissionsState.hasPermission(permName, userId)) {
3256                    return PackageManager.PERMISSION_GRANTED;
3257                }
3258                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3259                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3260                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3261                    return PackageManager.PERMISSION_GRANTED;
3262                }
3263            } else {
3264                ArraySet<String> perms = mSystemPermissions.get(uid);
3265                if (perms != null) {
3266                    if (perms.contains(permName)) {
3267                        return PackageManager.PERMISSION_GRANTED;
3268                    }
3269                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3270                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3271                        return PackageManager.PERMISSION_GRANTED;
3272                    }
3273                }
3274            }
3275        }
3276
3277        return PackageManager.PERMISSION_DENIED;
3278    }
3279
3280    @Override
3281    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3282        if (UserHandle.getCallingUserId() != userId) {
3283            mContext.enforceCallingPermission(
3284                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3285                    "isPermissionRevokedByPolicy for user " + userId);
3286        }
3287
3288        if (checkPermission(permission, packageName, userId)
3289                == PackageManager.PERMISSION_GRANTED) {
3290            return false;
3291        }
3292
3293        final long identity = Binder.clearCallingIdentity();
3294        try {
3295            final int flags = getPermissionFlags(permission, packageName, userId);
3296            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3297        } finally {
3298            Binder.restoreCallingIdentity(identity);
3299        }
3300    }
3301
3302    @Override
3303    public String getPermissionControllerPackageName() {
3304        synchronized (mPackages) {
3305            return mRequiredInstallerPackage;
3306        }
3307    }
3308
3309    /**
3310     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3311     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3312     * @param checkShell TODO(yamasani):
3313     * @param message the message to log on security exception
3314     */
3315    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3316            boolean checkShell, String message) {
3317        if (userId < 0) {
3318            throw new IllegalArgumentException("Invalid userId " + userId);
3319        }
3320        if (checkShell) {
3321            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3322        }
3323        if (userId == UserHandle.getUserId(callingUid)) return;
3324        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3325            if (requireFullPermission) {
3326                mContext.enforceCallingOrSelfPermission(
3327                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3328            } else {
3329                try {
3330                    mContext.enforceCallingOrSelfPermission(
3331                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3332                } catch (SecurityException se) {
3333                    mContext.enforceCallingOrSelfPermission(
3334                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3335                }
3336            }
3337        }
3338    }
3339
3340    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3341        if (callingUid == Process.SHELL_UID) {
3342            if (userHandle >= 0
3343                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3344                throw new SecurityException("Shell does not have permission to access user "
3345                        + userHandle);
3346            } else if (userHandle < 0) {
3347                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3348                        + Debug.getCallers(3));
3349            }
3350        }
3351    }
3352
3353    private BasePermission findPermissionTreeLP(String permName) {
3354        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3355            if (permName.startsWith(bp.name) &&
3356                    permName.length() > bp.name.length() &&
3357                    permName.charAt(bp.name.length()) == '.') {
3358                return bp;
3359            }
3360        }
3361        return null;
3362    }
3363
3364    private BasePermission checkPermissionTreeLP(String permName) {
3365        if (permName != null) {
3366            BasePermission bp = findPermissionTreeLP(permName);
3367            if (bp != null) {
3368                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3369                    return bp;
3370                }
3371                throw new SecurityException("Calling uid "
3372                        + Binder.getCallingUid()
3373                        + " is not allowed to add to permission tree "
3374                        + bp.name + " owned by uid " + bp.uid);
3375            }
3376        }
3377        throw new SecurityException("No permission tree found for " + permName);
3378    }
3379
3380    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3381        if (s1 == null) {
3382            return s2 == null;
3383        }
3384        if (s2 == null) {
3385            return false;
3386        }
3387        if (s1.getClass() != s2.getClass()) {
3388            return false;
3389        }
3390        return s1.equals(s2);
3391    }
3392
3393    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3394        if (pi1.icon != pi2.icon) return false;
3395        if (pi1.logo != pi2.logo) return false;
3396        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3397        if (!compareStrings(pi1.name, pi2.name)) return false;
3398        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3399        // We'll take care of setting this one.
3400        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3401        // These are not currently stored in settings.
3402        //if (!compareStrings(pi1.group, pi2.group)) return false;
3403        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3404        //if (pi1.labelRes != pi2.labelRes) return false;
3405        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3406        return true;
3407    }
3408
3409    int permissionInfoFootprint(PermissionInfo info) {
3410        int size = info.name.length();
3411        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3412        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3413        return size;
3414    }
3415
3416    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3417        int size = 0;
3418        for (BasePermission perm : mSettings.mPermissions.values()) {
3419            if (perm.uid == tree.uid) {
3420                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3421            }
3422        }
3423        return size;
3424    }
3425
3426    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3427        // We calculate the max size of permissions defined by this uid and throw
3428        // if that plus the size of 'info' would exceed our stated maximum.
3429        if (tree.uid != Process.SYSTEM_UID) {
3430            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3431            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3432                throw new SecurityException("Permission tree size cap exceeded");
3433            }
3434        }
3435    }
3436
3437    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3438        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3439            throw new SecurityException("Label must be specified in permission");
3440        }
3441        BasePermission tree = checkPermissionTreeLP(info.name);
3442        BasePermission bp = mSettings.mPermissions.get(info.name);
3443        boolean added = bp == null;
3444        boolean changed = true;
3445        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3446        if (added) {
3447            enforcePermissionCapLocked(info, tree);
3448            bp = new BasePermission(info.name, tree.sourcePackage,
3449                    BasePermission.TYPE_DYNAMIC);
3450        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3451            throw new SecurityException(
3452                    "Not allowed to modify non-dynamic permission "
3453                    + info.name);
3454        } else {
3455            if (bp.protectionLevel == fixedLevel
3456                    && bp.perm.owner.equals(tree.perm.owner)
3457                    && bp.uid == tree.uid
3458                    && comparePermissionInfos(bp.perm.info, info)) {
3459                changed = false;
3460            }
3461        }
3462        bp.protectionLevel = fixedLevel;
3463        info = new PermissionInfo(info);
3464        info.protectionLevel = fixedLevel;
3465        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3466        bp.perm.info.packageName = tree.perm.info.packageName;
3467        bp.uid = tree.uid;
3468        if (added) {
3469            mSettings.mPermissions.put(info.name, bp);
3470        }
3471        if (changed) {
3472            if (!async) {
3473                mSettings.writeLPr();
3474            } else {
3475                scheduleWriteSettingsLocked();
3476            }
3477        }
3478        return added;
3479    }
3480
3481    @Override
3482    public boolean addPermission(PermissionInfo info) {
3483        synchronized (mPackages) {
3484            return addPermissionLocked(info, false);
3485        }
3486    }
3487
3488    @Override
3489    public boolean addPermissionAsync(PermissionInfo info) {
3490        synchronized (mPackages) {
3491            return addPermissionLocked(info, true);
3492        }
3493    }
3494
3495    @Override
3496    public void removePermission(String name) {
3497        synchronized (mPackages) {
3498            checkPermissionTreeLP(name);
3499            BasePermission bp = mSettings.mPermissions.get(name);
3500            if (bp != null) {
3501                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3502                    throw new SecurityException(
3503                            "Not allowed to modify non-dynamic permission "
3504                            + name);
3505                }
3506                mSettings.mPermissions.remove(name);
3507                mSettings.writeLPr();
3508            }
3509        }
3510    }
3511
3512    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3513            BasePermission bp) {
3514        int index = pkg.requestedPermissions.indexOf(bp.name);
3515        if (index == -1) {
3516            throw new SecurityException("Package " + pkg.packageName
3517                    + " has not requested permission " + bp.name);
3518        }
3519        if (!bp.isRuntime() && !bp.isDevelopment()) {
3520            throw new SecurityException("Permission " + bp.name
3521                    + " is not a changeable permission type");
3522        }
3523    }
3524
3525    @Override
3526    public void grantRuntimePermission(String packageName, String name, final int userId) {
3527        if (!sUserManager.exists(userId)) {
3528            Log.e(TAG, "No such user:" + userId);
3529            return;
3530        }
3531
3532        mContext.enforceCallingOrSelfPermission(
3533                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3534                "grantRuntimePermission");
3535
3536        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3537                "grantRuntimePermission");
3538
3539        final int uid;
3540        final SettingBase sb;
3541
3542        synchronized (mPackages) {
3543            final PackageParser.Package pkg = mPackages.get(packageName);
3544            if (pkg == null) {
3545                throw new IllegalArgumentException("Unknown package: " + packageName);
3546            }
3547
3548            final BasePermission bp = mSettings.mPermissions.get(name);
3549            if (bp == null) {
3550                throw new IllegalArgumentException("Unknown permission: " + name);
3551            }
3552
3553            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3554
3555            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3556            sb = (SettingBase) pkg.mExtras;
3557            if (sb == null) {
3558                throw new IllegalArgumentException("Unknown package: " + packageName);
3559            }
3560
3561            final PermissionsState permissionsState = sb.getPermissionsState();
3562
3563            final int flags = permissionsState.getPermissionFlags(name, userId);
3564            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3565                throw new SecurityException("Cannot grant system fixed permission: "
3566                        + name + " for package: " + packageName);
3567            }
3568
3569            if (bp.isDevelopment()) {
3570                // Development permissions must be handled specially, since they are not
3571                // normal runtime permissions.  For now they apply to all users.
3572                if (permissionsState.grantInstallPermission(bp) !=
3573                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3574                    scheduleWriteSettingsLocked();
3575                }
3576                return;
3577            }
3578
3579            final int result = permissionsState.grantRuntimePermission(bp, userId);
3580            switch (result) {
3581                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3582                    return;
3583                }
3584
3585                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3586                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3587                    mHandler.post(new Runnable() {
3588                        @Override
3589                        public void run() {
3590                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3591                        }
3592                    });
3593                }
3594                break;
3595            }
3596
3597            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3598
3599            // Not critical if that is lost - app has to request again.
3600            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3601        }
3602
3603        // Only need to do this if user is initialized. Otherwise it's a new user
3604        // and there are no processes running as the user yet and there's no need
3605        // to make an expensive call to remount processes for the changed permissions.
3606        if (READ_EXTERNAL_STORAGE.equals(name)
3607                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3608            final long token = Binder.clearCallingIdentity();
3609            try {
3610                if (sUserManager.isInitialized(userId)) {
3611                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3612                            MountServiceInternal.class);
3613                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3614                }
3615            } finally {
3616                Binder.restoreCallingIdentity(token);
3617            }
3618        }
3619    }
3620
3621    @Override
3622    public void revokeRuntimePermission(String packageName, String name, int userId) {
3623        if (!sUserManager.exists(userId)) {
3624            Log.e(TAG, "No such user:" + userId);
3625            return;
3626        }
3627
3628        mContext.enforceCallingOrSelfPermission(
3629                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3630                "revokeRuntimePermission");
3631
3632        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3633                "revokeRuntimePermission");
3634
3635        final int appId;
3636
3637        synchronized (mPackages) {
3638            final PackageParser.Package pkg = mPackages.get(packageName);
3639            if (pkg == null) {
3640                throw new IllegalArgumentException("Unknown package: " + packageName);
3641            }
3642
3643            final BasePermission bp = mSettings.mPermissions.get(name);
3644            if (bp == null) {
3645                throw new IllegalArgumentException("Unknown permission: " + name);
3646            }
3647
3648            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3649
3650            SettingBase sb = (SettingBase) pkg.mExtras;
3651            if (sb == null) {
3652                throw new IllegalArgumentException("Unknown package: " + packageName);
3653            }
3654
3655            final PermissionsState permissionsState = sb.getPermissionsState();
3656
3657            final int flags = permissionsState.getPermissionFlags(name, userId);
3658            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3659                throw new SecurityException("Cannot revoke system fixed permission: "
3660                        + name + " for package: " + packageName);
3661            }
3662
3663            if (bp.isDevelopment()) {
3664                // Development permissions must be handled specially, since they are not
3665                // normal runtime permissions.  For now they apply to all users.
3666                if (permissionsState.revokeInstallPermission(bp) !=
3667                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3668                    scheduleWriteSettingsLocked();
3669                }
3670                return;
3671            }
3672
3673            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3674                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3675                return;
3676            }
3677
3678            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3679
3680            // Critical, after this call app should never have the permission.
3681            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3682
3683            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3684        }
3685
3686        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3687    }
3688
3689    @Override
3690    public void resetRuntimePermissions() {
3691        mContext.enforceCallingOrSelfPermission(
3692                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3693                "revokeRuntimePermission");
3694
3695        int callingUid = Binder.getCallingUid();
3696        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3697            mContext.enforceCallingOrSelfPermission(
3698                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3699                    "resetRuntimePermissions");
3700        }
3701
3702        synchronized (mPackages) {
3703            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3704            for (int userId : UserManagerService.getInstance().getUserIds()) {
3705                final int packageCount = mPackages.size();
3706                for (int i = 0; i < packageCount; i++) {
3707                    PackageParser.Package pkg = mPackages.valueAt(i);
3708                    if (!(pkg.mExtras instanceof PackageSetting)) {
3709                        continue;
3710                    }
3711                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3712                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3713                }
3714            }
3715        }
3716    }
3717
3718    @Override
3719    public int getPermissionFlags(String name, String packageName, int userId) {
3720        if (!sUserManager.exists(userId)) {
3721            return 0;
3722        }
3723
3724        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3725
3726        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3727                "getPermissionFlags");
3728
3729        synchronized (mPackages) {
3730            final PackageParser.Package pkg = mPackages.get(packageName);
3731            if (pkg == null) {
3732                throw new IllegalArgumentException("Unknown package: " + packageName);
3733            }
3734
3735            final BasePermission bp = mSettings.mPermissions.get(name);
3736            if (bp == null) {
3737                throw new IllegalArgumentException("Unknown permission: " + name);
3738            }
3739
3740            SettingBase sb = (SettingBase) pkg.mExtras;
3741            if (sb == null) {
3742                throw new IllegalArgumentException("Unknown package: " + packageName);
3743            }
3744
3745            PermissionsState permissionsState = sb.getPermissionsState();
3746            return permissionsState.getPermissionFlags(name, userId);
3747        }
3748    }
3749
3750    @Override
3751    public void updatePermissionFlags(String name, String packageName, int flagMask,
3752            int flagValues, int userId) {
3753        if (!sUserManager.exists(userId)) {
3754            return;
3755        }
3756
3757        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3758
3759        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3760                "updatePermissionFlags");
3761
3762        // Only the system can change these flags and nothing else.
3763        if (getCallingUid() != Process.SYSTEM_UID) {
3764            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3765            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3766            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3767            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3768        }
3769
3770        synchronized (mPackages) {
3771            final PackageParser.Package pkg = mPackages.get(packageName);
3772            if (pkg == null) {
3773                throw new IllegalArgumentException("Unknown package: " + packageName);
3774            }
3775
3776            final BasePermission bp = mSettings.mPermissions.get(name);
3777            if (bp == null) {
3778                throw new IllegalArgumentException("Unknown permission: " + name);
3779            }
3780
3781            SettingBase sb = (SettingBase) pkg.mExtras;
3782            if (sb == null) {
3783                throw new IllegalArgumentException("Unknown package: " + packageName);
3784            }
3785
3786            PermissionsState permissionsState = sb.getPermissionsState();
3787
3788            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3789
3790            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3791                // Install and runtime permissions are stored in different places,
3792                // so figure out what permission changed and persist the change.
3793                if (permissionsState.getInstallPermissionState(name) != null) {
3794                    scheduleWriteSettingsLocked();
3795                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3796                        || hadState) {
3797                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3798                }
3799            }
3800        }
3801    }
3802
3803    /**
3804     * Update the permission flags for all packages and runtime permissions of a user in order
3805     * to allow device or profile owner to remove POLICY_FIXED.
3806     */
3807    @Override
3808    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3809        if (!sUserManager.exists(userId)) {
3810            return;
3811        }
3812
3813        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3814
3815        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3816                "updatePermissionFlagsForAllApps");
3817
3818        // Only the system can change system fixed flags.
3819        if (getCallingUid() != Process.SYSTEM_UID) {
3820            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3821            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3822        }
3823
3824        synchronized (mPackages) {
3825            boolean changed = false;
3826            final int packageCount = mPackages.size();
3827            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3828                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3829                SettingBase sb = (SettingBase) pkg.mExtras;
3830                if (sb == null) {
3831                    continue;
3832                }
3833                PermissionsState permissionsState = sb.getPermissionsState();
3834                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3835                        userId, flagMask, flagValues);
3836            }
3837            if (changed) {
3838                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3839            }
3840        }
3841    }
3842
3843    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3844        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3845                != PackageManager.PERMISSION_GRANTED
3846            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3847                != PackageManager.PERMISSION_GRANTED) {
3848            throw new SecurityException(message + " requires "
3849                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3850                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3851        }
3852    }
3853
3854    @Override
3855    public boolean shouldShowRequestPermissionRationale(String permissionName,
3856            String packageName, int userId) {
3857        if (UserHandle.getCallingUserId() != userId) {
3858            mContext.enforceCallingPermission(
3859                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3860                    "canShowRequestPermissionRationale for user " + userId);
3861        }
3862
3863        final int uid = getPackageUid(packageName, userId);
3864        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3865            return false;
3866        }
3867
3868        if (checkPermission(permissionName, packageName, userId)
3869                == PackageManager.PERMISSION_GRANTED) {
3870            return false;
3871        }
3872
3873        final int flags;
3874
3875        final long identity = Binder.clearCallingIdentity();
3876        try {
3877            flags = getPermissionFlags(permissionName,
3878                    packageName, userId);
3879        } finally {
3880            Binder.restoreCallingIdentity(identity);
3881        }
3882
3883        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3884                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3885                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3886
3887        if ((flags & fixedFlags) != 0) {
3888            return false;
3889        }
3890
3891        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3892    }
3893
3894    @Override
3895    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3896        mContext.enforceCallingOrSelfPermission(
3897                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3898                "addOnPermissionsChangeListener");
3899
3900        synchronized (mPackages) {
3901            mOnPermissionChangeListeners.addListenerLocked(listener);
3902        }
3903    }
3904
3905    @Override
3906    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3907        synchronized (mPackages) {
3908            mOnPermissionChangeListeners.removeListenerLocked(listener);
3909        }
3910    }
3911
3912    @Override
3913    public boolean isProtectedBroadcast(String actionName) {
3914        synchronized (mPackages) {
3915            return mProtectedBroadcasts.contains(actionName);
3916        }
3917    }
3918
3919    @Override
3920    public int checkSignatures(String pkg1, String pkg2) {
3921        synchronized (mPackages) {
3922            final PackageParser.Package p1 = mPackages.get(pkg1);
3923            final PackageParser.Package p2 = mPackages.get(pkg2);
3924            if (p1 == null || p1.mExtras == null
3925                    || p2 == null || p2.mExtras == null) {
3926                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3927            }
3928            return compareSignatures(p1.mSignatures, p2.mSignatures);
3929        }
3930    }
3931
3932    @Override
3933    public int checkUidSignatures(int uid1, int uid2) {
3934        // Map to base uids.
3935        uid1 = UserHandle.getAppId(uid1);
3936        uid2 = UserHandle.getAppId(uid2);
3937        // reader
3938        synchronized (mPackages) {
3939            Signature[] s1;
3940            Signature[] s2;
3941            Object obj = mSettings.getUserIdLPr(uid1);
3942            if (obj != null) {
3943                if (obj instanceof SharedUserSetting) {
3944                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3945                } else if (obj instanceof PackageSetting) {
3946                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3947                } else {
3948                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3949                }
3950            } else {
3951                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3952            }
3953            obj = mSettings.getUserIdLPr(uid2);
3954            if (obj != null) {
3955                if (obj instanceof SharedUserSetting) {
3956                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3957                } else if (obj instanceof PackageSetting) {
3958                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3959                } else {
3960                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3961                }
3962            } else {
3963                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3964            }
3965            return compareSignatures(s1, s2);
3966        }
3967    }
3968
3969    private void killUid(int appId, int userId, String reason) {
3970        final long identity = Binder.clearCallingIdentity();
3971        try {
3972            IActivityManager am = ActivityManagerNative.getDefault();
3973            if (am != null) {
3974                try {
3975                    am.killUid(appId, userId, reason);
3976                } catch (RemoteException e) {
3977                    /* ignore - same process */
3978                }
3979            }
3980        } finally {
3981            Binder.restoreCallingIdentity(identity);
3982        }
3983    }
3984
3985    /**
3986     * Compares two sets of signatures. Returns:
3987     * <br />
3988     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3989     * <br />
3990     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3991     * <br />
3992     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3993     * <br />
3994     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3995     * <br />
3996     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3997     */
3998    static int compareSignatures(Signature[] s1, Signature[] s2) {
3999        if (s1 == null) {
4000            return s2 == null
4001                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4002                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4003        }
4004
4005        if (s2 == null) {
4006            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4007        }
4008
4009        if (s1.length != s2.length) {
4010            return PackageManager.SIGNATURE_NO_MATCH;
4011        }
4012
4013        // Since both signature sets are of size 1, we can compare without HashSets.
4014        if (s1.length == 1) {
4015            return s1[0].equals(s2[0]) ?
4016                    PackageManager.SIGNATURE_MATCH :
4017                    PackageManager.SIGNATURE_NO_MATCH;
4018        }
4019
4020        ArraySet<Signature> set1 = new ArraySet<Signature>();
4021        for (Signature sig : s1) {
4022            set1.add(sig);
4023        }
4024        ArraySet<Signature> set2 = new ArraySet<Signature>();
4025        for (Signature sig : s2) {
4026            set2.add(sig);
4027        }
4028        // Make sure s2 contains all signatures in s1.
4029        if (set1.equals(set2)) {
4030            return PackageManager.SIGNATURE_MATCH;
4031        }
4032        return PackageManager.SIGNATURE_NO_MATCH;
4033    }
4034
4035    /**
4036     * If the database version for this type of package (internal storage or
4037     * external storage) is less than the version where package signatures
4038     * were updated, return true.
4039     */
4040    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4041        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4042        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4043    }
4044
4045    /**
4046     * Used for backward compatibility to make sure any packages with
4047     * certificate chains get upgraded to the new style. {@code existingSigs}
4048     * will be in the old format (since they were stored on disk from before the
4049     * system upgrade) and {@code scannedSigs} will be in the newer format.
4050     */
4051    private int compareSignaturesCompat(PackageSignatures existingSigs,
4052            PackageParser.Package scannedPkg) {
4053        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4054            return PackageManager.SIGNATURE_NO_MATCH;
4055        }
4056
4057        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4058        for (Signature sig : existingSigs.mSignatures) {
4059            existingSet.add(sig);
4060        }
4061        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4062        for (Signature sig : scannedPkg.mSignatures) {
4063            try {
4064                Signature[] chainSignatures = sig.getChainSignatures();
4065                for (Signature chainSig : chainSignatures) {
4066                    scannedCompatSet.add(chainSig);
4067                }
4068            } catch (CertificateEncodingException e) {
4069                scannedCompatSet.add(sig);
4070            }
4071        }
4072        /*
4073         * Make sure the expanded scanned set contains all signatures in the
4074         * existing one.
4075         */
4076        if (scannedCompatSet.equals(existingSet)) {
4077            // Migrate the old signatures to the new scheme.
4078            existingSigs.assignSignatures(scannedPkg.mSignatures);
4079            // The new KeySets will be re-added later in the scanning process.
4080            synchronized (mPackages) {
4081                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4082            }
4083            return PackageManager.SIGNATURE_MATCH;
4084        }
4085        return PackageManager.SIGNATURE_NO_MATCH;
4086    }
4087
4088    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4089        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4090        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4091    }
4092
4093    private int compareSignaturesRecover(PackageSignatures existingSigs,
4094            PackageParser.Package scannedPkg) {
4095        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4096            return PackageManager.SIGNATURE_NO_MATCH;
4097        }
4098
4099        String msg = null;
4100        try {
4101            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4102                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4103                        + scannedPkg.packageName);
4104                return PackageManager.SIGNATURE_MATCH;
4105            }
4106        } catch (CertificateException e) {
4107            msg = e.getMessage();
4108        }
4109
4110        logCriticalInfo(Log.INFO,
4111                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4112        return PackageManager.SIGNATURE_NO_MATCH;
4113    }
4114
4115    @Override
4116    public String[] getPackagesForUid(int uid) {
4117        uid = UserHandle.getAppId(uid);
4118        // reader
4119        synchronized (mPackages) {
4120            Object obj = mSettings.getUserIdLPr(uid);
4121            if (obj instanceof SharedUserSetting) {
4122                final SharedUserSetting sus = (SharedUserSetting) obj;
4123                final int N = sus.packages.size();
4124                final String[] res = new String[N];
4125                final Iterator<PackageSetting> it = sus.packages.iterator();
4126                int i = 0;
4127                while (it.hasNext()) {
4128                    res[i++] = it.next().name;
4129                }
4130                return res;
4131            } else if (obj instanceof PackageSetting) {
4132                final PackageSetting ps = (PackageSetting) obj;
4133                return new String[] { ps.name };
4134            }
4135        }
4136        return null;
4137    }
4138
4139    @Override
4140    public String getNameForUid(int uid) {
4141        // reader
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.name + ":" + sus.userId;
4147            } else if (obj instanceof PackageSetting) {
4148                final PackageSetting ps = (PackageSetting) obj;
4149                return ps.name;
4150            }
4151        }
4152        return null;
4153    }
4154
4155    @Override
4156    public int getUidForSharedUser(String sharedUserName) {
4157        if(sharedUserName == null) {
4158            return -1;
4159        }
4160        // reader
4161        synchronized (mPackages) {
4162            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4163            if (suid == null) {
4164                return -1;
4165            }
4166            return suid.userId;
4167        }
4168    }
4169
4170    @Override
4171    public int getFlagsForUid(int uid) {
4172        synchronized (mPackages) {
4173            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4174            if (obj instanceof SharedUserSetting) {
4175                final SharedUserSetting sus = (SharedUserSetting) obj;
4176                return sus.pkgFlags;
4177            } else if (obj instanceof PackageSetting) {
4178                final PackageSetting ps = (PackageSetting) obj;
4179                return ps.pkgFlags;
4180            }
4181        }
4182        return 0;
4183    }
4184
4185    @Override
4186    public int getPrivateFlagsForUid(int uid) {
4187        synchronized (mPackages) {
4188            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4189            if (obj instanceof SharedUserSetting) {
4190                final SharedUserSetting sus = (SharedUserSetting) obj;
4191                return sus.pkgPrivateFlags;
4192            } else if (obj instanceof PackageSetting) {
4193                final PackageSetting ps = (PackageSetting) obj;
4194                return ps.pkgPrivateFlags;
4195            }
4196        }
4197        return 0;
4198    }
4199
4200    @Override
4201    public boolean isUidPrivileged(int uid) {
4202        uid = UserHandle.getAppId(uid);
4203        // reader
4204        synchronized (mPackages) {
4205            Object obj = mSettings.getUserIdLPr(uid);
4206            if (obj instanceof SharedUserSetting) {
4207                final SharedUserSetting sus = (SharedUserSetting) obj;
4208                final Iterator<PackageSetting> it = sus.packages.iterator();
4209                while (it.hasNext()) {
4210                    if (it.next().isPrivileged()) {
4211                        return true;
4212                    }
4213                }
4214            } else if (obj instanceof PackageSetting) {
4215                final PackageSetting ps = (PackageSetting) obj;
4216                return ps.isPrivileged();
4217            }
4218        }
4219        return false;
4220    }
4221
4222    @Override
4223    public String[] getAppOpPermissionPackages(String permissionName) {
4224        synchronized (mPackages) {
4225            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4226            if (pkgs == null) {
4227                return null;
4228            }
4229            return pkgs.toArray(new String[pkgs.size()]);
4230        }
4231    }
4232
4233    @Override
4234    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4235            int flags, int userId) {
4236        if (!sUserManager.exists(userId)) return null;
4237        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4238        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4239        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4240    }
4241
4242    @Override
4243    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4244            IntentFilter filter, int match, ComponentName activity) {
4245        final int userId = UserHandle.getCallingUserId();
4246        if (DEBUG_PREFERRED) {
4247            Log.v(TAG, "setLastChosenActivity intent=" + intent
4248                + " resolvedType=" + resolvedType
4249                + " flags=" + flags
4250                + " filter=" + filter
4251                + " match=" + match
4252                + " activity=" + activity);
4253            filter.dump(new PrintStreamPrinter(System.out), "    ");
4254        }
4255        intent.setComponent(null);
4256        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4257        // Find any earlier preferred or last chosen entries and nuke them
4258        findPreferredActivity(intent, resolvedType,
4259                flags, query, 0, false, true, false, userId);
4260        // Add the new activity as the last chosen for this filter
4261        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4262                "Setting last chosen");
4263    }
4264
4265    @Override
4266    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4267        final int userId = UserHandle.getCallingUserId();
4268        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4269        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4270        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4271                false, false, false, userId);
4272    }
4273
4274    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4275            int flags, List<ResolveInfo> query, int userId) {
4276        if (query != null) {
4277            final int N = query.size();
4278            if (N == 1) {
4279                return query.get(0);
4280            } else if (N > 1) {
4281                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4282                // If there is more than one activity with the same priority,
4283                // then let the user decide between them.
4284                ResolveInfo r0 = query.get(0);
4285                ResolveInfo r1 = query.get(1);
4286                if (DEBUG_INTENT_MATCHING || debug) {
4287                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4288                            + r1.activityInfo.name + "=" + r1.priority);
4289                }
4290                // If the first activity has a higher priority, or a different
4291                // default, then it is always desireable to pick it.
4292                if (r0.priority != r1.priority
4293                        || r0.preferredOrder != r1.preferredOrder
4294                        || r0.isDefault != r1.isDefault) {
4295                    return query.get(0);
4296                }
4297                // If we have saved a preference for a preferred activity for
4298                // this Intent, use that.
4299                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4300                        flags, query, r0.priority, true, false, debug, userId);
4301                if (ri != null) {
4302                    return ri;
4303                }
4304                ri = new ResolveInfo(mResolveInfo);
4305                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4306                ri.activityInfo.applicationInfo = new ApplicationInfo(
4307                        ri.activityInfo.applicationInfo);
4308                if (userId != 0) {
4309                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4310                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4311                }
4312                // Make sure that the resolver is displayable in car mode
4313                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4314                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4315                return ri;
4316            }
4317        }
4318        return null;
4319    }
4320
4321    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4322            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4323        final int N = query.size();
4324        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4325                .get(userId);
4326        // Get the list of persistent preferred activities that handle the intent
4327        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4328        List<PersistentPreferredActivity> pprefs = ppir != null
4329                ? ppir.queryIntent(intent, resolvedType,
4330                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4331                : null;
4332        if (pprefs != null && pprefs.size() > 0) {
4333            final int M = pprefs.size();
4334            for (int i=0; i<M; i++) {
4335                final PersistentPreferredActivity ppa = pprefs.get(i);
4336                if (DEBUG_PREFERRED || debug) {
4337                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4338                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4339                            + "\n  component=" + ppa.mComponent);
4340                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4341                }
4342                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4343                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4344                if (DEBUG_PREFERRED || debug) {
4345                    Slog.v(TAG, "Found persistent preferred activity:");
4346                    if (ai != null) {
4347                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4348                    } else {
4349                        Slog.v(TAG, "  null");
4350                    }
4351                }
4352                if (ai == null) {
4353                    // This previously registered persistent preferred activity
4354                    // component is no longer known. Ignore it and do NOT remove it.
4355                    continue;
4356                }
4357                for (int j=0; j<N; j++) {
4358                    final ResolveInfo ri = query.get(j);
4359                    if (!ri.activityInfo.applicationInfo.packageName
4360                            .equals(ai.applicationInfo.packageName)) {
4361                        continue;
4362                    }
4363                    if (!ri.activityInfo.name.equals(ai.name)) {
4364                        continue;
4365                    }
4366                    //  Found a persistent preference that can handle the intent.
4367                    if (DEBUG_PREFERRED || debug) {
4368                        Slog.v(TAG, "Returning persistent preferred activity: " +
4369                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4370                    }
4371                    return ri;
4372                }
4373            }
4374        }
4375        return null;
4376    }
4377
4378    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4379            List<ResolveInfo> query, int priority, boolean always,
4380            boolean removeMatches, boolean debug, int userId) {
4381        if (!sUserManager.exists(userId)) return null;
4382        // writer
4383        synchronized (mPackages) {
4384            if (intent.getSelector() != null) {
4385                intent = intent.getSelector();
4386            }
4387            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4388
4389            // Try to find a matching persistent preferred activity.
4390            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4391                    debug, userId);
4392
4393            // If a persistent preferred activity matched, use it.
4394            if (pri != null) {
4395                return pri;
4396            }
4397
4398            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4399            // Get the list of preferred activities that handle the intent
4400            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4401            List<PreferredActivity> prefs = pir != null
4402                    ? pir.queryIntent(intent, resolvedType,
4403                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4404                    : null;
4405            if (prefs != null && prefs.size() > 0) {
4406                boolean changed = false;
4407                try {
4408                    // First figure out how good the original match set is.
4409                    // We will only allow preferred activities that came
4410                    // from the same match quality.
4411                    int match = 0;
4412
4413                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4414
4415                    final int N = query.size();
4416                    for (int j=0; j<N; j++) {
4417                        final ResolveInfo ri = query.get(j);
4418                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4419                                + ": 0x" + Integer.toHexString(match));
4420                        if (ri.match > match) {
4421                            match = ri.match;
4422                        }
4423                    }
4424
4425                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4426                            + Integer.toHexString(match));
4427
4428                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4429                    final int M = prefs.size();
4430                    for (int i=0; i<M; i++) {
4431                        final PreferredActivity pa = prefs.get(i);
4432                        if (DEBUG_PREFERRED || debug) {
4433                            Slog.v(TAG, "Checking PreferredActivity ds="
4434                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4435                                    + "\n  component=" + pa.mPref.mComponent);
4436                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4437                        }
4438                        if (pa.mPref.mMatch != match) {
4439                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4440                                    + Integer.toHexString(pa.mPref.mMatch));
4441                            continue;
4442                        }
4443                        // If it's not an "always" type preferred activity and that's what we're
4444                        // looking for, skip it.
4445                        if (always && !pa.mPref.mAlways) {
4446                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4447                            continue;
4448                        }
4449                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4450                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4451                        if (DEBUG_PREFERRED || debug) {
4452                            Slog.v(TAG, "Found preferred activity:");
4453                            if (ai != null) {
4454                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4455                            } else {
4456                                Slog.v(TAG, "  null");
4457                            }
4458                        }
4459                        if (ai == null) {
4460                            // This previously registered preferred activity
4461                            // component is no longer known.  Most likely an update
4462                            // to the app was installed and in the new version this
4463                            // component no longer exists.  Clean it up by removing
4464                            // it from the preferred activities list, and skip it.
4465                            Slog.w(TAG, "Removing dangling preferred activity: "
4466                                    + pa.mPref.mComponent);
4467                            pir.removeFilter(pa);
4468                            changed = true;
4469                            continue;
4470                        }
4471                        for (int j=0; j<N; j++) {
4472                            final ResolveInfo ri = query.get(j);
4473                            if (!ri.activityInfo.applicationInfo.packageName
4474                                    .equals(ai.applicationInfo.packageName)) {
4475                                continue;
4476                            }
4477                            if (!ri.activityInfo.name.equals(ai.name)) {
4478                                continue;
4479                            }
4480
4481                            if (removeMatches) {
4482                                pir.removeFilter(pa);
4483                                changed = true;
4484                                if (DEBUG_PREFERRED) {
4485                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4486                                }
4487                                break;
4488                            }
4489
4490                            // Okay we found a previously set preferred or last chosen app.
4491                            // If the result set is different from when this
4492                            // was created, we need to clear it and re-ask the
4493                            // user their preference, if we're looking for an "always" type entry.
4494                            if (always && !pa.mPref.sameSet(query)) {
4495                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4496                                        + intent + " type " + resolvedType);
4497                                if (DEBUG_PREFERRED) {
4498                                    Slog.v(TAG, "Removing preferred activity since set changed "
4499                                            + pa.mPref.mComponent);
4500                                }
4501                                pir.removeFilter(pa);
4502                                // Re-add the filter as a "last chosen" entry (!always)
4503                                PreferredActivity lastChosen = new PreferredActivity(
4504                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4505                                pir.addFilter(lastChosen);
4506                                changed = true;
4507                                return null;
4508                            }
4509
4510                            // Yay! Either the set matched or we're looking for the last chosen
4511                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4512                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4513                            return ri;
4514                        }
4515                    }
4516                } finally {
4517                    if (changed) {
4518                        if (DEBUG_PREFERRED) {
4519                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4520                        }
4521                        scheduleWritePackageRestrictionsLocked(userId);
4522                    }
4523                }
4524            }
4525        }
4526        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4527        return null;
4528    }
4529
4530    /*
4531     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4532     */
4533    @Override
4534    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4535            int targetUserId) {
4536        mContext.enforceCallingOrSelfPermission(
4537                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4538        List<CrossProfileIntentFilter> matches =
4539                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4540        if (matches != null) {
4541            int size = matches.size();
4542            for (int i = 0; i < size; i++) {
4543                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4544            }
4545        }
4546        if (hasWebURI(intent)) {
4547            // cross-profile app linking works only towards the parent.
4548            final UserInfo parent = getProfileParent(sourceUserId);
4549            synchronized(mPackages) {
4550                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4551                        intent, resolvedType, 0, sourceUserId, parent.id);
4552                return xpDomainInfo != null;
4553            }
4554        }
4555        return false;
4556    }
4557
4558    private UserInfo getProfileParent(int userId) {
4559        final long identity = Binder.clearCallingIdentity();
4560        try {
4561            return sUserManager.getProfileParent(userId);
4562        } finally {
4563            Binder.restoreCallingIdentity(identity);
4564        }
4565    }
4566
4567    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4568            String resolvedType, int userId) {
4569        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4570        if (resolver != null) {
4571            return resolver.queryIntent(intent, resolvedType, false, userId);
4572        }
4573        return null;
4574    }
4575
4576    @Override
4577    public List<ResolveInfo> queryIntentActivities(Intent intent,
4578            String resolvedType, int flags, int userId) {
4579        if (!sUserManager.exists(userId)) return Collections.emptyList();
4580        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4581        ComponentName comp = intent.getComponent();
4582        if (comp == null) {
4583            if (intent.getSelector() != null) {
4584                intent = intent.getSelector();
4585                comp = intent.getComponent();
4586            }
4587        }
4588
4589        if (comp != null) {
4590            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4591            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4592            if (ai != null) {
4593                final ResolveInfo ri = new ResolveInfo();
4594                ri.activityInfo = ai;
4595                list.add(ri);
4596            }
4597            return list;
4598        }
4599
4600        // reader
4601        synchronized (mPackages) {
4602            final String pkgName = intent.getPackage();
4603            if (pkgName == null) {
4604                List<CrossProfileIntentFilter> matchingFilters =
4605                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4606                // Check for results that need to skip the current profile.
4607                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4608                        resolvedType, flags, userId);
4609                if (xpResolveInfo != null) {
4610                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4611                    result.add(xpResolveInfo);
4612                    return filterIfNotSystemUser(result, userId);
4613                }
4614
4615                // Check for results in the current profile.
4616                List<ResolveInfo> result = mActivities.queryIntent(
4617                        intent, resolvedType, flags, userId);
4618
4619                // Check for cross profile results.
4620                xpResolveInfo = queryCrossProfileIntents(
4621                        matchingFilters, intent, resolvedType, flags, userId);
4622                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4623                    result.add(xpResolveInfo);
4624                    Collections.sort(result, mResolvePrioritySorter);
4625                }
4626                result = filterIfNotSystemUser(result, userId);
4627                if (hasWebURI(intent)) {
4628                    CrossProfileDomainInfo xpDomainInfo = null;
4629                    final UserInfo parent = getProfileParent(userId);
4630                    if (parent != null) {
4631                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4632                                flags, userId, parent.id);
4633                    }
4634                    if (xpDomainInfo != null) {
4635                        if (xpResolveInfo != null) {
4636                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4637                            // in the result.
4638                            result.remove(xpResolveInfo);
4639                        }
4640                        if (result.size() == 0) {
4641                            result.add(xpDomainInfo.resolveInfo);
4642                            return result;
4643                        }
4644                    } else if (result.size() <= 1) {
4645                        return result;
4646                    }
4647                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4648                            xpDomainInfo, userId);
4649                    Collections.sort(result, mResolvePrioritySorter);
4650                }
4651                return result;
4652            }
4653            final PackageParser.Package pkg = mPackages.get(pkgName);
4654            if (pkg != null) {
4655                return filterIfNotSystemUser(
4656                        mActivities.queryIntentForPackage(
4657                                intent, resolvedType, flags, pkg.activities, userId),
4658                        userId);
4659            }
4660            return new ArrayList<ResolveInfo>();
4661        }
4662    }
4663
4664    private static class CrossProfileDomainInfo {
4665        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4666        ResolveInfo resolveInfo;
4667        /* Best domain verification status of the activities found in the other profile */
4668        int bestDomainVerificationStatus;
4669    }
4670
4671    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4672            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4673        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4674                sourceUserId)) {
4675            return null;
4676        }
4677        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4678                resolvedType, flags, parentUserId);
4679
4680        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4681            return null;
4682        }
4683        CrossProfileDomainInfo result = null;
4684        int size = resultTargetUser.size();
4685        for (int i = 0; i < size; i++) {
4686            ResolveInfo riTargetUser = resultTargetUser.get(i);
4687            // Intent filter verification is only for filters that specify a host. So don't return
4688            // those that handle all web uris.
4689            if (riTargetUser.handleAllWebDataURI) {
4690                continue;
4691            }
4692            String packageName = riTargetUser.activityInfo.packageName;
4693            PackageSetting ps = mSettings.mPackages.get(packageName);
4694            if (ps == null) {
4695                continue;
4696            }
4697            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4698            int status = (int)(verificationState >> 32);
4699            if (result == null) {
4700                result = new CrossProfileDomainInfo();
4701                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
4702                        sourceUserId, parentUserId);
4703                result.bestDomainVerificationStatus = status;
4704            } else {
4705                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4706                        result.bestDomainVerificationStatus);
4707            }
4708        }
4709        // Don't consider matches with status NEVER across profiles.
4710        if (result != null && result.bestDomainVerificationStatus
4711                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4712            return null;
4713        }
4714        return result;
4715    }
4716
4717    /**
4718     * Verification statuses are ordered from the worse to the best, except for
4719     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4720     */
4721    private int bestDomainVerificationStatus(int status1, int status2) {
4722        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4723            return status2;
4724        }
4725        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4726            return status1;
4727        }
4728        return (int) MathUtils.max(status1, status2);
4729    }
4730
4731    private boolean isUserEnabled(int userId) {
4732        long callingId = Binder.clearCallingIdentity();
4733        try {
4734            UserInfo userInfo = sUserManager.getUserInfo(userId);
4735            return userInfo != null && userInfo.isEnabled();
4736        } finally {
4737            Binder.restoreCallingIdentity(callingId);
4738        }
4739    }
4740
4741    /**
4742     * Filter out activities with systemUserOnly flag set, when current user is not System.
4743     *
4744     * @return filtered list
4745     */
4746    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
4747        if (userId == UserHandle.USER_SYSTEM) {
4748            return resolveInfos;
4749        }
4750        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4751            ResolveInfo info = resolveInfos.get(i);
4752            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
4753                resolveInfos.remove(i);
4754            }
4755        }
4756        return resolveInfos;
4757    }
4758
4759    private static boolean hasWebURI(Intent intent) {
4760        if (intent.getData() == null) {
4761            return false;
4762        }
4763        final String scheme = intent.getScheme();
4764        if (TextUtils.isEmpty(scheme)) {
4765            return false;
4766        }
4767        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4768    }
4769
4770    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4771            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4772            int userId) {
4773        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4774
4775        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4776            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4777                    candidates.size());
4778        }
4779
4780        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4781        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4782        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4783        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
4784        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4785        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4786
4787        synchronized (mPackages) {
4788            final int count = candidates.size();
4789            // First, try to use linked apps. Partition the candidates into four lists:
4790            // one for the final results, one for the "do not use ever", one for "undefined status"
4791            // and finally one for "browser app type".
4792            for (int n=0; n<count; n++) {
4793                ResolveInfo info = candidates.get(n);
4794                String packageName = info.activityInfo.packageName;
4795                PackageSetting ps = mSettings.mPackages.get(packageName);
4796                if (ps != null) {
4797                    // Add to the special match all list (Browser use case)
4798                    if (info.handleAllWebDataURI) {
4799                        matchAllList.add(info);
4800                        continue;
4801                    }
4802                    // Try to get the status from User settings first
4803                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4804                    int status = (int)(packedStatus >> 32);
4805                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4806                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4807                        if (DEBUG_DOMAIN_VERIFICATION) {
4808                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4809                                    + " : linkgen=" + linkGeneration);
4810                        }
4811                        // Use link-enabled generation as preferredOrder, i.e.
4812                        // prefer newly-enabled over earlier-enabled.
4813                        info.preferredOrder = linkGeneration;
4814                        alwaysList.add(info);
4815                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4816                        if (DEBUG_DOMAIN_VERIFICATION) {
4817                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4818                        }
4819                        neverList.add(info);
4820                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4821                        if (DEBUG_DOMAIN_VERIFICATION) {
4822                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
4823                        }
4824                        alwaysAskList.add(info);
4825                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4826                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4827                        if (DEBUG_DOMAIN_VERIFICATION) {
4828                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4829                        }
4830                        undefinedList.add(info);
4831                    }
4832                }
4833            }
4834
4835            // We'll want to include browser possibilities in a few cases
4836            boolean includeBrowser = false;
4837
4838            // First try to add the "always" resolution(s) for the current user, if any
4839            if (alwaysList.size() > 0) {
4840                result.addAll(alwaysList);
4841            } else {
4842                // Add all undefined apps as we want them to appear in the disambiguation dialog.
4843                result.addAll(undefinedList);
4844                // Maybe add one for the other profile.
4845                if (xpDomainInfo != null && (
4846                        xpDomainInfo.bestDomainVerificationStatus
4847                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
4848                    result.add(xpDomainInfo.resolveInfo);
4849                }
4850                includeBrowser = true;
4851            }
4852
4853            // The presence of any 'always ask' alternatives means we'll also offer browsers.
4854            // If there were 'always' entries their preferred order has been set, so we also
4855            // back that off to make the alternatives equivalent
4856            if (alwaysAskList.size() > 0) {
4857                for (ResolveInfo i : result) {
4858                    i.preferredOrder = 0;
4859                }
4860                result.addAll(alwaysAskList);
4861                includeBrowser = true;
4862            }
4863
4864            if (includeBrowser) {
4865                // Also add browsers (all of them or only the default one)
4866                if (DEBUG_DOMAIN_VERIFICATION) {
4867                    Slog.v(TAG, "   ...including browsers in candidate set");
4868                }
4869                if ((matchFlags & MATCH_ALL) != 0) {
4870                    result.addAll(matchAllList);
4871                } else {
4872                    // Browser/generic handling case.  If there's a default browser, go straight
4873                    // to that (but only if there is no other higher-priority match).
4874                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4875                    int maxMatchPrio = 0;
4876                    ResolveInfo defaultBrowserMatch = null;
4877                    final int numCandidates = matchAllList.size();
4878                    for (int n = 0; n < numCandidates; n++) {
4879                        ResolveInfo info = matchAllList.get(n);
4880                        // track the highest overall match priority...
4881                        if (info.priority > maxMatchPrio) {
4882                            maxMatchPrio = info.priority;
4883                        }
4884                        // ...and the highest-priority default browser match
4885                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4886                            if (defaultBrowserMatch == null
4887                                    || (defaultBrowserMatch.priority < info.priority)) {
4888                                if (debug) {
4889                                    Slog.v(TAG, "Considering default browser match " + info);
4890                                }
4891                                defaultBrowserMatch = info;
4892                            }
4893                        }
4894                    }
4895                    if (defaultBrowserMatch != null
4896                            && defaultBrowserMatch.priority >= maxMatchPrio
4897                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4898                    {
4899                        if (debug) {
4900                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4901                        }
4902                        result.add(defaultBrowserMatch);
4903                    } else {
4904                        result.addAll(matchAllList);
4905                    }
4906                }
4907
4908                // If there is nothing selected, add all candidates and remove the ones that the user
4909                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4910                if (result.size() == 0) {
4911                    result.addAll(candidates);
4912                    result.removeAll(neverList);
4913                }
4914            }
4915        }
4916        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4917            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4918                    result.size());
4919            for (ResolveInfo info : result) {
4920                Slog.v(TAG, "  + " + info.activityInfo);
4921            }
4922        }
4923        return result;
4924    }
4925
4926    // Returns a packed value as a long:
4927    //
4928    // high 'int'-sized word: link status: undefined/ask/never/always.
4929    // low 'int'-sized word: relative priority among 'always' results.
4930    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4931        long result = ps.getDomainVerificationStatusForUser(userId);
4932        // if none available, get the master status
4933        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4934            if (ps.getIntentFilterVerificationInfo() != null) {
4935                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4936            }
4937        }
4938        return result;
4939    }
4940
4941    private ResolveInfo querySkipCurrentProfileIntents(
4942            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4943            int flags, int sourceUserId) {
4944        if (matchingFilters != null) {
4945            int size = matchingFilters.size();
4946            for (int i = 0; i < size; i ++) {
4947                CrossProfileIntentFilter filter = matchingFilters.get(i);
4948                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4949                    // Checking if there are activities in the target user that can handle the
4950                    // intent.
4951                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
4952                            resolvedType, flags, sourceUserId);
4953                    if (resolveInfo != null) {
4954                        return resolveInfo;
4955                    }
4956                }
4957            }
4958        }
4959        return null;
4960    }
4961
4962    // Return matching ResolveInfo if any for skip current profile intent filters.
4963    private ResolveInfo queryCrossProfileIntents(
4964            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4965            int flags, int sourceUserId) {
4966        if (matchingFilters != null) {
4967            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4968            // match the same intent. For performance reasons, it is better not to
4969            // run queryIntent twice for the same userId
4970            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4971            int size = matchingFilters.size();
4972            for (int i = 0; i < size; i++) {
4973                CrossProfileIntentFilter filter = matchingFilters.get(i);
4974                int targetUserId = filter.getTargetUserId();
4975                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4976                        && !alreadyTriedUserIds.get(targetUserId)) {
4977                    // Checking if there are activities in the target user that can handle the
4978                    // intent.
4979                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
4980                            resolvedType, flags, sourceUserId);
4981                    if (resolveInfo != null) return resolveInfo;
4982                    alreadyTriedUserIds.put(targetUserId, true);
4983                }
4984            }
4985        }
4986        return null;
4987    }
4988
4989    /**
4990     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
4991     * will forward the intent to the filter's target user.
4992     * Otherwise, returns null.
4993     */
4994    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
4995            String resolvedType, int flags, int sourceUserId) {
4996        int targetUserId = filter.getTargetUserId();
4997        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4998                resolvedType, flags, targetUserId);
4999        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5000                && isUserEnabled(targetUserId)) {
5001            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5002        }
5003        return null;
5004    }
5005
5006    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5007            int sourceUserId, int targetUserId) {
5008        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5009        long ident = Binder.clearCallingIdentity();
5010        boolean targetIsProfile;
5011        try {
5012            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5013        } finally {
5014            Binder.restoreCallingIdentity(ident);
5015        }
5016        String className;
5017        if (targetIsProfile) {
5018            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5019        } else {
5020            className = FORWARD_INTENT_TO_PARENT;
5021        }
5022        ComponentName forwardingActivityComponentName = new ComponentName(
5023                mAndroidApplication.packageName, className);
5024        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5025                sourceUserId);
5026        if (!targetIsProfile) {
5027            forwardingActivityInfo.showUserIcon = targetUserId;
5028            forwardingResolveInfo.noResourceId = true;
5029        }
5030        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5031        forwardingResolveInfo.priority = 0;
5032        forwardingResolveInfo.preferredOrder = 0;
5033        forwardingResolveInfo.match = 0;
5034        forwardingResolveInfo.isDefault = true;
5035        forwardingResolveInfo.filter = filter;
5036        forwardingResolveInfo.targetUserId = targetUserId;
5037        return forwardingResolveInfo;
5038    }
5039
5040    @Override
5041    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5042            Intent[] specifics, String[] specificTypes, Intent intent,
5043            String resolvedType, int flags, int userId) {
5044        if (!sUserManager.exists(userId)) return Collections.emptyList();
5045        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5046                false, "query intent activity options");
5047        final String resultsAction = intent.getAction();
5048
5049        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5050                | PackageManager.GET_RESOLVED_FILTER, userId);
5051
5052        if (DEBUG_INTENT_MATCHING) {
5053            Log.v(TAG, "Query " + intent + ": " + results);
5054        }
5055
5056        int specificsPos = 0;
5057        int N;
5058
5059        // todo: note that the algorithm used here is O(N^2).  This
5060        // isn't a problem in our current environment, but if we start running
5061        // into situations where we have more than 5 or 10 matches then this
5062        // should probably be changed to something smarter...
5063
5064        // First we go through and resolve each of the specific items
5065        // that were supplied, taking care of removing any corresponding
5066        // duplicate items in the generic resolve list.
5067        if (specifics != null) {
5068            for (int i=0; i<specifics.length; i++) {
5069                final Intent sintent = specifics[i];
5070                if (sintent == null) {
5071                    continue;
5072                }
5073
5074                if (DEBUG_INTENT_MATCHING) {
5075                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5076                }
5077
5078                String action = sintent.getAction();
5079                if (resultsAction != null && resultsAction.equals(action)) {
5080                    // If this action was explicitly requested, then don't
5081                    // remove things that have it.
5082                    action = null;
5083                }
5084
5085                ResolveInfo ri = null;
5086                ActivityInfo ai = null;
5087
5088                ComponentName comp = sintent.getComponent();
5089                if (comp == null) {
5090                    ri = resolveIntent(
5091                        sintent,
5092                        specificTypes != null ? specificTypes[i] : null,
5093                            flags, userId);
5094                    if (ri == null) {
5095                        continue;
5096                    }
5097                    if (ri == mResolveInfo) {
5098                        // ACK!  Must do something better with this.
5099                    }
5100                    ai = ri.activityInfo;
5101                    comp = new ComponentName(ai.applicationInfo.packageName,
5102                            ai.name);
5103                } else {
5104                    ai = getActivityInfo(comp, flags, userId);
5105                    if (ai == null) {
5106                        continue;
5107                    }
5108                }
5109
5110                // Look for any generic query activities that are duplicates
5111                // of this specific one, and remove them from the results.
5112                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5113                N = results.size();
5114                int j;
5115                for (j=specificsPos; j<N; j++) {
5116                    ResolveInfo sri = results.get(j);
5117                    if ((sri.activityInfo.name.equals(comp.getClassName())
5118                            && sri.activityInfo.applicationInfo.packageName.equals(
5119                                    comp.getPackageName()))
5120                        || (action != null && sri.filter.matchAction(action))) {
5121                        results.remove(j);
5122                        if (DEBUG_INTENT_MATCHING) Log.v(
5123                            TAG, "Removing duplicate item from " + j
5124                            + " due to specific " + specificsPos);
5125                        if (ri == null) {
5126                            ri = sri;
5127                        }
5128                        j--;
5129                        N--;
5130                    }
5131                }
5132
5133                // Add this specific item to its proper place.
5134                if (ri == null) {
5135                    ri = new ResolveInfo();
5136                    ri.activityInfo = ai;
5137                }
5138                results.add(specificsPos, ri);
5139                ri.specificIndex = i;
5140                specificsPos++;
5141            }
5142        }
5143
5144        // Now we go through the remaining generic results and remove any
5145        // duplicate actions that are found here.
5146        N = results.size();
5147        for (int i=specificsPos; i<N-1; i++) {
5148            final ResolveInfo rii = results.get(i);
5149            if (rii.filter == null) {
5150                continue;
5151            }
5152
5153            // Iterate over all of the actions of this result's intent
5154            // filter...  typically this should be just one.
5155            final Iterator<String> it = rii.filter.actionsIterator();
5156            if (it == null) {
5157                continue;
5158            }
5159            while (it.hasNext()) {
5160                final String action = it.next();
5161                if (resultsAction != null && resultsAction.equals(action)) {
5162                    // If this action was explicitly requested, then don't
5163                    // remove things that have it.
5164                    continue;
5165                }
5166                for (int j=i+1; j<N; j++) {
5167                    final ResolveInfo rij = results.get(j);
5168                    if (rij.filter != null && rij.filter.hasAction(action)) {
5169                        results.remove(j);
5170                        if (DEBUG_INTENT_MATCHING) Log.v(
5171                            TAG, "Removing duplicate item from " + j
5172                            + " due to action " + action + " at " + i);
5173                        j--;
5174                        N--;
5175                    }
5176                }
5177            }
5178
5179            // If the caller didn't request filter information, drop it now
5180            // so we don't have to marshall/unmarshall it.
5181            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5182                rii.filter = null;
5183            }
5184        }
5185
5186        // Filter out the caller activity if so requested.
5187        if (caller != null) {
5188            N = results.size();
5189            for (int i=0; i<N; i++) {
5190                ActivityInfo ainfo = results.get(i).activityInfo;
5191                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5192                        && caller.getClassName().equals(ainfo.name)) {
5193                    results.remove(i);
5194                    break;
5195                }
5196            }
5197        }
5198
5199        // If the caller didn't request filter information,
5200        // drop them now so we don't have to
5201        // marshall/unmarshall it.
5202        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5203            N = results.size();
5204            for (int i=0; i<N; i++) {
5205                results.get(i).filter = null;
5206            }
5207        }
5208
5209        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5210        return results;
5211    }
5212
5213    @Override
5214    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5215            int userId) {
5216        if (!sUserManager.exists(userId)) return Collections.emptyList();
5217        ComponentName comp = intent.getComponent();
5218        if (comp == null) {
5219            if (intent.getSelector() != null) {
5220                intent = intent.getSelector();
5221                comp = intent.getComponent();
5222            }
5223        }
5224        if (comp != null) {
5225            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5226            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5227            if (ai != null) {
5228                ResolveInfo ri = new ResolveInfo();
5229                ri.activityInfo = ai;
5230                list.add(ri);
5231            }
5232            return list;
5233        }
5234
5235        // reader
5236        synchronized (mPackages) {
5237            String pkgName = intent.getPackage();
5238            if (pkgName == null) {
5239                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5240            }
5241            final PackageParser.Package pkg = mPackages.get(pkgName);
5242            if (pkg != null) {
5243                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5244                        userId);
5245            }
5246            return null;
5247        }
5248    }
5249
5250    @Override
5251    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5252        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5253        if (!sUserManager.exists(userId)) return null;
5254        if (query != null) {
5255            if (query.size() >= 1) {
5256                // If there is more than one service with the same priority,
5257                // just arbitrarily pick the first one.
5258                return query.get(0);
5259            }
5260        }
5261        return null;
5262    }
5263
5264    @Override
5265    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5266            int userId) {
5267        if (!sUserManager.exists(userId)) return Collections.emptyList();
5268        ComponentName comp = intent.getComponent();
5269        if (comp == null) {
5270            if (intent.getSelector() != null) {
5271                intent = intent.getSelector();
5272                comp = intent.getComponent();
5273            }
5274        }
5275        if (comp != null) {
5276            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5277            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5278            if (si != null) {
5279                final ResolveInfo ri = new ResolveInfo();
5280                ri.serviceInfo = si;
5281                list.add(ri);
5282            }
5283            return list;
5284        }
5285
5286        // reader
5287        synchronized (mPackages) {
5288            String pkgName = intent.getPackage();
5289            if (pkgName == null) {
5290                return mServices.queryIntent(intent, resolvedType, flags, userId);
5291            }
5292            final PackageParser.Package pkg = mPackages.get(pkgName);
5293            if (pkg != null) {
5294                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5295                        userId);
5296            }
5297            return null;
5298        }
5299    }
5300
5301    @Override
5302    public List<ResolveInfo> queryIntentContentProviders(
5303            Intent intent, String resolvedType, int flags, int userId) {
5304        if (!sUserManager.exists(userId)) return Collections.emptyList();
5305        ComponentName comp = intent.getComponent();
5306        if (comp == null) {
5307            if (intent.getSelector() != null) {
5308                intent = intent.getSelector();
5309                comp = intent.getComponent();
5310            }
5311        }
5312        if (comp != null) {
5313            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5314            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5315            if (pi != null) {
5316                final ResolveInfo ri = new ResolveInfo();
5317                ri.providerInfo = pi;
5318                list.add(ri);
5319            }
5320            return list;
5321        }
5322
5323        // reader
5324        synchronized (mPackages) {
5325            String pkgName = intent.getPackage();
5326            if (pkgName == null) {
5327                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5328            }
5329            final PackageParser.Package pkg = mPackages.get(pkgName);
5330            if (pkg != null) {
5331                return mProviders.queryIntentForPackage(
5332                        intent, resolvedType, flags, pkg.providers, userId);
5333            }
5334            return null;
5335        }
5336    }
5337
5338    @Override
5339    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5340        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5341
5342        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5343
5344        // writer
5345        synchronized (mPackages) {
5346            ArrayList<PackageInfo> list;
5347            if (listUninstalled) {
5348                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5349                for (PackageSetting ps : mSettings.mPackages.values()) {
5350                    PackageInfo pi;
5351                    if (ps.pkg != null) {
5352                        pi = generatePackageInfo(ps.pkg, flags, userId);
5353                    } else {
5354                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5355                    }
5356                    if (pi != null) {
5357                        list.add(pi);
5358                    }
5359                }
5360            } else {
5361                list = new ArrayList<PackageInfo>(mPackages.size());
5362                for (PackageParser.Package p : mPackages.values()) {
5363                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5364                    if (pi != null) {
5365                        list.add(pi);
5366                    }
5367                }
5368            }
5369
5370            return new ParceledListSlice<PackageInfo>(list);
5371        }
5372    }
5373
5374    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5375            String[] permissions, boolean[] tmp, int flags, int userId) {
5376        int numMatch = 0;
5377        final PermissionsState permissionsState = ps.getPermissionsState();
5378        for (int i=0; i<permissions.length; i++) {
5379            final String permission = permissions[i];
5380            if (permissionsState.hasPermission(permission, userId)) {
5381                tmp[i] = true;
5382                numMatch++;
5383            } else {
5384                tmp[i] = false;
5385            }
5386        }
5387        if (numMatch == 0) {
5388            return;
5389        }
5390        PackageInfo pi;
5391        if (ps.pkg != null) {
5392            pi = generatePackageInfo(ps.pkg, flags, userId);
5393        } else {
5394            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5395        }
5396        // The above might return null in cases of uninstalled apps or install-state
5397        // skew across users/profiles.
5398        if (pi != null) {
5399            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5400                if (numMatch == permissions.length) {
5401                    pi.requestedPermissions = permissions;
5402                } else {
5403                    pi.requestedPermissions = new String[numMatch];
5404                    numMatch = 0;
5405                    for (int i=0; i<permissions.length; i++) {
5406                        if (tmp[i]) {
5407                            pi.requestedPermissions[numMatch] = permissions[i];
5408                            numMatch++;
5409                        }
5410                    }
5411                }
5412            }
5413            list.add(pi);
5414        }
5415    }
5416
5417    @Override
5418    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5419            String[] permissions, int flags, int userId) {
5420        if (!sUserManager.exists(userId)) return null;
5421        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5422
5423        // writer
5424        synchronized (mPackages) {
5425            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5426            boolean[] tmpBools = new boolean[permissions.length];
5427            if (listUninstalled) {
5428                for (PackageSetting ps : mSettings.mPackages.values()) {
5429                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5430                }
5431            } else {
5432                for (PackageParser.Package pkg : mPackages.values()) {
5433                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5434                    if (ps != null) {
5435                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5436                                userId);
5437                    }
5438                }
5439            }
5440
5441            return new ParceledListSlice<PackageInfo>(list);
5442        }
5443    }
5444
5445    @Override
5446    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5447        if (!sUserManager.exists(userId)) return null;
5448        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5449
5450        // writer
5451        synchronized (mPackages) {
5452            ArrayList<ApplicationInfo> list;
5453            if (listUninstalled) {
5454                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5455                for (PackageSetting ps : mSettings.mPackages.values()) {
5456                    ApplicationInfo ai;
5457                    if (ps.pkg != null) {
5458                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5459                                ps.readUserState(userId), userId);
5460                    } else {
5461                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5462                    }
5463                    if (ai != null) {
5464                        list.add(ai);
5465                    }
5466                }
5467            } else {
5468                list = new ArrayList<ApplicationInfo>(mPackages.size());
5469                for (PackageParser.Package p : mPackages.values()) {
5470                    if (p.mExtras != null) {
5471                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5472                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5473                        if (ai != null) {
5474                            list.add(ai);
5475                        }
5476                    }
5477                }
5478            }
5479
5480            return new ParceledListSlice<ApplicationInfo>(list);
5481        }
5482    }
5483
5484    public List<ApplicationInfo> getPersistentApplications(int flags) {
5485        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5486
5487        // reader
5488        synchronized (mPackages) {
5489            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5490            final int userId = UserHandle.getCallingUserId();
5491            while (i.hasNext()) {
5492                final PackageParser.Package p = i.next();
5493                if (p.applicationInfo != null
5494                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5495                        && (!mSafeMode || isSystemApp(p))) {
5496                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5497                    if (ps != null) {
5498                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5499                                ps.readUserState(userId), userId);
5500                        if (ai != null) {
5501                            finalList.add(ai);
5502                        }
5503                    }
5504                }
5505            }
5506        }
5507
5508        return finalList;
5509    }
5510
5511    @Override
5512    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5513        if (!sUserManager.exists(userId)) return null;
5514        // reader
5515        synchronized (mPackages) {
5516            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5517            PackageSetting ps = provider != null
5518                    ? mSettings.mPackages.get(provider.owner.packageName)
5519                    : null;
5520            return ps != null
5521                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5522                    && (!mSafeMode || (provider.info.applicationInfo.flags
5523                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5524                    ? PackageParser.generateProviderInfo(provider, flags,
5525                            ps.readUserState(userId), userId)
5526                    : null;
5527        }
5528    }
5529
5530    /**
5531     * @deprecated
5532     */
5533    @Deprecated
5534    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5535        // reader
5536        synchronized (mPackages) {
5537            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5538                    .entrySet().iterator();
5539            final int userId = UserHandle.getCallingUserId();
5540            while (i.hasNext()) {
5541                Map.Entry<String, PackageParser.Provider> entry = i.next();
5542                PackageParser.Provider p = entry.getValue();
5543                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5544
5545                if (ps != null && p.syncable
5546                        && (!mSafeMode || (p.info.applicationInfo.flags
5547                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5548                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5549                            ps.readUserState(userId), userId);
5550                    if (info != null) {
5551                        outNames.add(entry.getKey());
5552                        outInfo.add(info);
5553                    }
5554                }
5555            }
5556        }
5557    }
5558
5559    @Override
5560    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5561            int uid, int flags) {
5562        ArrayList<ProviderInfo> finalList = null;
5563        // reader
5564        synchronized (mPackages) {
5565            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5566            final int userId = processName != null ?
5567                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5568            while (i.hasNext()) {
5569                final PackageParser.Provider p = i.next();
5570                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5571                if (ps != null && p.info.authority != null
5572                        && (processName == null
5573                                || (p.info.processName.equals(processName)
5574                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5575                        && mSettings.isEnabledLPr(p.info, flags, userId)
5576                        && (!mSafeMode
5577                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5578                    if (finalList == null) {
5579                        finalList = new ArrayList<ProviderInfo>(3);
5580                    }
5581                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5582                            ps.readUserState(userId), userId);
5583                    if (info != null) {
5584                        finalList.add(info);
5585                    }
5586                }
5587            }
5588        }
5589
5590        if (finalList != null) {
5591            Collections.sort(finalList, mProviderInitOrderSorter);
5592            return new ParceledListSlice<ProviderInfo>(finalList);
5593        }
5594
5595        return null;
5596    }
5597
5598    @Override
5599    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5600            int flags) {
5601        // reader
5602        synchronized (mPackages) {
5603            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5604            return PackageParser.generateInstrumentationInfo(i, flags);
5605        }
5606    }
5607
5608    @Override
5609    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5610            int flags) {
5611        ArrayList<InstrumentationInfo> finalList =
5612            new ArrayList<InstrumentationInfo>();
5613
5614        // reader
5615        synchronized (mPackages) {
5616            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5617            while (i.hasNext()) {
5618                final PackageParser.Instrumentation p = i.next();
5619                if (targetPackage == null
5620                        || targetPackage.equals(p.info.targetPackage)) {
5621                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5622                            flags);
5623                    if (ii != null) {
5624                        finalList.add(ii);
5625                    }
5626                }
5627            }
5628        }
5629
5630        return finalList;
5631    }
5632
5633    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5634        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5635        if (overlays == null) {
5636            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5637            return;
5638        }
5639        for (PackageParser.Package opkg : overlays.values()) {
5640            // Not much to do if idmap fails: we already logged the error
5641            // and we certainly don't want to abort installation of pkg simply
5642            // because an overlay didn't fit properly. For these reasons,
5643            // ignore the return value of createIdmapForPackagePairLI.
5644            createIdmapForPackagePairLI(pkg, opkg);
5645        }
5646    }
5647
5648    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5649            PackageParser.Package opkg) {
5650        if (!opkg.mTrustedOverlay) {
5651            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5652                    opkg.baseCodePath + ": overlay not trusted");
5653            return false;
5654        }
5655        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5656        if (overlaySet == null) {
5657            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5658                    opkg.baseCodePath + " but target package has no known overlays");
5659            return false;
5660        }
5661        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5662        // TODO: generate idmap for split APKs
5663        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5664            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5665                    + opkg.baseCodePath);
5666            return false;
5667        }
5668        PackageParser.Package[] overlayArray =
5669            overlaySet.values().toArray(new PackageParser.Package[0]);
5670        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5671            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5672                return p1.mOverlayPriority - p2.mOverlayPriority;
5673            }
5674        };
5675        Arrays.sort(overlayArray, cmp);
5676
5677        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5678        int i = 0;
5679        for (PackageParser.Package p : overlayArray) {
5680            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5681        }
5682        return true;
5683    }
5684
5685    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5686        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
5687        try {
5688            scanDirLI(dir, parseFlags, scanFlags, currentTime);
5689        } finally {
5690            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5691        }
5692    }
5693
5694    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5695        final File[] files = dir.listFiles();
5696        if (ArrayUtils.isEmpty(files)) {
5697            Log.d(TAG, "No files in app dir " + dir);
5698            return;
5699        }
5700
5701        if (DEBUG_PACKAGE_SCANNING) {
5702            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5703                    + " flags=0x" + Integer.toHexString(parseFlags));
5704        }
5705
5706        for (File file : files) {
5707            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5708                    && !PackageInstallerService.isStageName(file.getName());
5709            if (!isPackage) {
5710                // Ignore entries which are not packages
5711                continue;
5712            }
5713            try {
5714                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5715                        scanFlags, currentTime, null);
5716            } catch (PackageManagerException e) {
5717                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5718
5719                // Delete invalid userdata apps
5720                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5721                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5722                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5723                    if (file.isDirectory()) {
5724                        mInstaller.rmPackageDir(file.getAbsolutePath());
5725                    } else {
5726                        file.delete();
5727                    }
5728                }
5729            }
5730        }
5731    }
5732
5733    private static File getSettingsProblemFile() {
5734        File dataDir = Environment.getDataDirectory();
5735        File systemDir = new File(dataDir, "system");
5736        File fname = new File(systemDir, "uiderrors.txt");
5737        return fname;
5738    }
5739
5740    static void reportSettingsProblem(int priority, String msg) {
5741        logCriticalInfo(priority, msg);
5742    }
5743
5744    static void logCriticalInfo(int priority, String msg) {
5745        Slog.println(priority, TAG, msg);
5746        EventLogTags.writePmCriticalInfo(msg);
5747        try {
5748            File fname = getSettingsProblemFile();
5749            FileOutputStream out = new FileOutputStream(fname, true);
5750            PrintWriter pw = new FastPrintWriter(out);
5751            SimpleDateFormat formatter = new SimpleDateFormat();
5752            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5753            pw.println(dateString + ": " + msg);
5754            pw.close();
5755            FileUtils.setPermissions(
5756                    fname.toString(),
5757                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5758                    -1, -1);
5759        } catch (java.io.IOException e) {
5760        }
5761    }
5762
5763    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5764            PackageParser.Package pkg, File srcFile, int parseFlags)
5765            throws PackageManagerException {
5766        if (ps != null
5767                && ps.codePath.equals(srcFile)
5768                && ps.timeStamp == srcFile.lastModified()
5769                && !isCompatSignatureUpdateNeeded(pkg)
5770                && !isRecoverSignatureUpdateNeeded(pkg)) {
5771            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5772            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5773            ArraySet<PublicKey> signingKs;
5774            synchronized (mPackages) {
5775                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5776            }
5777            if (ps.signatures.mSignatures != null
5778                    && ps.signatures.mSignatures.length != 0
5779                    && signingKs != null) {
5780                // Optimization: reuse the existing cached certificates
5781                // if the package appears to be unchanged.
5782                pkg.mSignatures = ps.signatures.mSignatures;
5783                pkg.mSigningKeys = signingKs;
5784                return;
5785            }
5786
5787            Slog.w(TAG, "PackageSetting for " + ps.name
5788                    + " is missing signatures.  Collecting certs again to recover them.");
5789        } else {
5790            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5791        }
5792
5793        try {
5794            pp.collectCertificates(pkg, parseFlags);
5795            pp.collectManifestDigest(pkg);
5796        } catch (PackageParserException e) {
5797            throw PackageManagerException.from(e);
5798        }
5799    }
5800
5801    /**
5802     *  Traces a package scan.
5803     *  @see #scanPackageLI(File, int, int, long, UserHandle)
5804     */
5805    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
5806            long currentTime, UserHandle user) throws PackageManagerException {
5807        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
5808        try {
5809            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
5810        } finally {
5811            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5812        }
5813    }
5814
5815    /**
5816     *  Scans a package and returns the newly parsed package.
5817     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
5818     */
5819    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5820            long currentTime, UserHandle user) throws PackageManagerException {
5821        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5822        parseFlags |= mDefParseFlags;
5823        PackageParser pp = new PackageParser();
5824        pp.setSeparateProcesses(mSeparateProcesses);
5825        pp.setOnlyCoreApps(mOnlyCore);
5826        pp.setDisplayMetrics(mMetrics);
5827
5828        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5829            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5830        }
5831
5832        final PackageParser.Package pkg;
5833        try {
5834            pkg = pp.parsePackage(scanFile, parseFlags);
5835        } catch (PackageParserException e) {
5836            throw PackageManagerException.from(e);
5837        }
5838
5839        PackageSetting ps = null;
5840        PackageSetting updatedPkg;
5841        // reader
5842        synchronized (mPackages) {
5843            // Look to see if we already know about this package.
5844            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5845            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5846                // This package has been renamed to its original name.  Let's
5847                // use that.
5848                ps = mSettings.peekPackageLPr(oldName);
5849            }
5850            // If there was no original package, see one for the real package name.
5851            if (ps == null) {
5852                ps = mSettings.peekPackageLPr(pkg.packageName);
5853            }
5854            // Check to see if this package could be hiding/updating a system
5855            // package.  Must look for it either under the original or real
5856            // package name depending on our state.
5857            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5858            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5859        }
5860        boolean updatedPkgBetter = false;
5861        // First check if this is a system package that may involve an update
5862        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
5863            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5864            // it needs to drop FLAG_PRIVILEGED.
5865            if (locationIsPrivileged(scanFile)) {
5866                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5867            } else {
5868                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5869            }
5870
5871            if (ps != null && !ps.codePath.equals(scanFile)) {
5872                // The path has changed from what was last scanned...  check the
5873                // version of the new path against what we have stored to determine
5874                // what to do.
5875                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5876                if (pkg.mVersionCode <= ps.versionCode) {
5877                    // The system package has been updated and the code path does not match
5878                    // Ignore entry. Skip it.
5879                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5880                            + " ignored: updated version " + ps.versionCode
5881                            + " better than this " + pkg.mVersionCode);
5882                    if (!updatedPkg.codePath.equals(scanFile)) {
5883                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5884                                + ps.name + " changing from " + updatedPkg.codePathString
5885                                + " to " + scanFile);
5886                        updatedPkg.codePath = scanFile;
5887                        updatedPkg.codePathString = scanFile.toString();
5888                        updatedPkg.resourcePath = scanFile;
5889                        updatedPkg.resourcePathString = scanFile.toString();
5890                    }
5891                    updatedPkg.pkg = pkg;
5892                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5893                            "Package " + ps.name + " at " + scanFile
5894                                    + " ignored: updated version " + ps.versionCode
5895                                    + " better than this " + pkg.mVersionCode);
5896                } else {
5897                    // The current app on the system partition is better than
5898                    // what we have updated to on the data partition; switch
5899                    // back to the system partition version.
5900                    // At this point, its safely assumed that package installation for
5901                    // apps in system partition will go through. If not there won't be a working
5902                    // version of the app
5903                    // writer
5904                    synchronized (mPackages) {
5905                        // Just remove the loaded entries from package lists.
5906                        mPackages.remove(ps.name);
5907                    }
5908
5909                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5910                            + " reverting from " + ps.codePathString
5911                            + ": new version " + pkg.mVersionCode
5912                            + " better than installed " + ps.versionCode);
5913
5914                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5915                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5916                    synchronized (mInstallLock) {
5917                        args.cleanUpResourcesLI();
5918                    }
5919                    synchronized (mPackages) {
5920                        mSettings.enableSystemPackageLPw(ps.name);
5921                    }
5922                    updatedPkgBetter = true;
5923                }
5924            }
5925        }
5926
5927        if (updatedPkg != null) {
5928            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5929            // initially
5930            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5931
5932            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5933            // flag set initially
5934            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5935                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5936            }
5937        }
5938
5939        // Verify certificates against what was last scanned
5940        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5941
5942        /*
5943         * A new system app appeared, but we already had a non-system one of the
5944         * same name installed earlier.
5945         */
5946        boolean shouldHideSystemApp = false;
5947        if (updatedPkg == null && ps != null
5948                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5949            /*
5950             * Check to make sure the signatures match first. If they don't,
5951             * wipe the installed application and its data.
5952             */
5953            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5954                    != PackageManager.SIGNATURE_MATCH) {
5955                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5956                        + " signatures don't match existing userdata copy; removing");
5957                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5958                ps = null;
5959            } else {
5960                /*
5961                 * If the newly-added system app is an older version than the
5962                 * already installed version, hide it. It will be scanned later
5963                 * and re-added like an update.
5964                 */
5965                if (pkg.mVersionCode <= ps.versionCode) {
5966                    shouldHideSystemApp = true;
5967                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5968                            + " but new version " + pkg.mVersionCode + " better than installed "
5969                            + ps.versionCode + "; hiding system");
5970                } else {
5971                    /*
5972                     * The newly found system app is a newer version that the
5973                     * one previously installed. Simply remove the
5974                     * already-installed application and replace it with our own
5975                     * while keeping the application data.
5976                     */
5977                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5978                            + " reverting from " + ps.codePathString + ": new version "
5979                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5980                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5981                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5982                    synchronized (mInstallLock) {
5983                        args.cleanUpResourcesLI();
5984                    }
5985                }
5986            }
5987        }
5988
5989        // The apk is forward locked (not public) if its code and resources
5990        // are kept in different files. (except for app in either system or
5991        // vendor path).
5992        // TODO grab this value from PackageSettings
5993        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5994            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5995                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5996            }
5997        }
5998
5999        // TODO: extend to support forward-locked splits
6000        String resourcePath = null;
6001        String baseResourcePath = null;
6002        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6003            if (ps != null && ps.resourcePathString != null) {
6004                resourcePath = ps.resourcePathString;
6005                baseResourcePath = ps.resourcePathString;
6006            } else {
6007                // Should not happen at all. Just log an error.
6008                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
6009            }
6010        } else {
6011            resourcePath = pkg.codePath;
6012            baseResourcePath = pkg.baseCodePath;
6013        }
6014
6015        // Set application objects path explicitly.
6016        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6017        pkg.applicationInfo.setCodePath(pkg.codePath);
6018        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6019        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6020        pkg.applicationInfo.setResourcePath(resourcePath);
6021        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6022        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6023
6024        // Note that we invoke the following method only if we are about to unpack an application
6025        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6026                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6027
6028        /*
6029         * If the system app should be overridden by a previously installed
6030         * data, hide the system app now and let the /data/app scan pick it up
6031         * again.
6032         */
6033        if (shouldHideSystemApp) {
6034            synchronized (mPackages) {
6035                mSettings.disableSystemPackageLPw(pkg.packageName);
6036            }
6037        }
6038
6039        return scannedPkg;
6040    }
6041
6042    private static String fixProcessName(String defProcessName,
6043            String processName, int uid) {
6044        if (processName == null) {
6045            return defProcessName;
6046        }
6047        return processName;
6048    }
6049
6050    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6051            throws PackageManagerException {
6052        if (pkgSetting.signatures.mSignatures != null) {
6053            // Already existing package. Make sure signatures match
6054            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6055                    == PackageManager.SIGNATURE_MATCH;
6056            if (!match) {
6057                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6058                        == PackageManager.SIGNATURE_MATCH;
6059            }
6060            if (!match) {
6061                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6062                        == PackageManager.SIGNATURE_MATCH;
6063            }
6064            if (!match) {
6065                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6066                        + pkg.packageName + " signatures do not match the "
6067                        + "previously installed version; ignoring!");
6068            }
6069        }
6070
6071        // Check for shared user signatures
6072        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6073            // Already existing package. Make sure signatures match
6074            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6075                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6076            if (!match) {
6077                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6078                        == PackageManager.SIGNATURE_MATCH;
6079            }
6080            if (!match) {
6081                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6082                        == PackageManager.SIGNATURE_MATCH;
6083            }
6084            if (!match) {
6085                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6086                        "Package " + pkg.packageName
6087                        + " has no signatures that match those in shared user "
6088                        + pkgSetting.sharedUser.name + "; ignoring!");
6089            }
6090        }
6091    }
6092
6093    /**
6094     * Enforces that only the system UID or root's UID can call a method exposed
6095     * via Binder.
6096     *
6097     * @param message used as message if SecurityException is thrown
6098     * @throws SecurityException if the caller is not system or root
6099     */
6100    private static final void enforceSystemOrRoot(String message) {
6101        final int uid = Binder.getCallingUid();
6102        if (uid != Process.SYSTEM_UID && uid != 0) {
6103            throw new SecurityException(message);
6104        }
6105    }
6106
6107    @Override
6108    public void performBootDexOpt() {
6109        enforceSystemOrRoot("Only the system can request dexopt be performed");
6110
6111        // Before everything else, see whether we need to fstrim.
6112        try {
6113            IMountService ms = PackageHelper.getMountService();
6114            if (ms != null) {
6115                final boolean isUpgrade = isUpgrade();
6116                boolean doTrim = isUpgrade;
6117                if (doTrim) {
6118                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6119                } else {
6120                    final long interval = android.provider.Settings.Global.getLong(
6121                            mContext.getContentResolver(),
6122                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6123                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6124                    if (interval > 0) {
6125                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6126                        if (timeSinceLast > interval) {
6127                            doTrim = true;
6128                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6129                                    + "; running immediately");
6130                        }
6131                    }
6132                }
6133                if (doTrim) {
6134                    if (!isFirstBoot()) {
6135                        try {
6136                            ActivityManagerNative.getDefault().showBootMessage(
6137                                    mContext.getResources().getString(
6138                                            R.string.android_upgrading_fstrim), true);
6139                        } catch (RemoteException e) {
6140                        }
6141                    }
6142                    ms.runMaintenance();
6143                }
6144            } else {
6145                Slog.e(TAG, "Mount service unavailable!");
6146            }
6147        } catch (RemoteException e) {
6148            // Can't happen; MountService is local
6149        }
6150
6151        final ArraySet<PackageParser.Package> pkgs;
6152        synchronized (mPackages) {
6153            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6154        }
6155
6156        if (pkgs != null) {
6157            // Sort apps by importance for dexopt ordering. Important apps are given more priority
6158            // in case the device runs out of space.
6159            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6160            // Give priority to core apps.
6161            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6162                PackageParser.Package pkg = it.next();
6163                if (pkg.coreApp) {
6164                    if (DEBUG_DEXOPT) {
6165                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6166                    }
6167                    sortedPkgs.add(pkg);
6168                    it.remove();
6169                }
6170            }
6171            // Give priority to system apps that listen for pre boot complete.
6172            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6173            ArraySet<String> pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM);
6174            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6175                PackageParser.Package pkg = it.next();
6176                if (pkgNames.contains(pkg.packageName)) {
6177                    if (DEBUG_DEXOPT) {
6178                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6179                    }
6180                    sortedPkgs.add(pkg);
6181                    it.remove();
6182                }
6183            }
6184            // Filter out packages that aren't recently used.
6185            filterRecentlyUsedApps(pkgs);
6186            // Add all remaining apps.
6187            for (PackageParser.Package pkg : pkgs) {
6188                if (DEBUG_DEXOPT) {
6189                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6190                }
6191                sortedPkgs.add(pkg);
6192            }
6193
6194            // If we want to be lazy, filter everything that wasn't recently used.
6195            if (mLazyDexOpt) {
6196                filterRecentlyUsedApps(sortedPkgs);
6197            }
6198
6199            int i = 0;
6200            int total = sortedPkgs.size();
6201            File dataDir = Environment.getDataDirectory();
6202            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6203            if (lowThreshold == 0) {
6204                throw new IllegalStateException("Invalid low memory threshold");
6205            }
6206            for (PackageParser.Package pkg : sortedPkgs) {
6207                long usableSpace = dataDir.getUsableSpace();
6208                if (usableSpace < lowThreshold) {
6209                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6210                    break;
6211                }
6212                performBootDexOpt(pkg, ++i, total);
6213            }
6214        }
6215    }
6216
6217    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6218        // Filter out packages that aren't recently used.
6219        //
6220        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6221        // should do a full dexopt.
6222        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6223            int total = pkgs.size();
6224            int skipped = 0;
6225            long now = System.currentTimeMillis();
6226            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6227                PackageParser.Package pkg = i.next();
6228                long then = pkg.mLastPackageUsageTimeInMills;
6229                if (then + mDexOptLRUThresholdInMills < now) {
6230                    if (DEBUG_DEXOPT) {
6231                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6232                              ((then == 0) ? "never" : new Date(then)));
6233                    }
6234                    i.remove();
6235                    skipped++;
6236                }
6237            }
6238            if (DEBUG_DEXOPT) {
6239                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6240            }
6241        }
6242    }
6243
6244    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6245        List<ResolveInfo> ris = null;
6246        try {
6247            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6248                    intent, null, 0, userId);
6249        } catch (RemoteException e) {
6250        }
6251        ArraySet<String> pkgNames = new ArraySet<String>();
6252        if (ris != null) {
6253            for (ResolveInfo ri : ris) {
6254                pkgNames.add(ri.activityInfo.packageName);
6255            }
6256        }
6257        return pkgNames;
6258    }
6259
6260    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6261        if (DEBUG_DEXOPT) {
6262            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6263        }
6264        if (!isFirstBoot()) {
6265            try {
6266                ActivityManagerNative.getDefault().showBootMessage(
6267                        mContext.getResources().getString(R.string.android_upgrading_apk,
6268                                curr, total), true);
6269            } catch (RemoteException e) {
6270            }
6271        }
6272        PackageParser.Package p = pkg;
6273        synchronized (mInstallLock) {
6274            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6275                    false /* force dex */, false /* defer */, true /* include dependencies */,
6276                    false /* boot complete */, false /*useJit*/);
6277        }
6278    }
6279
6280    @Override
6281    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6282        return performDexOptTraced(packageName, instructionSet, false);
6283    }
6284
6285    public boolean performDexOpt(
6286            String packageName, String instructionSet, boolean backgroundDexopt) {
6287        return performDexOptTraced(packageName, instructionSet, backgroundDexopt);
6288    }
6289
6290    private boolean performDexOptTraced(
6291            String packageName, String instructionSet, boolean backgroundDexopt) {
6292        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6293        try {
6294            return performDexOptInternal(packageName, instructionSet, backgroundDexopt);
6295        } finally {
6296            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6297        }
6298    }
6299
6300    private boolean performDexOptInternal(
6301            String packageName, String instructionSet, boolean backgroundDexopt) {
6302        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6303        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6304        if (!dexopt && !updateUsage) {
6305            // We aren't going to dexopt or update usage, so bail early.
6306            return false;
6307        }
6308        PackageParser.Package p;
6309        final String targetInstructionSet;
6310        synchronized (mPackages) {
6311            p = mPackages.get(packageName);
6312            if (p == null) {
6313                return false;
6314            }
6315            if (updateUsage) {
6316                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6317            }
6318            mPackageUsage.write(false);
6319            if (!dexopt) {
6320                // We aren't going to dexopt, so bail early.
6321                return false;
6322            }
6323
6324            targetInstructionSet = instructionSet != null ? instructionSet :
6325                    getPrimaryInstructionSet(p.applicationInfo);
6326            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6327                return false;
6328            }
6329        }
6330        long callingId = Binder.clearCallingIdentity();
6331        try {
6332            synchronized (mInstallLock) {
6333                final String[] instructionSets = new String[] { targetInstructionSet };
6334                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6335                        false /* forceDex */, false /* defer */, true /* inclDependencies */,
6336                        true /* boot complete */, false /*useJit*/);
6337                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6338            }
6339        } finally {
6340            Binder.restoreCallingIdentity(callingId);
6341        }
6342    }
6343
6344    public ArraySet<String> getPackagesThatNeedDexOpt() {
6345        ArraySet<String> pkgs = null;
6346        synchronized (mPackages) {
6347            for (PackageParser.Package p : mPackages.values()) {
6348                if (DEBUG_DEXOPT) {
6349                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6350                }
6351                if (!p.mDexOptPerformed.isEmpty()) {
6352                    continue;
6353                }
6354                if (pkgs == null) {
6355                    pkgs = new ArraySet<String>();
6356                }
6357                pkgs.add(p.packageName);
6358            }
6359        }
6360        return pkgs;
6361    }
6362
6363    public void shutdown() {
6364        mPackageUsage.write(true);
6365    }
6366
6367    @Override
6368    public void forceDexOpt(String packageName) {
6369        enforceSystemOrRoot("forceDexOpt");
6370
6371        PackageParser.Package pkg;
6372        synchronized (mPackages) {
6373            pkg = mPackages.get(packageName);
6374            if (pkg == null) {
6375                throw new IllegalArgumentException("Missing package: " + packageName);
6376            }
6377        }
6378
6379        synchronized (mInstallLock) {
6380            final String[] instructionSets = new String[] {
6381                    getPrimaryInstructionSet(pkg.applicationInfo) };
6382
6383            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6384
6385            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6386                    true /*forceDex*/, false /* defer */, true /* inclDependencies */,
6387                    true /* boot complete */, false /*useJit*/);
6388
6389            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6390            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6391                throw new IllegalStateException("Failed to dexopt: " + res);
6392            }
6393        }
6394    }
6395
6396    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6397        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6398            Slog.w(TAG, "Unable to update from " + oldPkg.name
6399                    + " to " + newPkg.packageName
6400                    + ": old package not in system partition");
6401            return false;
6402        } else if (mPackages.get(oldPkg.name) != null) {
6403            Slog.w(TAG, "Unable to update from " + oldPkg.name
6404                    + " to " + newPkg.packageName
6405                    + ": old package still exists");
6406            return false;
6407        }
6408        return true;
6409    }
6410
6411    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6412        int[] users = sUserManager.getUserIds();
6413        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6414        if (res < 0) {
6415            return res;
6416        }
6417        for (int user : users) {
6418            if (user != 0) {
6419                res = mInstaller.createUserData(volumeUuid, packageName,
6420                        UserHandle.getUid(user, uid), user, seinfo);
6421                if (res < 0) {
6422                    return res;
6423                }
6424            }
6425        }
6426        return res;
6427    }
6428
6429    private int removeDataDirsLI(String volumeUuid, String packageName) {
6430        int[] users = sUserManager.getUserIds();
6431        int res = 0;
6432        for (int user : users) {
6433            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6434            if (resInner < 0) {
6435                res = resInner;
6436            }
6437        }
6438
6439        return res;
6440    }
6441
6442    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6443        int[] users = sUserManager.getUserIds();
6444        int res = 0;
6445        for (int user : users) {
6446            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6447            if (resInner < 0) {
6448                res = resInner;
6449            }
6450        }
6451        return res;
6452    }
6453
6454    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6455            PackageParser.Package changingLib) {
6456        if (file.path != null) {
6457            usesLibraryFiles.add(file.path);
6458            return;
6459        }
6460        PackageParser.Package p = mPackages.get(file.apk);
6461        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6462            // If we are doing this while in the middle of updating a library apk,
6463            // then we need to make sure to use that new apk for determining the
6464            // dependencies here.  (We haven't yet finished committing the new apk
6465            // to the package manager state.)
6466            if (p == null || p.packageName.equals(changingLib.packageName)) {
6467                p = changingLib;
6468            }
6469        }
6470        if (p != null) {
6471            usesLibraryFiles.addAll(p.getAllCodePaths());
6472        }
6473    }
6474
6475    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6476            PackageParser.Package changingLib) throws PackageManagerException {
6477        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6478            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6479            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6480            for (int i=0; i<N; i++) {
6481                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6482                if (file == null) {
6483                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6484                            "Package " + pkg.packageName + " requires unavailable shared library "
6485                            + pkg.usesLibraries.get(i) + "; failing!");
6486                }
6487                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6488            }
6489            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6490            for (int i=0; i<N; i++) {
6491                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6492                if (file == null) {
6493                    Slog.w(TAG, "Package " + pkg.packageName
6494                            + " desires unavailable shared library "
6495                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6496                } else {
6497                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6498                }
6499            }
6500            N = usesLibraryFiles.size();
6501            if (N > 0) {
6502                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6503            } else {
6504                pkg.usesLibraryFiles = null;
6505            }
6506        }
6507    }
6508
6509    private static boolean hasString(List<String> list, List<String> which) {
6510        if (list == null) {
6511            return false;
6512        }
6513        for (int i=list.size()-1; i>=0; i--) {
6514            for (int j=which.size()-1; j>=0; j--) {
6515                if (which.get(j).equals(list.get(i))) {
6516                    return true;
6517                }
6518            }
6519        }
6520        return false;
6521    }
6522
6523    private void updateAllSharedLibrariesLPw() {
6524        for (PackageParser.Package pkg : mPackages.values()) {
6525            try {
6526                updateSharedLibrariesLPw(pkg, null);
6527            } catch (PackageManagerException e) {
6528                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6529            }
6530        }
6531    }
6532
6533    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6534            PackageParser.Package changingPkg) {
6535        ArrayList<PackageParser.Package> res = null;
6536        for (PackageParser.Package pkg : mPackages.values()) {
6537            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6538                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6539                if (res == null) {
6540                    res = new ArrayList<PackageParser.Package>();
6541                }
6542                res.add(pkg);
6543                try {
6544                    updateSharedLibrariesLPw(pkg, changingPkg);
6545                } catch (PackageManagerException e) {
6546                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6547                }
6548            }
6549        }
6550        return res;
6551    }
6552
6553    /**
6554     * Derive the value of the {@code cpuAbiOverride} based on the provided
6555     * value and an optional stored value from the package settings.
6556     */
6557    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6558        String cpuAbiOverride = null;
6559
6560        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6561            cpuAbiOverride = null;
6562        } else if (abiOverride != null) {
6563            cpuAbiOverride = abiOverride;
6564        } else if (settings != null) {
6565            cpuAbiOverride = settings.cpuAbiOverrideString;
6566        }
6567
6568        return cpuAbiOverride;
6569    }
6570
6571    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6572            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6573        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6574        try {
6575            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6576        } finally {
6577            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6578        }
6579    }
6580
6581    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6582            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6583        boolean success = false;
6584        try {
6585            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6586                    currentTime, user);
6587            success = true;
6588            return res;
6589        } finally {
6590            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6591                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6592            }
6593        }
6594    }
6595
6596    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6597            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6598        final File scanFile = new File(pkg.codePath);
6599        if (pkg.applicationInfo.getCodePath() == null ||
6600                pkg.applicationInfo.getResourcePath() == null) {
6601            // Bail out. The resource and code paths haven't been set.
6602            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6603                    "Code and resource paths haven't been set correctly");
6604        }
6605
6606        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6607            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6608        } else {
6609            // Only allow system apps to be flagged as core apps.
6610            pkg.coreApp = false;
6611        }
6612
6613        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6614            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6615        }
6616
6617        if (mCustomResolverComponentName != null &&
6618                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6619            setUpCustomResolverActivity(pkg);
6620        }
6621
6622        if (pkg.packageName.equals("android")) {
6623            synchronized (mPackages) {
6624                if (mAndroidApplication != null) {
6625                    Slog.w(TAG, "*************************************************");
6626                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6627                    Slog.w(TAG, " file=" + scanFile);
6628                    Slog.w(TAG, "*************************************************");
6629                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6630                            "Core android package being redefined.  Skipping.");
6631                }
6632
6633                // Set up information for our fall-back user intent resolution activity.
6634                mPlatformPackage = pkg;
6635                pkg.mVersionCode = mSdkVersion;
6636                mAndroidApplication = pkg.applicationInfo;
6637
6638                if (!mResolverReplaced) {
6639                    mResolveActivity.applicationInfo = mAndroidApplication;
6640                    mResolveActivity.name = ResolverActivity.class.getName();
6641                    mResolveActivity.packageName = mAndroidApplication.packageName;
6642                    mResolveActivity.processName = "system:ui";
6643                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6644                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6645                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6646                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6647                    mResolveActivity.exported = true;
6648                    mResolveActivity.enabled = true;
6649                    mResolveInfo.activityInfo = mResolveActivity;
6650                    mResolveInfo.priority = 0;
6651                    mResolveInfo.preferredOrder = 0;
6652                    mResolveInfo.match = 0;
6653                    mResolveComponentName = new ComponentName(
6654                            mAndroidApplication.packageName, mResolveActivity.name);
6655                }
6656            }
6657        }
6658
6659        if (DEBUG_PACKAGE_SCANNING) {
6660            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6661                Log.d(TAG, "Scanning package " + pkg.packageName);
6662        }
6663
6664        if (mPackages.containsKey(pkg.packageName)
6665                || mSharedLibraries.containsKey(pkg.packageName)) {
6666            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6667                    "Application package " + pkg.packageName
6668                    + " already installed.  Skipping duplicate.");
6669        }
6670
6671        // If we're only installing presumed-existing packages, require that the
6672        // scanned APK is both already known and at the path previously established
6673        // for it.  Previously unknown packages we pick up normally, but if we have an
6674        // a priori expectation about this package's install presence, enforce it.
6675        // With a singular exception for new system packages. When an OTA contains
6676        // a new system package, we allow the codepath to change from a system location
6677        // to the user-installed location. If we don't allow this change, any newer,
6678        // user-installed version of the application will be ignored.
6679        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6680            if (mExpectingBetter.containsKey(pkg.packageName)) {
6681                logCriticalInfo(Log.WARN,
6682                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6683            } else {
6684                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6685                if (known != null) {
6686                    if (DEBUG_PACKAGE_SCANNING) {
6687                        Log.d(TAG, "Examining " + pkg.codePath
6688                                + " and requiring known paths " + known.codePathString
6689                                + " & " + known.resourcePathString);
6690                    }
6691                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6692                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6693                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6694                                "Application package " + pkg.packageName
6695                                + " found at " + pkg.applicationInfo.getCodePath()
6696                                + " but expected at " + known.codePathString + "; ignoring.");
6697                    }
6698                }
6699            }
6700        }
6701
6702        // Initialize package source and resource directories
6703        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6704        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6705
6706        SharedUserSetting suid = null;
6707        PackageSetting pkgSetting = null;
6708
6709        if (!isSystemApp(pkg)) {
6710            // Only system apps can use these features.
6711            pkg.mOriginalPackages = null;
6712            pkg.mRealPackage = null;
6713            pkg.mAdoptPermissions = null;
6714        }
6715
6716        // writer
6717        synchronized (mPackages) {
6718            if (pkg.mSharedUserId != null) {
6719                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6720                if (suid == null) {
6721                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6722                            "Creating application package " + pkg.packageName
6723                            + " for shared user failed");
6724                }
6725                if (DEBUG_PACKAGE_SCANNING) {
6726                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6727                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6728                                + "): packages=" + suid.packages);
6729                }
6730            }
6731
6732            // Check if we are renaming from an original package name.
6733            PackageSetting origPackage = null;
6734            String realName = null;
6735            if (pkg.mOriginalPackages != null) {
6736                // This package may need to be renamed to a previously
6737                // installed name.  Let's check on that...
6738                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6739                if (pkg.mOriginalPackages.contains(renamed)) {
6740                    // This package had originally been installed as the
6741                    // original name, and we have already taken care of
6742                    // transitioning to the new one.  Just update the new
6743                    // one to continue using the old name.
6744                    realName = pkg.mRealPackage;
6745                    if (!pkg.packageName.equals(renamed)) {
6746                        // Callers into this function may have already taken
6747                        // care of renaming the package; only do it here if
6748                        // it is not already done.
6749                        pkg.setPackageName(renamed);
6750                    }
6751
6752                } else {
6753                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6754                        if ((origPackage = mSettings.peekPackageLPr(
6755                                pkg.mOriginalPackages.get(i))) != null) {
6756                            // We do have the package already installed under its
6757                            // original name...  should we use it?
6758                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6759                                // New package is not compatible with original.
6760                                origPackage = null;
6761                                continue;
6762                            } else if (origPackage.sharedUser != null) {
6763                                // Make sure uid is compatible between packages.
6764                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6765                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6766                                            + " to " + pkg.packageName + ": old uid "
6767                                            + origPackage.sharedUser.name
6768                                            + " differs from " + pkg.mSharedUserId);
6769                                    origPackage = null;
6770                                    continue;
6771                                }
6772                            } else {
6773                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6774                                        + pkg.packageName + " to old name " + origPackage.name);
6775                            }
6776                            break;
6777                        }
6778                    }
6779                }
6780            }
6781
6782            if (mTransferedPackages.contains(pkg.packageName)) {
6783                Slog.w(TAG, "Package " + pkg.packageName
6784                        + " was transferred to another, but its .apk remains");
6785            }
6786
6787            // Just create the setting, don't add it yet. For already existing packages
6788            // the PkgSetting exists already and doesn't have to be created.
6789            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6790                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6791                    pkg.applicationInfo.primaryCpuAbi,
6792                    pkg.applicationInfo.secondaryCpuAbi,
6793                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6794                    user, false);
6795            if (pkgSetting == null) {
6796                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6797                        "Creating application package " + pkg.packageName + " failed");
6798            }
6799
6800            if (pkgSetting.origPackage != null) {
6801                // If we are first transitioning from an original package,
6802                // fix up the new package's name now.  We need to do this after
6803                // looking up the package under its new name, so getPackageLP
6804                // can take care of fiddling things correctly.
6805                pkg.setPackageName(origPackage.name);
6806
6807                // File a report about this.
6808                String msg = "New package " + pkgSetting.realName
6809                        + " renamed to replace old package " + pkgSetting.name;
6810                reportSettingsProblem(Log.WARN, msg);
6811
6812                // Make a note of it.
6813                mTransferedPackages.add(origPackage.name);
6814
6815                // No longer need to retain this.
6816                pkgSetting.origPackage = null;
6817            }
6818
6819            if (realName != null) {
6820                // Make a note of it.
6821                mTransferedPackages.add(pkg.packageName);
6822            }
6823
6824            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6825                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6826            }
6827
6828            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6829                // Check all shared libraries and map to their actual file path.
6830                // We only do this here for apps not on a system dir, because those
6831                // are the only ones that can fail an install due to this.  We
6832                // will take care of the system apps by updating all of their
6833                // library paths after the scan is done.
6834                updateSharedLibrariesLPw(pkg, null);
6835            }
6836
6837            if (mFoundPolicyFile) {
6838                SELinuxMMAC.assignSeinfoValue(pkg);
6839            }
6840
6841            pkg.applicationInfo.uid = pkgSetting.appId;
6842            pkg.mExtras = pkgSetting;
6843            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6844                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6845                    // We just determined the app is signed correctly, so bring
6846                    // over the latest parsed certs.
6847                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6848                } else {
6849                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6850                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6851                                "Package " + pkg.packageName + " upgrade keys do not match the "
6852                                + "previously installed version");
6853                    } else {
6854                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6855                        String msg = "System package " + pkg.packageName
6856                            + " signature changed; retaining data.";
6857                        reportSettingsProblem(Log.WARN, msg);
6858                    }
6859                }
6860            } else {
6861                try {
6862                    verifySignaturesLP(pkgSetting, pkg);
6863                    // We just determined the app is signed correctly, so bring
6864                    // over the latest parsed certs.
6865                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6866                } catch (PackageManagerException e) {
6867                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6868                        throw e;
6869                    }
6870                    // The signature has changed, but this package is in the system
6871                    // image...  let's recover!
6872                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6873                    // However...  if this package is part of a shared user, but it
6874                    // doesn't match the signature of the shared user, let's fail.
6875                    // What this means is that you can't change the signatures
6876                    // associated with an overall shared user, which doesn't seem all
6877                    // that unreasonable.
6878                    if (pkgSetting.sharedUser != null) {
6879                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6880                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6881                            throw new PackageManagerException(
6882                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6883                                            "Signature mismatch for shared user : "
6884                                            + pkgSetting.sharedUser);
6885                        }
6886                    }
6887                    // File a report about this.
6888                    String msg = "System package " + pkg.packageName
6889                        + " signature changed; retaining data.";
6890                    reportSettingsProblem(Log.WARN, msg);
6891                }
6892            }
6893            // Verify that this new package doesn't have any content providers
6894            // that conflict with existing packages.  Only do this if the
6895            // package isn't already installed, since we don't want to break
6896            // things that are installed.
6897            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6898                final int N = pkg.providers.size();
6899                int i;
6900                for (i=0; i<N; i++) {
6901                    PackageParser.Provider p = pkg.providers.get(i);
6902                    if (p.info.authority != null) {
6903                        String names[] = p.info.authority.split(";");
6904                        for (int j = 0; j < names.length; j++) {
6905                            if (mProvidersByAuthority.containsKey(names[j])) {
6906                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6907                                final String otherPackageName =
6908                                        ((other != null && other.getComponentName() != null) ?
6909                                                other.getComponentName().getPackageName() : "?");
6910                                throw new PackageManagerException(
6911                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6912                                                "Can't install because provider name " + names[j]
6913                                                + " (in package " + pkg.applicationInfo.packageName
6914                                                + ") is already used by " + otherPackageName);
6915                            }
6916                        }
6917                    }
6918                }
6919            }
6920
6921            if (pkg.mAdoptPermissions != null) {
6922                // This package wants to adopt ownership of permissions from
6923                // another package.
6924                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6925                    final String origName = pkg.mAdoptPermissions.get(i);
6926                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6927                    if (orig != null) {
6928                        if (verifyPackageUpdateLPr(orig, pkg)) {
6929                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6930                                    + pkg.packageName);
6931                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6932                        }
6933                    }
6934                }
6935            }
6936        }
6937
6938        final String pkgName = pkg.packageName;
6939
6940        final long scanFileTime = scanFile.lastModified();
6941        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6942        pkg.applicationInfo.processName = fixProcessName(
6943                pkg.applicationInfo.packageName,
6944                pkg.applicationInfo.processName,
6945                pkg.applicationInfo.uid);
6946
6947        File dataPath;
6948        if (mPlatformPackage == pkg) {
6949            // The system package is special.
6950            dataPath = new File(Environment.getDataDirectory(), "system");
6951
6952            pkg.applicationInfo.dataDir = dataPath.getPath();
6953
6954        } else {
6955            // This is a normal package, need to make its data directory.
6956            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6957                    UserHandle.USER_SYSTEM, pkg.packageName);
6958
6959            boolean uidError = false;
6960            if (dataPath.exists()) {
6961                int currentUid = 0;
6962                try {
6963                    StructStat stat = Os.stat(dataPath.getPath());
6964                    currentUid = stat.st_uid;
6965                } catch (ErrnoException e) {
6966                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6967                }
6968
6969                // If we have mismatched owners for the data path, we have a problem.
6970                if (currentUid != pkg.applicationInfo.uid) {
6971                    boolean recovered = false;
6972                    if (currentUid == 0) {
6973                        // The directory somehow became owned by root.  Wow.
6974                        // This is probably because the system was stopped while
6975                        // installd was in the middle of messing with its libs
6976                        // directory.  Ask installd to fix that.
6977                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6978                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6979                        if (ret >= 0) {
6980                            recovered = true;
6981                            String msg = "Package " + pkg.packageName
6982                                    + " unexpectedly changed to uid 0; recovered to " +
6983                                    + pkg.applicationInfo.uid;
6984                            reportSettingsProblem(Log.WARN, msg);
6985                        }
6986                    }
6987                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6988                            || (scanFlags&SCAN_BOOTING) != 0)) {
6989                        // If this is a system app, we can at least delete its
6990                        // current data so the application will still work.
6991                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6992                        if (ret >= 0) {
6993                            // TODO: Kill the processes first
6994                            // Old data gone!
6995                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6996                                    ? "System package " : "Third party package ";
6997                            String msg = prefix + pkg.packageName
6998                                    + " has changed from uid: "
6999                                    + currentUid + " to "
7000                                    + pkg.applicationInfo.uid + "; old data erased";
7001                            reportSettingsProblem(Log.WARN, msg);
7002                            recovered = true;
7003
7004                            // And now re-install the app.
7005                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7006                                    pkg.applicationInfo.seinfo);
7007                            if (ret == -1) {
7008                                // Ack should not happen!
7009                                msg = prefix + pkg.packageName
7010                                        + " could not have data directory re-created after delete.";
7011                                reportSettingsProblem(Log.WARN, msg);
7012                                throw new PackageManagerException(
7013                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
7014                            }
7015                        }
7016                        if (!recovered) {
7017                            mHasSystemUidErrors = true;
7018                        }
7019                    } else if (!recovered) {
7020                        // If we allow this install to proceed, we will be broken.
7021                        // Abort, abort!
7022                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7023                                "scanPackageLI");
7024                    }
7025                    if (!recovered) {
7026                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7027                            + pkg.applicationInfo.uid + "/fs_"
7028                            + currentUid;
7029                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7030                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7031                        String msg = "Package " + pkg.packageName
7032                                + " has mismatched uid: "
7033                                + currentUid + " on disk, "
7034                                + pkg.applicationInfo.uid + " in settings";
7035                        // writer
7036                        synchronized (mPackages) {
7037                            mSettings.mReadMessages.append(msg);
7038                            mSettings.mReadMessages.append('\n');
7039                            uidError = true;
7040                            if (!pkgSetting.uidError) {
7041                                reportSettingsProblem(Log.ERROR, msg);
7042                            }
7043                        }
7044                    }
7045                }
7046                pkg.applicationInfo.dataDir = dataPath.getPath();
7047                if (mShouldRestoreconData) {
7048                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7049                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7050                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7051                }
7052            } else {
7053                if (DEBUG_PACKAGE_SCANNING) {
7054                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7055                        Log.v(TAG, "Want this data dir: " + dataPath);
7056                }
7057                //invoke installer to do the actual installation
7058                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7059                        pkg.applicationInfo.seinfo);
7060                if (ret < 0) {
7061                    // Error from installer
7062                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7063                            "Unable to create data dirs [errorCode=" + ret + "]");
7064                }
7065
7066                if (dataPath.exists()) {
7067                    pkg.applicationInfo.dataDir = dataPath.getPath();
7068                } else {
7069                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
7070                    pkg.applicationInfo.dataDir = null;
7071                }
7072            }
7073
7074            pkgSetting.uidError = uidError;
7075        }
7076
7077        final String path = scanFile.getPath();
7078        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7079
7080        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7081            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7082
7083            // Some system apps still use directory structure for native libraries
7084            // in which case we might end up not detecting abi solely based on apk
7085            // structure. Try to detect abi based on directory structure.
7086            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7087                    pkg.applicationInfo.primaryCpuAbi == null) {
7088                setBundledAppAbisAndRoots(pkg, pkgSetting);
7089                setNativeLibraryPaths(pkg);
7090            }
7091
7092        } else {
7093            if ((scanFlags & SCAN_MOVE) != 0) {
7094                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7095                // but we already have this packages package info in the PackageSetting. We just
7096                // use that and derive the native library path based on the new codepath.
7097                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7098                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7099            }
7100
7101            // Set native library paths again. For moves, the path will be updated based on the
7102            // ABIs we've determined above. For non-moves, the path will be updated based on the
7103            // ABIs we determined during compilation, but the path will depend on the final
7104            // package path (after the rename away from the stage path).
7105            setNativeLibraryPaths(pkg);
7106        }
7107
7108        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7109        final int[] userIds = sUserManager.getUserIds();
7110        synchronized (mInstallLock) {
7111            // Make sure all user data directories are ready to roll; we're okay
7112            // if they already exist
7113            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7114                for (int userId : userIds) {
7115                    if (userId != UserHandle.USER_SYSTEM) {
7116                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7117                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7118                                pkg.applicationInfo.seinfo);
7119                    }
7120                }
7121            }
7122
7123            // Create a native library symlink only if we have native libraries
7124            // and if the native libraries are 32 bit libraries. We do not provide
7125            // this symlink for 64 bit libraries.
7126            if (pkg.applicationInfo.primaryCpuAbi != null &&
7127                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7128                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7129                try {
7130                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7131                    for (int userId : userIds) {
7132                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7133                                nativeLibPath, userId) < 0) {
7134                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7135                                    "Failed linking native library dir (user=" + userId + ")");
7136                        }
7137                    }
7138                } finally {
7139                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7140                }
7141            }
7142        }
7143
7144        // This is a special case for the "system" package, where the ABI is
7145        // dictated by the zygote configuration (and init.rc). We should keep track
7146        // of this ABI so that we can deal with "normal" applications that run under
7147        // the same UID correctly.
7148        if (mPlatformPackage == pkg) {
7149            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7150                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7151        }
7152
7153        // If there's a mismatch between the abi-override in the package setting
7154        // and the abiOverride specified for the install. Warn about this because we
7155        // would've already compiled the app without taking the package setting into
7156        // account.
7157        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7158            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7159                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7160                        " for package: " + pkg.packageName);
7161            }
7162        }
7163
7164        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7165        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7166        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7167
7168        // Copy the derived override back to the parsed package, so that we can
7169        // update the package settings accordingly.
7170        pkg.cpuAbiOverride = cpuAbiOverride;
7171
7172        if (DEBUG_ABI_SELECTION) {
7173            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7174                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7175                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7176        }
7177
7178        // Push the derived path down into PackageSettings so we know what to
7179        // clean up at uninstall time.
7180        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7181
7182        if (DEBUG_ABI_SELECTION) {
7183            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7184                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7185                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7186        }
7187
7188        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7189            // We don't do this here during boot because we can do it all
7190            // at once after scanning all existing packages.
7191            //
7192            // We also do this *before* we perform dexopt on this package, so that
7193            // we can avoid redundant dexopts, and also to make sure we've got the
7194            // code and package path correct.
7195            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7196                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */);
7197        }
7198
7199        if ((scanFlags & SCAN_NO_DEX) == 0) {
7200            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7201
7202            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7203                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */,
7204                    (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/);
7205
7206            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7207            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7208                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7209            }
7210        }
7211        if (mFactoryTest && pkg.requestedPermissions.contains(
7212                android.Manifest.permission.FACTORY_TEST)) {
7213            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7214        }
7215
7216        ArrayList<PackageParser.Package> clientLibPkgs = null;
7217
7218        // writer
7219        synchronized (mPackages) {
7220            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7221                // Only system apps can add new shared libraries.
7222                if (pkg.libraryNames != null) {
7223                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7224                        String name = pkg.libraryNames.get(i);
7225                        boolean allowed = false;
7226                        if (pkg.isUpdatedSystemApp()) {
7227                            // New library entries can only be added through the
7228                            // system image.  This is important to get rid of a lot
7229                            // of nasty edge cases: for example if we allowed a non-
7230                            // system update of the app to add a library, then uninstalling
7231                            // the update would make the library go away, and assumptions
7232                            // we made such as through app install filtering would now
7233                            // have allowed apps on the device which aren't compatible
7234                            // with it.  Better to just have the restriction here, be
7235                            // conservative, and create many fewer cases that can negatively
7236                            // impact the user experience.
7237                            final PackageSetting sysPs = mSettings
7238                                    .getDisabledSystemPkgLPr(pkg.packageName);
7239                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7240                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7241                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7242                                        allowed = true;
7243                                        break;
7244                                    }
7245                                }
7246                            }
7247                        } else {
7248                            allowed = true;
7249                        }
7250                        if (allowed) {
7251                            if (!mSharedLibraries.containsKey(name)) {
7252                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7253                            } else if (!name.equals(pkg.packageName)) {
7254                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7255                                        + name + " already exists; skipping");
7256                            }
7257                        } else {
7258                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7259                                    + name + " that is not declared on system image; skipping");
7260                        }
7261                    }
7262                    if ((scanFlags&SCAN_BOOTING) == 0) {
7263                        // If we are not booting, we need to update any applications
7264                        // that are clients of our shared library.  If we are booting,
7265                        // this will all be done once the scan is complete.
7266                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7267                    }
7268                }
7269            }
7270        }
7271
7272        // We also need to dexopt any apps that are dependent on this library.  Note that
7273        // if these fail, we should abort the install since installing the library will
7274        // result in some apps being broken.
7275        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7276        try {
7277            if (clientLibPkgs != null) {
7278                if ((scanFlags & SCAN_NO_DEX) == 0) {
7279                    for (int i = 0; i < clientLibPkgs.size(); i++) {
7280                        PackageParser.Package clientPkg = clientLibPkgs.get(i);
7281                        int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7282                                null /* instruction sets */, forceDex,
7283                                (scanFlags & SCAN_DEFER_DEX) != 0, false,
7284                                (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/);
7285                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7286                            throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7287                                    "scanPackageLI failed to dexopt clientLibPkgs");
7288                        }
7289                    }
7290                }
7291            }
7292        } finally {
7293            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7294        }
7295
7296        // Request the ActivityManager to kill the process(only for existing packages)
7297        // so that we do not end up in a confused state while the user is still using the older
7298        // version of the application while the new one gets installed.
7299        if ((scanFlags & SCAN_REPLACING) != 0) {
7300            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7301
7302            killApplication(pkg.applicationInfo.packageName,
7303                        pkg.applicationInfo.uid, "replace pkg");
7304
7305            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7306        }
7307
7308        // Also need to kill any apps that are dependent on the library.
7309        if (clientLibPkgs != null) {
7310            for (int i=0; i<clientLibPkgs.size(); i++) {
7311                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7312                killApplication(clientPkg.applicationInfo.packageName,
7313                        clientPkg.applicationInfo.uid, "update lib");
7314            }
7315        }
7316
7317        // Make sure we're not adding any bogus keyset info
7318        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7319        ksms.assertScannedPackageValid(pkg);
7320
7321        // writer
7322        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7323
7324        boolean createIdmapFailed = false;
7325        synchronized (mPackages) {
7326            // We don't expect installation to fail beyond this point
7327
7328            // Add the new setting to mSettings
7329            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7330            // Add the new setting to mPackages
7331            mPackages.put(pkg.applicationInfo.packageName, pkg);
7332            // Make sure we don't accidentally delete its data.
7333            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7334            while (iter.hasNext()) {
7335                PackageCleanItem item = iter.next();
7336                if (pkgName.equals(item.packageName)) {
7337                    iter.remove();
7338                }
7339            }
7340
7341            // Take care of first install / last update times.
7342            if (currentTime != 0) {
7343                if (pkgSetting.firstInstallTime == 0) {
7344                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7345                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7346                    pkgSetting.lastUpdateTime = currentTime;
7347                }
7348            } else if (pkgSetting.firstInstallTime == 0) {
7349                // We need *something*.  Take time time stamp of the file.
7350                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7351            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7352                if (scanFileTime != pkgSetting.timeStamp) {
7353                    // A package on the system image has changed; consider this
7354                    // to be an update.
7355                    pkgSetting.lastUpdateTime = scanFileTime;
7356                }
7357            }
7358
7359            // Add the package's KeySets to the global KeySetManagerService
7360            ksms.addScannedPackageLPw(pkg);
7361
7362            int N = pkg.providers.size();
7363            StringBuilder r = null;
7364            int i;
7365            for (i=0; i<N; i++) {
7366                PackageParser.Provider p = pkg.providers.get(i);
7367                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7368                        p.info.processName, pkg.applicationInfo.uid);
7369                mProviders.addProvider(p);
7370                p.syncable = p.info.isSyncable;
7371                if (p.info.authority != null) {
7372                    String names[] = p.info.authority.split(";");
7373                    p.info.authority = null;
7374                    for (int j = 0; j < names.length; j++) {
7375                        if (j == 1 && p.syncable) {
7376                            // We only want the first authority for a provider to possibly be
7377                            // syncable, so if we already added this provider using a different
7378                            // authority clear the syncable flag. We copy the provider before
7379                            // changing it because the mProviders object contains a reference
7380                            // to a provider that we don't want to change.
7381                            // Only do this for the second authority since the resulting provider
7382                            // object can be the same for all future authorities for this provider.
7383                            p = new PackageParser.Provider(p);
7384                            p.syncable = false;
7385                        }
7386                        if (!mProvidersByAuthority.containsKey(names[j])) {
7387                            mProvidersByAuthority.put(names[j], p);
7388                            if (p.info.authority == null) {
7389                                p.info.authority = names[j];
7390                            } else {
7391                                p.info.authority = p.info.authority + ";" + names[j];
7392                            }
7393                            if (DEBUG_PACKAGE_SCANNING) {
7394                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7395                                    Log.d(TAG, "Registered content provider: " + names[j]
7396                                            + ", className = " + p.info.name + ", isSyncable = "
7397                                            + p.info.isSyncable);
7398                            }
7399                        } else {
7400                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7401                            Slog.w(TAG, "Skipping provider name " + names[j] +
7402                                    " (in package " + pkg.applicationInfo.packageName +
7403                                    "): name already used by "
7404                                    + ((other != null && other.getComponentName() != null)
7405                                            ? other.getComponentName().getPackageName() : "?"));
7406                        }
7407                    }
7408                }
7409                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7410                    if (r == null) {
7411                        r = new StringBuilder(256);
7412                    } else {
7413                        r.append(' ');
7414                    }
7415                    r.append(p.info.name);
7416                }
7417            }
7418            if (r != null) {
7419                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7420            }
7421
7422            N = pkg.services.size();
7423            r = null;
7424            for (i=0; i<N; i++) {
7425                PackageParser.Service s = pkg.services.get(i);
7426                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7427                        s.info.processName, pkg.applicationInfo.uid);
7428                mServices.addService(s);
7429                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7430                    if (r == null) {
7431                        r = new StringBuilder(256);
7432                    } else {
7433                        r.append(' ');
7434                    }
7435                    r.append(s.info.name);
7436                }
7437            }
7438            if (r != null) {
7439                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7440            }
7441
7442            N = pkg.receivers.size();
7443            r = null;
7444            for (i=0; i<N; i++) {
7445                PackageParser.Activity a = pkg.receivers.get(i);
7446                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7447                        a.info.processName, pkg.applicationInfo.uid);
7448                mReceivers.addActivity(a, "receiver");
7449                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7450                    if (r == null) {
7451                        r = new StringBuilder(256);
7452                    } else {
7453                        r.append(' ');
7454                    }
7455                    r.append(a.info.name);
7456                }
7457            }
7458            if (r != null) {
7459                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7460            }
7461
7462            N = pkg.activities.size();
7463            r = null;
7464            for (i=0; i<N; i++) {
7465                PackageParser.Activity a = pkg.activities.get(i);
7466                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7467                        a.info.processName, pkg.applicationInfo.uid);
7468                mActivities.addActivity(a, "activity");
7469                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7470                    if (r == null) {
7471                        r = new StringBuilder(256);
7472                    } else {
7473                        r.append(' ');
7474                    }
7475                    r.append(a.info.name);
7476                }
7477            }
7478            if (r != null) {
7479                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7480            }
7481
7482            N = pkg.permissionGroups.size();
7483            r = null;
7484            for (i=0; i<N; i++) {
7485                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7486                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7487                if (cur == null) {
7488                    mPermissionGroups.put(pg.info.name, pg);
7489                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7490                        if (r == null) {
7491                            r = new StringBuilder(256);
7492                        } else {
7493                            r.append(' ');
7494                        }
7495                        r.append(pg.info.name);
7496                    }
7497                } else {
7498                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7499                            + pg.info.packageName + " ignored: original from "
7500                            + cur.info.packageName);
7501                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7502                        if (r == null) {
7503                            r = new StringBuilder(256);
7504                        } else {
7505                            r.append(' ');
7506                        }
7507                        r.append("DUP:");
7508                        r.append(pg.info.name);
7509                    }
7510                }
7511            }
7512            if (r != null) {
7513                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7514            }
7515
7516            N = pkg.permissions.size();
7517            r = null;
7518            for (i=0; i<N; i++) {
7519                PackageParser.Permission p = pkg.permissions.get(i);
7520
7521                // Assume by default that we did not install this permission into the system.
7522                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7523
7524                // Now that permission groups have a special meaning, we ignore permission
7525                // groups for legacy apps to prevent unexpected behavior. In particular,
7526                // permissions for one app being granted to someone just becuase they happen
7527                // to be in a group defined by another app (before this had no implications).
7528                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7529                    p.group = mPermissionGroups.get(p.info.group);
7530                    // Warn for a permission in an unknown group.
7531                    if (p.info.group != null && p.group == null) {
7532                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7533                                + p.info.packageName + " in an unknown group " + p.info.group);
7534                    }
7535                }
7536
7537                ArrayMap<String, BasePermission> permissionMap =
7538                        p.tree ? mSettings.mPermissionTrees
7539                                : mSettings.mPermissions;
7540                BasePermission bp = permissionMap.get(p.info.name);
7541
7542                // Allow system apps to redefine non-system permissions
7543                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7544                    final boolean currentOwnerIsSystem = (bp.perm != null
7545                            && isSystemApp(bp.perm.owner));
7546                    if (isSystemApp(p.owner)) {
7547                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7548                            // It's a built-in permission and no owner, take ownership now
7549                            bp.packageSetting = pkgSetting;
7550                            bp.perm = p;
7551                            bp.uid = pkg.applicationInfo.uid;
7552                            bp.sourcePackage = p.info.packageName;
7553                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7554                        } else if (!currentOwnerIsSystem) {
7555                            String msg = "New decl " + p.owner + " of permission  "
7556                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7557                            reportSettingsProblem(Log.WARN, msg);
7558                            bp = null;
7559                        }
7560                    }
7561                }
7562
7563                if (bp == null) {
7564                    bp = new BasePermission(p.info.name, p.info.packageName,
7565                            BasePermission.TYPE_NORMAL);
7566                    permissionMap.put(p.info.name, bp);
7567                }
7568
7569                if (bp.perm == null) {
7570                    if (bp.sourcePackage == null
7571                            || bp.sourcePackage.equals(p.info.packageName)) {
7572                        BasePermission tree = findPermissionTreeLP(p.info.name);
7573                        if (tree == null
7574                                || tree.sourcePackage.equals(p.info.packageName)) {
7575                            bp.packageSetting = pkgSetting;
7576                            bp.perm = p;
7577                            bp.uid = pkg.applicationInfo.uid;
7578                            bp.sourcePackage = p.info.packageName;
7579                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7580                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7581                                if (r == null) {
7582                                    r = new StringBuilder(256);
7583                                } else {
7584                                    r.append(' ');
7585                                }
7586                                r.append(p.info.name);
7587                            }
7588                        } else {
7589                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7590                                    + p.info.packageName + " ignored: base tree "
7591                                    + tree.name + " is from package "
7592                                    + tree.sourcePackage);
7593                        }
7594                    } else {
7595                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7596                                + p.info.packageName + " ignored: original from "
7597                                + bp.sourcePackage);
7598                    }
7599                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7600                    if (r == null) {
7601                        r = new StringBuilder(256);
7602                    } else {
7603                        r.append(' ');
7604                    }
7605                    r.append("DUP:");
7606                    r.append(p.info.name);
7607                }
7608                if (bp.perm == p) {
7609                    bp.protectionLevel = p.info.protectionLevel;
7610                }
7611            }
7612
7613            if (r != null) {
7614                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7615            }
7616
7617            N = pkg.instrumentation.size();
7618            r = null;
7619            for (i=0; i<N; i++) {
7620                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7621                a.info.packageName = pkg.applicationInfo.packageName;
7622                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7623                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7624                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7625                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7626                a.info.dataDir = pkg.applicationInfo.dataDir;
7627
7628                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7629                // need other information about the application, like the ABI and what not ?
7630                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7631                mInstrumentation.put(a.getComponentName(), a);
7632                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7633                    if (r == null) {
7634                        r = new StringBuilder(256);
7635                    } else {
7636                        r.append(' ');
7637                    }
7638                    r.append(a.info.name);
7639                }
7640            }
7641            if (r != null) {
7642                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7643            }
7644
7645            if (pkg.protectedBroadcasts != null) {
7646                N = pkg.protectedBroadcasts.size();
7647                for (i=0; i<N; i++) {
7648                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7649                }
7650            }
7651
7652            pkgSetting.setTimeStamp(scanFileTime);
7653
7654            // Create idmap files for pairs of (packages, overlay packages).
7655            // Note: "android", ie framework-res.apk, is handled by native layers.
7656            if (pkg.mOverlayTarget != null) {
7657                // This is an overlay package.
7658                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7659                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7660                        mOverlays.put(pkg.mOverlayTarget,
7661                                new ArrayMap<String, PackageParser.Package>());
7662                    }
7663                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7664                    map.put(pkg.packageName, pkg);
7665                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7666                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7667                        createIdmapFailed = true;
7668                    }
7669                }
7670            } else if (mOverlays.containsKey(pkg.packageName) &&
7671                    !pkg.packageName.equals("android")) {
7672                // This is a regular package, with one or more known overlay packages.
7673                createIdmapsForPackageLI(pkg);
7674            }
7675        }
7676
7677        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7678
7679        if (createIdmapFailed) {
7680            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7681                    "scanPackageLI failed to createIdmap");
7682        }
7683        return pkg;
7684    }
7685
7686    /**
7687     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7688     * is derived purely on the basis of the contents of {@code scanFile} and
7689     * {@code cpuAbiOverride}.
7690     *
7691     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7692     */
7693    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7694                                 String cpuAbiOverride, boolean extractLibs)
7695            throws PackageManagerException {
7696        // TODO: We can probably be smarter about this stuff. For installed apps,
7697        // we can calculate this information at install time once and for all. For
7698        // system apps, we can probably assume that this information doesn't change
7699        // after the first boot scan. As things stand, we do lots of unnecessary work.
7700
7701        // Give ourselves some initial paths; we'll come back for another
7702        // pass once we've determined ABI below.
7703        setNativeLibraryPaths(pkg);
7704
7705        // We would never need to extract libs for forward-locked and external packages,
7706        // since the container service will do it for us. We shouldn't attempt to
7707        // extract libs from system app when it was not updated.
7708        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7709                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7710            extractLibs = false;
7711        }
7712
7713        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7714        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7715
7716        NativeLibraryHelper.Handle handle = null;
7717        try {
7718            handle = NativeLibraryHelper.Handle.create(pkg);
7719            // TODO(multiArch): This can be null for apps that didn't go through the
7720            // usual installation process. We can calculate it again, like we
7721            // do during install time.
7722            //
7723            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7724            // unnecessary.
7725            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7726
7727            // Null out the abis so that they can be recalculated.
7728            pkg.applicationInfo.primaryCpuAbi = null;
7729            pkg.applicationInfo.secondaryCpuAbi = null;
7730            if (isMultiArch(pkg.applicationInfo)) {
7731                // Warn if we've set an abiOverride for multi-lib packages..
7732                // By definition, we need to copy both 32 and 64 bit libraries for
7733                // such packages.
7734                if (pkg.cpuAbiOverride != null
7735                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7736                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7737                }
7738
7739                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7740                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7741                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7742                    if (extractLibs) {
7743                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7744                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7745                                useIsaSpecificSubdirs);
7746                    } else {
7747                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7748                    }
7749                }
7750
7751                maybeThrowExceptionForMultiArchCopy(
7752                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7753
7754                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7755                    if (extractLibs) {
7756                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7757                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7758                                useIsaSpecificSubdirs);
7759                    } else {
7760                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7761                    }
7762                }
7763
7764                maybeThrowExceptionForMultiArchCopy(
7765                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7766
7767                if (abi64 >= 0) {
7768                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7769                }
7770
7771                if (abi32 >= 0) {
7772                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7773                    if (abi64 >= 0) {
7774                        pkg.applicationInfo.secondaryCpuAbi = abi;
7775                    } else {
7776                        pkg.applicationInfo.primaryCpuAbi = abi;
7777                    }
7778                }
7779            } else {
7780                String[] abiList = (cpuAbiOverride != null) ?
7781                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7782
7783                // Enable gross and lame hacks for apps that are built with old
7784                // SDK tools. We must scan their APKs for renderscript bitcode and
7785                // not launch them if it's present. Don't bother checking on devices
7786                // that don't have 64 bit support.
7787                boolean needsRenderScriptOverride = false;
7788                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7789                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7790                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7791                    needsRenderScriptOverride = true;
7792                }
7793
7794                final int copyRet;
7795                if (extractLibs) {
7796                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7797                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7798                } else {
7799                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7800                }
7801
7802                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7803                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7804                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7805                }
7806
7807                if (copyRet >= 0) {
7808                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7809                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7810                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7811                } else if (needsRenderScriptOverride) {
7812                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7813                }
7814            }
7815        } catch (IOException ioe) {
7816            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7817        } finally {
7818            IoUtils.closeQuietly(handle);
7819        }
7820
7821        // Now that we've calculated the ABIs and determined if it's an internal app,
7822        // we will go ahead and populate the nativeLibraryPath.
7823        setNativeLibraryPaths(pkg);
7824    }
7825
7826    /**
7827     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7828     * i.e, so that all packages can be run inside a single process if required.
7829     *
7830     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7831     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7832     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7833     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7834     * updating a package that belongs to a shared user.
7835     *
7836     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7837     * adds unnecessary complexity.
7838     */
7839    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7840            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt,
7841            boolean bootComplete) {
7842        String requiredInstructionSet = null;
7843        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7844            requiredInstructionSet = VMRuntime.getInstructionSet(
7845                     scannedPackage.applicationInfo.primaryCpuAbi);
7846        }
7847
7848        PackageSetting requirer = null;
7849        for (PackageSetting ps : packagesForUser) {
7850            // If packagesForUser contains scannedPackage, we skip it. This will happen
7851            // when scannedPackage is an update of an existing package. Without this check,
7852            // we will never be able to change the ABI of any package belonging to a shared
7853            // user, even if it's compatible with other packages.
7854            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7855                if (ps.primaryCpuAbiString == null) {
7856                    continue;
7857                }
7858
7859                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7860                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7861                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7862                    // this but there's not much we can do.
7863                    String errorMessage = "Instruction set mismatch, "
7864                            + ((requirer == null) ? "[caller]" : requirer)
7865                            + " requires " + requiredInstructionSet + " whereas " + ps
7866                            + " requires " + instructionSet;
7867                    Slog.w(TAG, errorMessage);
7868                }
7869
7870                if (requiredInstructionSet == null) {
7871                    requiredInstructionSet = instructionSet;
7872                    requirer = ps;
7873                }
7874            }
7875        }
7876
7877        if (requiredInstructionSet != null) {
7878            String adjustedAbi;
7879            if (requirer != null) {
7880                // requirer != null implies that either scannedPackage was null or that scannedPackage
7881                // did not require an ABI, in which case we have to adjust scannedPackage to match
7882                // the ABI of the set (which is the same as requirer's ABI)
7883                adjustedAbi = requirer.primaryCpuAbiString;
7884                if (scannedPackage != null) {
7885                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7886                }
7887            } else {
7888                // requirer == null implies that we're updating all ABIs in the set to
7889                // match scannedPackage.
7890                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7891            }
7892
7893            for (PackageSetting ps : packagesForUser) {
7894                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7895                    if (ps.primaryCpuAbiString != null) {
7896                        continue;
7897                    }
7898
7899                    ps.primaryCpuAbiString = adjustedAbi;
7900                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7901                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7902                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7903
7904                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7905
7906                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7907                                null /* instruction sets */, forceDexOpt, deferDexOpt, true,
7908                                bootComplete, false /*useJit*/);
7909
7910                        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7911                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7912                            ps.primaryCpuAbiString = null;
7913                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7914                            return;
7915                        } else {
7916                            mInstaller.rmdex(ps.codePathString,
7917                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7918                        }
7919                    }
7920                }
7921            }
7922        }
7923    }
7924
7925    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7926        synchronized (mPackages) {
7927            mResolverReplaced = true;
7928            // Set up information for custom user intent resolution activity.
7929            mResolveActivity.applicationInfo = pkg.applicationInfo;
7930            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7931            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7932            mResolveActivity.processName = pkg.applicationInfo.packageName;
7933            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7934            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7935                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7936            mResolveActivity.theme = 0;
7937            mResolveActivity.exported = true;
7938            mResolveActivity.enabled = true;
7939            mResolveInfo.activityInfo = mResolveActivity;
7940            mResolveInfo.priority = 0;
7941            mResolveInfo.preferredOrder = 0;
7942            mResolveInfo.match = 0;
7943            mResolveComponentName = mCustomResolverComponentName;
7944            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7945                    mResolveComponentName);
7946        }
7947    }
7948
7949    private static String calculateBundledApkRoot(final String codePathString) {
7950        final File codePath = new File(codePathString);
7951        final File codeRoot;
7952        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7953            codeRoot = Environment.getRootDirectory();
7954        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7955            codeRoot = Environment.getOemDirectory();
7956        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7957            codeRoot = Environment.getVendorDirectory();
7958        } else {
7959            // Unrecognized code path; take its top real segment as the apk root:
7960            // e.g. /something/app/blah.apk => /something
7961            try {
7962                File f = codePath.getCanonicalFile();
7963                File parent = f.getParentFile();    // non-null because codePath is a file
7964                File tmp;
7965                while ((tmp = parent.getParentFile()) != null) {
7966                    f = parent;
7967                    parent = tmp;
7968                }
7969                codeRoot = f;
7970                Slog.w(TAG, "Unrecognized code path "
7971                        + codePath + " - using " + codeRoot);
7972            } catch (IOException e) {
7973                // Can't canonicalize the code path -- shenanigans?
7974                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7975                return Environment.getRootDirectory().getPath();
7976            }
7977        }
7978        return codeRoot.getPath();
7979    }
7980
7981    /**
7982     * Derive and set the location of native libraries for the given package,
7983     * which varies depending on where and how the package was installed.
7984     */
7985    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7986        final ApplicationInfo info = pkg.applicationInfo;
7987        final String codePath = pkg.codePath;
7988        final File codeFile = new File(codePath);
7989        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7990        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
7991
7992        info.nativeLibraryRootDir = null;
7993        info.nativeLibraryRootRequiresIsa = false;
7994        info.nativeLibraryDir = null;
7995        info.secondaryNativeLibraryDir = null;
7996
7997        if (isApkFile(codeFile)) {
7998            // Monolithic install
7999            if (bundledApp) {
8000                // If "/system/lib64/apkname" exists, assume that is the per-package
8001                // native library directory to use; otherwise use "/system/lib/apkname".
8002                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8003                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8004                        getPrimaryInstructionSet(info));
8005
8006                // This is a bundled system app so choose the path based on the ABI.
8007                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8008                // is just the default path.
8009                final String apkName = deriveCodePathName(codePath);
8010                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8011                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8012                        apkName).getAbsolutePath();
8013
8014                if (info.secondaryCpuAbi != null) {
8015                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8016                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8017                            secondaryLibDir, apkName).getAbsolutePath();
8018                }
8019            } else if (asecApp) {
8020                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8021                        .getAbsolutePath();
8022            } else {
8023                final String apkName = deriveCodePathName(codePath);
8024                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8025                        .getAbsolutePath();
8026            }
8027
8028            info.nativeLibraryRootRequiresIsa = false;
8029            info.nativeLibraryDir = info.nativeLibraryRootDir;
8030        } else {
8031            // Cluster install
8032            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8033            info.nativeLibraryRootRequiresIsa = true;
8034
8035            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8036                    getPrimaryInstructionSet(info)).getAbsolutePath();
8037
8038            if (info.secondaryCpuAbi != null) {
8039                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8040                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8041            }
8042        }
8043    }
8044
8045    /**
8046     * Calculate the abis and roots for a bundled app. These can uniquely
8047     * be determined from the contents of the system partition, i.e whether
8048     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8049     * of this information, and instead assume that the system was built
8050     * sensibly.
8051     */
8052    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8053                                           PackageSetting pkgSetting) {
8054        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8055
8056        // If "/system/lib64/apkname" exists, assume that is the per-package
8057        // native library directory to use; otherwise use "/system/lib/apkname".
8058        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8059        setBundledAppAbi(pkg, apkRoot, apkName);
8060        // pkgSetting might be null during rescan following uninstall of updates
8061        // to a bundled app, so accommodate that possibility.  The settings in
8062        // that case will be established later from the parsed package.
8063        //
8064        // If the settings aren't null, sync them up with what we've just derived.
8065        // note that apkRoot isn't stored in the package settings.
8066        if (pkgSetting != null) {
8067            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8068            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8069        }
8070    }
8071
8072    /**
8073     * Deduces the ABI of a bundled app and sets the relevant fields on the
8074     * parsed pkg object.
8075     *
8076     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8077     *        under which system libraries are installed.
8078     * @param apkName the name of the installed package.
8079     */
8080    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8081        final File codeFile = new File(pkg.codePath);
8082
8083        final boolean has64BitLibs;
8084        final boolean has32BitLibs;
8085        if (isApkFile(codeFile)) {
8086            // Monolithic install
8087            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8088            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8089        } else {
8090            // Cluster install
8091            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8092            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8093                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8094                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8095                has64BitLibs = (new File(rootDir, isa)).exists();
8096            } else {
8097                has64BitLibs = false;
8098            }
8099            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8100                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8101                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8102                has32BitLibs = (new File(rootDir, isa)).exists();
8103            } else {
8104                has32BitLibs = false;
8105            }
8106        }
8107
8108        if (has64BitLibs && !has32BitLibs) {
8109            // The package has 64 bit libs, but not 32 bit libs. Its primary
8110            // ABI should be 64 bit. We can safely assume here that the bundled
8111            // native libraries correspond to the most preferred ABI in the list.
8112
8113            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8114            pkg.applicationInfo.secondaryCpuAbi = null;
8115        } else if (has32BitLibs && !has64BitLibs) {
8116            // The package has 32 bit libs but not 64 bit libs. Its primary
8117            // ABI should be 32 bit.
8118
8119            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8120            pkg.applicationInfo.secondaryCpuAbi = null;
8121        } else if (has32BitLibs && has64BitLibs) {
8122            // The application has both 64 and 32 bit bundled libraries. We check
8123            // here that the app declares multiArch support, and warn if it doesn't.
8124            //
8125            // We will be lenient here and record both ABIs. The primary will be the
8126            // ABI that's higher on the list, i.e, a device that's configured to prefer
8127            // 64 bit apps will see a 64 bit primary ABI,
8128
8129            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8130                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8131            }
8132
8133            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8134                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8135                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8136            } else {
8137                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8138                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8139            }
8140        } else {
8141            pkg.applicationInfo.primaryCpuAbi = null;
8142            pkg.applicationInfo.secondaryCpuAbi = null;
8143        }
8144    }
8145
8146    private void killApplication(String pkgName, int appId, String reason) {
8147        // Request the ActivityManager to kill the process(only for existing packages)
8148        // so that we do not end up in a confused state while the user is still using the older
8149        // version of the application while the new one gets installed.
8150        IActivityManager am = ActivityManagerNative.getDefault();
8151        if (am != null) {
8152            try {
8153                am.killApplicationWithAppId(pkgName, appId, reason);
8154            } catch (RemoteException e) {
8155            }
8156        }
8157    }
8158
8159    void removePackageLI(PackageSetting ps, boolean chatty) {
8160        if (DEBUG_INSTALL) {
8161            if (chatty)
8162                Log.d(TAG, "Removing package " + ps.name);
8163        }
8164
8165        // writer
8166        synchronized (mPackages) {
8167            mPackages.remove(ps.name);
8168            final PackageParser.Package pkg = ps.pkg;
8169            if (pkg != null) {
8170                cleanPackageDataStructuresLILPw(pkg, chatty);
8171            }
8172        }
8173    }
8174
8175    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8176        if (DEBUG_INSTALL) {
8177            if (chatty)
8178                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8179        }
8180
8181        // writer
8182        synchronized (mPackages) {
8183            mPackages.remove(pkg.applicationInfo.packageName);
8184            cleanPackageDataStructuresLILPw(pkg, chatty);
8185        }
8186    }
8187
8188    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8189        int N = pkg.providers.size();
8190        StringBuilder r = null;
8191        int i;
8192        for (i=0; i<N; i++) {
8193            PackageParser.Provider p = pkg.providers.get(i);
8194            mProviders.removeProvider(p);
8195            if (p.info.authority == null) {
8196
8197                /* There was another ContentProvider with this authority when
8198                 * this app was installed so this authority is null,
8199                 * Ignore it as we don't have to unregister the provider.
8200                 */
8201                continue;
8202            }
8203            String names[] = p.info.authority.split(";");
8204            for (int j = 0; j < names.length; j++) {
8205                if (mProvidersByAuthority.get(names[j]) == p) {
8206                    mProvidersByAuthority.remove(names[j]);
8207                    if (DEBUG_REMOVE) {
8208                        if (chatty)
8209                            Log.d(TAG, "Unregistered content provider: " + names[j]
8210                                    + ", className = " + p.info.name + ", isSyncable = "
8211                                    + p.info.isSyncable);
8212                    }
8213                }
8214            }
8215            if (DEBUG_REMOVE && chatty) {
8216                if (r == null) {
8217                    r = new StringBuilder(256);
8218                } else {
8219                    r.append(' ');
8220                }
8221                r.append(p.info.name);
8222            }
8223        }
8224        if (r != null) {
8225            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8226        }
8227
8228        N = pkg.services.size();
8229        r = null;
8230        for (i=0; i<N; i++) {
8231            PackageParser.Service s = pkg.services.get(i);
8232            mServices.removeService(s);
8233            if (chatty) {
8234                if (r == null) {
8235                    r = new StringBuilder(256);
8236                } else {
8237                    r.append(' ');
8238                }
8239                r.append(s.info.name);
8240            }
8241        }
8242        if (r != null) {
8243            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8244        }
8245
8246        N = pkg.receivers.size();
8247        r = null;
8248        for (i=0; i<N; i++) {
8249            PackageParser.Activity a = pkg.receivers.get(i);
8250            mReceivers.removeActivity(a, "receiver");
8251            if (DEBUG_REMOVE && chatty) {
8252                if (r == null) {
8253                    r = new StringBuilder(256);
8254                } else {
8255                    r.append(' ');
8256                }
8257                r.append(a.info.name);
8258            }
8259        }
8260        if (r != null) {
8261            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8262        }
8263
8264        N = pkg.activities.size();
8265        r = null;
8266        for (i=0; i<N; i++) {
8267            PackageParser.Activity a = pkg.activities.get(i);
8268            mActivities.removeActivity(a, "activity");
8269            if (DEBUG_REMOVE && chatty) {
8270                if (r == null) {
8271                    r = new StringBuilder(256);
8272                } else {
8273                    r.append(' ');
8274                }
8275                r.append(a.info.name);
8276            }
8277        }
8278        if (r != null) {
8279            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8280        }
8281
8282        N = pkg.permissions.size();
8283        r = null;
8284        for (i=0; i<N; i++) {
8285            PackageParser.Permission p = pkg.permissions.get(i);
8286            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8287            if (bp == null) {
8288                bp = mSettings.mPermissionTrees.get(p.info.name);
8289            }
8290            if (bp != null && bp.perm == p) {
8291                bp.perm = null;
8292                if (DEBUG_REMOVE && chatty) {
8293                    if (r == null) {
8294                        r = new StringBuilder(256);
8295                    } else {
8296                        r.append(' ');
8297                    }
8298                    r.append(p.info.name);
8299                }
8300            }
8301            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8302                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8303                if (appOpPerms != null) {
8304                    appOpPerms.remove(pkg.packageName);
8305                }
8306            }
8307        }
8308        if (r != null) {
8309            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8310        }
8311
8312        N = pkg.requestedPermissions.size();
8313        r = null;
8314        for (i=0; i<N; i++) {
8315            String perm = pkg.requestedPermissions.get(i);
8316            BasePermission bp = mSettings.mPermissions.get(perm);
8317            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8318                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8319                if (appOpPerms != null) {
8320                    appOpPerms.remove(pkg.packageName);
8321                    if (appOpPerms.isEmpty()) {
8322                        mAppOpPermissionPackages.remove(perm);
8323                    }
8324                }
8325            }
8326        }
8327        if (r != null) {
8328            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8329        }
8330
8331        N = pkg.instrumentation.size();
8332        r = null;
8333        for (i=0; i<N; i++) {
8334            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8335            mInstrumentation.remove(a.getComponentName());
8336            if (DEBUG_REMOVE && chatty) {
8337                if (r == null) {
8338                    r = new StringBuilder(256);
8339                } else {
8340                    r.append(' ');
8341                }
8342                r.append(a.info.name);
8343            }
8344        }
8345        if (r != null) {
8346            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8347        }
8348
8349        r = null;
8350        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8351            // Only system apps can hold shared libraries.
8352            if (pkg.libraryNames != null) {
8353                for (i=0; i<pkg.libraryNames.size(); i++) {
8354                    String name = pkg.libraryNames.get(i);
8355                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8356                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8357                        mSharedLibraries.remove(name);
8358                        if (DEBUG_REMOVE && chatty) {
8359                            if (r == null) {
8360                                r = new StringBuilder(256);
8361                            } else {
8362                                r.append(' ');
8363                            }
8364                            r.append(name);
8365                        }
8366                    }
8367                }
8368            }
8369        }
8370        if (r != null) {
8371            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8372        }
8373    }
8374
8375    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8376        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8377            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8378                return true;
8379            }
8380        }
8381        return false;
8382    }
8383
8384    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8385    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8386    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8387
8388    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8389            int flags) {
8390        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8391        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8392    }
8393
8394    private void updatePermissionsLPw(String changingPkg,
8395            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8396        // Make sure there are no dangling permission trees.
8397        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8398        while (it.hasNext()) {
8399            final BasePermission bp = it.next();
8400            if (bp.packageSetting == null) {
8401                // We may not yet have parsed the package, so just see if
8402                // we still know about its settings.
8403                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8404            }
8405            if (bp.packageSetting == null) {
8406                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8407                        + " from package " + bp.sourcePackage);
8408                it.remove();
8409            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8410                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8411                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8412                            + " from package " + bp.sourcePackage);
8413                    flags |= UPDATE_PERMISSIONS_ALL;
8414                    it.remove();
8415                }
8416            }
8417        }
8418
8419        // Make sure all dynamic permissions have been assigned to a package,
8420        // and make sure there are no dangling permissions.
8421        it = mSettings.mPermissions.values().iterator();
8422        while (it.hasNext()) {
8423            final BasePermission bp = it.next();
8424            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8425                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8426                        + bp.name + " pkg=" + bp.sourcePackage
8427                        + " info=" + bp.pendingInfo);
8428                if (bp.packageSetting == null && bp.pendingInfo != null) {
8429                    final BasePermission tree = findPermissionTreeLP(bp.name);
8430                    if (tree != null && tree.perm != null) {
8431                        bp.packageSetting = tree.packageSetting;
8432                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8433                                new PermissionInfo(bp.pendingInfo));
8434                        bp.perm.info.packageName = tree.perm.info.packageName;
8435                        bp.perm.info.name = bp.name;
8436                        bp.uid = tree.uid;
8437                    }
8438                }
8439            }
8440            if (bp.packageSetting == null) {
8441                // We may not yet have parsed the package, so just see if
8442                // we still know about its settings.
8443                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8444            }
8445            if (bp.packageSetting == null) {
8446                Slog.w(TAG, "Removing dangling permission: " + bp.name
8447                        + " from package " + bp.sourcePackage);
8448                it.remove();
8449            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8450                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8451                    Slog.i(TAG, "Removing old permission: " + bp.name
8452                            + " from package " + bp.sourcePackage);
8453                    flags |= UPDATE_PERMISSIONS_ALL;
8454                    it.remove();
8455                }
8456            }
8457        }
8458
8459        // Now update the permissions for all packages, in particular
8460        // replace the granted permissions of the system packages.
8461        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8462            for (PackageParser.Package pkg : mPackages.values()) {
8463                if (pkg != pkgInfo) {
8464                    // Only replace for packages on requested volume
8465                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8466                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8467                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8468                    grantPermissionsLPw(pkg, replace, changingPkg);
8469                }
8470            }
8471        }
8472
8473        if (pkgInfo != null) {
8474            // Only replace for packages on requested volume
8475            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8476            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8477                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8478            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8479        }
8480    }
8481
8482    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8483            String packageOfInterest) {
8484        // IMPORTANT: There are two types of permissions: install and runtime.
8485        // Install time permissions are granted when the app is installed to
8486        // all device users and users added in the future. Runtime permissions
8487        // are granted at runtime explicitly to specific users. Normal and signature
8488        // protected permissions are install time permissions. Dangerous permissions
8489        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8490        // otherwise they are runtime permissions. This function does not manage
8491        // runtime permissions except for the case an app targeting Lollipop MR1
8492        // being upgraded to target a newer SDK, in which case dangerous permissions
8493        // are transformed from install time to runtime ones.
8494
8495        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8496        if (ps == null) {
8497            return;
8498        }
8499
8500        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8501
8502        PermissionsState permissionsState = ps.getPermissionsState();
8503        PermissionsState origPermissions = permissionsState;
8504
8505        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8506
8507        boolean runtimePermissionsRevoked = false;
8508        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8509
8510        boolean changedInstallPermission = false;
8511
8512        if (replace) {
8513            ps.installPermissionsFixed = false;
8514            if (!ps.isSharedUser()) {
8515                origPermissions = new PermissionsState(permissionsState);
8516                permissionsState.reset();
8517            } else {
8518                // We need to know only about runtime permission changes since the
8519                // calling code always writes the install permissions state but
8520                // the runtime ones are written only if changed. The only cases of
8521                // changed runtime permissions here are promotion of an install to
8522                // runtime and revocation of a runtime from a shared user.
8523                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8524                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8525                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8526                    runtimePermissionsRevoked = true;
8527                }
8528            }
8529        }
8530
8531        permissionsState.setGlobalGids(mGlobalGids);
8532
8533        final int N = pkg.requestedPermissions.size();
8534        for (int i=0; i<N; i++) {
8535            final String name = pkg.requestedPermissions.get(i);
8536            final BasePermission bp = mSettings.mPermissions.get(name);
8537
8538            if (DEBUG_INSTALL) {
8539                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8540            }
8541
8542            if (bp == null || bp.packageSetting == null) {
8543                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8544                    Slog.w(TAG, "Unknown permission " + name
8545                            + " in package " + pkg.packageName);
8546                }
8547                continue;
8548            }
8549
8550            final String perm = bp.name;
8551            boolean allowedSig = false;
8552            int grant = GRANT_DENIED;
8553
8554            // Keep track of app op permissions.
8555            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8556                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8557                if (pkgs == null) {
8558                    pkgs = new ArraySet<>();
8559                    mAppOpPermissionPackages.put(bp.name, pkgs);
8560                }
8561                pkgs.add(pkg.packageName);
8562            }
8563
8564            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8565            switch (level) {
8566                case PermissionInfo.PROTECTION_NORMAL: {
8567                    // For all apps normal permissions are install time ones.
8568                    grant = GRANT_INSTALL;
8569                } break;
8570
8571                case PermissionInfo.PROTECTION_DANGEROUS: {
8572                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8573                        // For legacy apps dangerous permissions are install time ones.
8574                        grant = GRANT_INSTALL_LEGACY;
8575                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8576                        // For legacy apps that became modern, install becomes runtime.
8577                        grant = GRANT_UPGRADE;
8578                    } else if (mPromoteSystemApps
8579                            && isSystemApp(ps)
8580                            && mExistingSystemPackages.contains(ps.name)) {
8581                        // For legacy system apps, install becomes runtime.
8582                        // We cannot check hasInstallPermission() for system apps since those
8583                        // permissions were granted implicitly and not persisted pre-M.
8584                        grant = GRANT_UPGRADE;
8585                    } else {
8586                        // For modern apps keep runtime permissions unchanged.
8587                        grant = GRANT_RUNTIME;
8588                    }
8589                } break;
8590
8591                case PermissionInfo.PROTECTION_SIGNATURE: {
8592                    // For all apps signature permissions are install time ones.
8593                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8594                    if (allowedSig) {
8595                        grant = GRANT_INSTALL;
8596                    }
8597                } break;
8598            }
8599
8600            if (DEBUG_INSTALL) {
8601                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8602            }
8603
8604            if (grant != GRANT_DENIED) {
8605                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8606                    // If this is an existing, non-system package, then
8607                    // we can't add any new permissions to it.
8608                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8609                        // Except...  if this is a permission that was added
8610                        // to the platform (note: need to only do this when
8611                        // updating the platform).
8612                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8613                            grant = GRANT_DENIED;
8614                        }
8615                    }
8616                }
8617
8618                switch (grant) {
8619                    case GRANT_INSTALL: {
8620                        // Revoke this as runtime permission to handle the case of
8621                        // a runtime permission being downgraded to an install one.
8622                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8623                            if (origPermissions.getRuntimePermissionState(
8624                                    bp.name, userId) != null) {
8625                                // Revoke the runtime permission and clear the flags.
8626                                origPermissions.revokeRuntimePermission(bp, userId);
8627                                origPermissions.updatePermissionFlags(bp, userId,
8628                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8629                                // If we revoked a permission permission, we have to write.
8630                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8631                                        changedRuntimePermissionUserIds, userId);
8632                            }
8633                        }
8634                        // Grant an install permission.
8635                        if (permissionsState.grantInstallPermission(bp) !=
8636                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8637                            changedInstallPermission = true;
8638                        }
8639                    } break;
8640
8641                    case GRANT_INSTALL_LEGACY: {
8642                        // Grant an install permission.
8643                        if (permissionsState.grantInstallPermission(bp) !=
8644                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8645                            changedInstallPermission = true;
8646                        }
8647                    } break;
8648
8649                    case GRANT_RUNTIME: {
8650                        // Grant previously granted runtime permissions.
8651                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8652                            PermissionState permissionState = origPermissions
8653                                    .getRuntimePermissionState(bp.name, userId);
8654                            final int flags = permissionState != null
8655                                    ? permissionState.getFlags() : 0;
8656                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8657                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8658                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8659                                    // If we cannot put the permission as it was, we have to write.
8660                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8661                                            changedRuntimePermissionUserIds, userId);
8662                                }
8663                            }
8664                            // Propagate the permission flags.
8665                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8666                        }
8667                    } break;
8668
8669                    case GRANT_UPGRADE: {
8670                        // Grant runtime permissions for a previously held install permission.
8671                        PermissionState permissionState = origPermissions
8672                                .getInstallPermissionState(bp.name);
8673                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8674
8675                        if (origPermissions.revokeInstallPermission(bp)
8676                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8677                            // We will be transferring the permission flags, so clear them.
8678                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8679                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8680                            changedInstallPermission = true;
8681                        }
8682
8683                        // If the permission is not to be promoted to runtime we ignore it and
8684                        // also its other flags as they are not applicable to install permissions.
8685                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8686                            for (int userId : currentUserIds) {
8687                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8688                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8689                                    // Transfer the permission flags.
8690                                    permissionsState.updatePermissionFlags(bp, userId,
8691                                            flags, flags);
8692                                    // If we granted the permission, we have to write.
8693                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8694                                            changedRuntimePermissionUserIds, userId);
8695                                }
8696                            }
8697                        }
8698                    } break;
8699
8700                    default: {
8701                        if (packageOfInterest == null
8702                                || packageOfInterest.equals(pkg.packageName)) {
8703                            Slog.w(TAG, "Not granting permission " + perm
8704                                    + " to package " + pkg.packageName
8705                                    + " because it was previously installed without");
8706                        }
8707                    } break;
8708                }
8709            } else {
8710                if (permissionsState.revokeInstallPermission(bp) !=
8711                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8712                    // Also drop the permission flags.
8713                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8714                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8715                    changedInstallPermission = true;
8716                    Slog.i(TAG, "Un-granting permission " + perm
8717                            + " from package " + pkg.packageName
8718                            + " (protectionLevel=" + bp.protectionLevel
8719                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8720                            + ")");
8721                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8722                    // Don't print warning for app op permissions, since it is fine for them
8723                    // not to be granted, there is a UI for the user to decide.
8724                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8725                        Slog.w(TAG, "Not granting permission " + perm
8726                                + " to package " + pkg.packageName
8727                                + " (protectionLevel=" + bp.protectionLevel
8728                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8729                                + ")");
8730                    }
8731                }
8732            }
8733        }
8734
8735        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8736                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8737            // This is the first that we have heard about this package, so the
8738            // permissions we have now selected are fixed until explicitly
8739            // changed.
8740            ps.installPermissionsFixed = true;
8741        }
8742
8743        // Persist the runtime permissions state for users with changes. If permissions
8744        // were revoked because no app in the shared user declares them we have to
8745        // write synchronously to avoid losing runtime permissions state.
8746        for (int userId : changedRuntimePermissionUserIds) {
8747            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8748        }
8749
8750        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8751    }
8752
8753    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8754        boolean allowed = false;
8755        final int NP = PackageParser.NEW_PERMISSIONS.length;
8756        for (int ip=0; ip<NP; ip++) {
8757            final PackageParser.NewPermissionInfo npi
8758                    = PackageParser.NEW_PERMISSIONS[ip];
8759            if (npi.name.equals(perm)
8760                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8761                allowed = true;
8762                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8763                        + pkg.packageName);
8764                break;
8765            }
8766        }
8767        return allowed;
8768    }
8769
8770    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8771            BasePermission bp, PermissionsState origPermissions) {
8772        boolean allowed;
8773        allowed = (compareSignatures(
8774                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8775                        == PackageManager.SIGNATURE_MATCH)
8776                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8777                        == PackageManager.SIGNATURE_MATCH);
8778        if (!allowed && (bp.protectionLevel
8779                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8780            if (isSystemApp(pkg)) {
8781                // For updated system applications, a system permission
8782                // is granted only if it had been defined by the original application.
8783                if (pkg.isUpdatedSystemApp()) {
8784                    final PackageSetting sysPs = mSettings
8785                            .getDisabledSystemPkgLPr(pkg.packageName);
8786                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8787                        // If the original was granted this permission, we take
8788                        // that grant decision as read and propagate it to the
8789                        // update.
8790                        if (sysPs.isPrivileged()) {
8791                            allowed = true;
8792                        }
8793                    } else {
8794                        // The system apk may have been updated with an older
8795                        // version of the one on the data partition, but which
8796                        // granted a new system permission that it didn't have
8797                        // before.  In this case we do want to allow the app to
8798                        // now get the new permission if the ancestral apk is
8799                        // privileged to get it.
8800                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8801                            for (int j=0;
8802                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8803                                if (perm.equals(
8804                                        sysPs.pkg.requestedPermissions.get(j))) {
8805                                    allowed = true;
8806                                    break;
8807                                }
8808                            }
8809                        }
8810                    }
8811                } else {
8812                    allowed = isPrivilegedApp(pkg);
8813                }
8814            }
8815        }
8816        if (!allowed) {
8817            if (!allowed && (bp.protectionLevel
8818                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8819                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8820                // If this was a previously normal/dangerous permission that got moved
8821                // to a system permission as part of the runtime permission redesign, then
8822                // we still want to blindly grant it to old apps.
8823                allowed = true;
8824            }
8825            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8826                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8827                // If this permission is to be granted to the system installer and
8828                // this app is an installer, then it gets the permission.
8829                allowed = true;
8830            }
8831            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8832                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8833                // If this permission is to be granted to the system verifier and
8834                // this app is a verifier, then it gets the permission.
8835                allowed = true;
8836            }
8837            if (!allowed && (bp.protectionLevel
8838                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8839                    && isSystemApp(pkg)) {
8840                // Any pre-installed system app is allowed to get this permission.
8841                allowed = true;
8842            }
8843            if (!allowed && (bp.protectionLevel
8844                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8845                // For development permissions, a development permission
8846                // is granted only if it was already granted.
8847                allowed = origPermissions.hasInstallPermission(perm);
8848            }
8849        }
8850        return allowed;
8851    }
8852
8853    final class ActivityIntentResolver
8854            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8855        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8856                boolean defaultOnly, int userId) {
8857            if (!sUserManager.exists(userId)) return null;
8858            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8859            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8860        }
8861
8862        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8863                int userId) {
8864            if (!sUserManager.exists(userId)) return null;
8865            mFlags = flags;
8866            return super.queryIntent(intent, resolvedType,
8867                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8868        }
8869
8870        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8871                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8872            if (!sUserManager.exists(userId)) return null;
8873            if (packageActivities == null) {
8874                return null;
8875            }
8876            mFlags = flags;
8877            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8878            final int N = packageActivities.size();
8879            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8880                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8881
8882            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8883            for (int i = 0; i < N; ++i) {
8884                intentFilters = packageActivities.get(i).intents;
8885                if (intentFilters != null && intentFilters.size() > 0) {
8886                    PackageParser.ActivityIntentInfo[] array =
8887                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8888                    intentFilters.toArray(array);
8889                    listCut.add(array);
8890                }
8891            }
8892            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8893        }
8894
8895        public final void addActivity(PackageParser.Activity a, String type) {
8896            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8897            mActivities.put(a.getComponentName(), a);
8898            if (DEBUG_SHOW_INFO)
8899                Log.v(
8900                TAG, "  " + type + " " +
8901                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8902            if (DEBUG_SHOW_INFO)
8903                Log.v(TAG, "    Class=" + a.info.name);
8904            final int NI = a.intents.size();
8905            for (int j=0; j<NI; j++) {
8906                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8907                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8908                    intent.setPriority(0);
8909                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8910                            + a.className + " with priority > 0, forcing to 0");
8911                }
8912                if (DEBUG_SHOW_INFO) {
8913                    Log.v(TAG, "    IntentFilter:");
8914                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8915                }
8916                if (!intent.debugCheck()) {
8917                    Log.w(TAG, "==> For Activity " + a.info.name);
8918                }
8919                addFilter(intent);
8920            }
8921        }
8922
8923        public final void removeActivity(PackageParser.Activity a, String type) {
8924            mActivities.remove(a.getComponentName());
8925            if (DEBUG_SHOW_INFO) {
8926                Log.v(TAG, "  " + type + " "
8927                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8928                                : a.info.name) + ":");
8929                Log.v(TAG, "    Class=" + a.info.name);
8930            }
8931            final int NI = a.intents.size();
8932            for (int j=0; j<NI; j++) {
8933                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8934                if (DEBUG_SHOW_INFO) {
8935                    Log.v(TAG, "    IntentFilter:");
8936                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8937                }
8938                removeFilter(intent);
8939            }
8940        }
8941
8942        @Override
8943        protected boolean allowFilterResult(
8944                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8945            ActivityInfo filterAi = filter.activity.info;
8946            for (int i=dest.size()-1; i>=0; i--) {
8947                ActivityInfo destAi = dest.get(i).activityInfo;
8948                if (destAi.name == filterAi.name
8949                        && destAi.packageName == filterAi.packageName) {
8950                    return false;
8951                }
8952            }
8953            return true;
8954        }
8955
8956        @Override
8957        protected ActivityIntentInfo[] newArray(int size) {
8958            return new ActivityIntentInfo[size];
8959        }
8960
8961        @Override
8962        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8963            if (!sUserManager.exists(userId)) return true;
8964            PackageParser.Package p = filter.activity.owner;
8965            if (p != null) {
8966                PackageSetting ps = (PackageSetting)p.mExtras;
8967                if (ps != null) {
8968                    // System apps are never considered stopped for purposes of
8969                    // filtering, because there may be no way for the user to
8970                    // actually re-launch them.
8971                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8972                            && ps.getStopped(userId);
8973                }
8974            }
8975            return false;
8976        }
8977
8978        @Override
8979        protected boolean isPackageForFilter(String packageName,
8980                PackageParser.ActivityIntentInfo info) {
8981            return packageName.equals(info.activity.owner.packageName);
8982        }
8983
8984        @Override
8985        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8986                int match, int userId) {
8987            if (!sUserManager.exists(userId)) return null;
8988            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8989                return null;
8990            }
8991            final PackageParser.Activity activity = info.activity;
8992            if (mSafeMode && (activity.info.applicationInfo.flags
8993                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8994                return null;
8995            }
8996            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8997            if (ps == null) {
8998                return null;
8999            }
9000            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9001                    ps.readUserState(userId), userId);
9002            if (ai == null) {
9003                return null;
9004            }
9005            final ResolveInfo res = new ResolveInfo();
9006            res.activityInfo = ai;
9007            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9008                res.filter = info;
9009            }
9010            if (info != null) {
9011                res.handleAllWebDataURI = info.handleAllWebDataURI();
9012            }
9013            res.priority = info.getPriority();
9014            res.preferredOrder = activity.owner.mPreferredOrder;
9015            //System.out.println("Result: " + res.activityInfo.className +
9016            //                   " = " + res.priority);
9017            res.match = match;
9018            res.isDefault = info.hasDefault;
9019            res.labelRes = info.labelRes;
9020            res.nonLocalizedLabel = info.nonLocalizedLabel;
9021            if (userNeedsBadging(userId)) {
9022                res.noResourceId = true;
9023            } else {
9024                res.icon = info.icon;
9025            }
9026            res.iconResourceId = info.icon;
9027            res.system = res.activityInfo.applicationInfo.isSystemApp();
9028            return res;
9029        }
9030
9031        @Override
9032        protected void sortResults(List<ResolveInfo> results) {
9033            Collections.sort(results, mResolvePrioritySorter);
9034        }
9035
9036        @Override
9037        protected void dumpFilter(PrintWriter out, String prefix,
9038                PackageParser.ActivityIntentInfo filter) {
9039            out.print(prefix); out.print(
9040                    Integer.toHexString(System.identityHashCode(filter.activity)));
9041                    out.print(' ');
9042                    filter.activity.printComponentShortName(out);
9043                    out.print(" filter ");
9044                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9045        }
9046
9047        @Override
9048        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9049            return filter.activity;
9050        }
9051
9052        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9053            PackageParser.Activity activity = (PackageParser.Activity)label;
9054            out.print(prefix); out.print(
9055                    Integer.toHexString(System.identityHashCode(activity)));
9056                    out.print(' ');
9057                    activity.printComponentShortName(out);
9058            if (count > 1) {
9059                out.print(" ("); out.print(count); out.print(" filters)");
9060            }
9061            out.println();
9062        }
9063
9064//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9065//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9066//            final List<ResolveInfo> retList = Lists.newArrayList();
9067//            while (i.hasNext()) {
9068//                final ResolveInfo resolveInfo = i.next();
9069//                if (isEnabledLP(resolveInfo.activityInfo)) {
9070//                    retList.add(resolveInfo);
9071//                }
9072//            }
9073//            return retList;
9074//        }
9075
9076        // Keys are String (activity class name), values are Activity.
9077        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9078                = new ArrayMap<ComponentName, PackageParser.Activity>();
9079        private int mFlags;
9080    }
9081
9082    private final class ServiceIntentResolver
9083            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9084        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9085                boolean defaultOnly, int userId) {
9086            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9087            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9088        }
9089
9090        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9091                int userId) {
9092            if (!sUserManager.exists(userId)) return null;
9093            mFlags = flags;
9094            return super.queryIntent(intent, resolvedType,
9095                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9096        }
9097
9098        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9099                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9100            if (!sUserManager.exists(userId)) return null;
9101            if (packageServices == null) {
9102                return null;
9103            }
9104            mFlags = flags;
9105            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9106            final int N = packageServices.size();
9107            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9108                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9109
9110            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9111            for (int i = 0; i < N; ++i) {
9112                intentFilters = packageServices.get(i).intents;
9113                if (intentFilters != null && intentFilters.size() > 0) {
9114                    PackageParser.ServiceIntentInfo[] array =
9115                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9116                    intentFilters.toArray(array);
9117                    listCut.add(array);
9118                }
9119            }
9120            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9121        }
9122
9123        public final void addService(PackageParser.Service s) {
9124            mServices.put(s.getComponentName(), s);
9125            if (DEBUG_SHOW_INFO) {
9126                Log.v(TAG, "  "
9127                        + (s.info.nonLocalizedLabel != null
9128                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9129                Log.v(TAG, "    Class=" + s.info.name);
9130            }
9131            final int NI = s.intents.size();
9132            int j;
9133            for (j=0; j<NI; j++) {
9134                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9135                if (DEBUG_SHOW_INFO) {
9136                    Log.v(TAG, "    IntentFilter:");
9137                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9138                }
9139                if (!intent.debugCheck()) {
9140                    Log.w(TAG, "==> For Service " + s.info.name);
9141                }
9142                addFilter(intent);
9143            }
9144        }
9145
9146        public final void removeService(PackageParser.Service s) {
9147            mServices.remove(s.getComponentName());
9148            if (DEBUG_SHOW_INFO) {
9149                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9150                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9151                Log.v(TAG, "    Class=" + s.info.name);
9152            }
9153            final int NI = s.intents.size();
9154            int j;
9155            for (j=0; j<NI; j++) {
9156                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9157                if (DEBUG_SHOW_INFO) {
9158                    Log.v(TAG, "    IntentFilter:");
9159                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9160                }
9161                removeFilter(intent);
9162            }
9163        }
9164
9165        @Override
9166        protected boolean allowFilterResult(
9167                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9168            ServiceInfo filterSi = filter.service.info;
9169            for (int i=dest.size()-1; i>=0; i--) {
9170                ServiceInfo destAi = dest.get(i).serviceInfo;
9171                if (destAi.name == filterSi.name
9172                        && destAi.packageName == filterSi.packageName) {
9173                    return false;
9174                }
9175            }
9176            return true;
9177        }
9178
9179        @Override
9180        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9181            return new PackageParser.ServiceIntentInfo[size];
9182        }
9183
9184        @Override
9185        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9186            if (!sUserManager.exists(userId)) return true;
9187            PackageParser.Package p = filter.service.owner;
9188            if (p != null) {
9189                PackageSetting ps = (PackageSetting)p.mExtras;
9190                if (ps != null) {
9191                    // System apps are never considered stopped for purposes of
9192                    // filtering, because there may be no way for the user to
9193                    // actually re-launch them.
9194                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9195                            && ps.getStopped(userId);
9196                }
9197            }
9198            return false;
9199        }
9200
9201        @Override
9202        protected boolean isPackageForFilter(String packageName,
9203                PackageParser.ServiceIntentInfo info) {
9204            return packageName.equals(info.service.owner.packageName);
9205        }
9206
9207        @Override
9208        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9209                int match, int userId) {
9210            if (!sUserManager.exists(userId)) return null;
9211            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9212            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
9213                return null;
9214            }
9215            final PackageParser.Service service = info.service;
9216            if (mSafeMode && (service.info.applicationInfo.flags
9217                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9218                return null;
9219            }
9220            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9221            if (ps == null) {
9222                return null;
9223            }
9224            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9225                    ps.readUserState(userId), userId);
9226            if (si == null) {
9227                return null;
9228            }
9229            final ResolveInfo res = new ResolveInfo();
9230            res.serviceInfo = si;
9231            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9232                res.filter = filter;
9233            }
9234            res.priority = info.getPriority();
9235            res.preferredOrder = service.owner.mPreferredOrder;
9236            res.match = match;
9237            res.isDefault = info.hasDefault;
9238            res.labelRes = info.labelRes;
9239            res.nonLocalizedLabel = info.nonLocalizedLabel;
9240            res.icon = info.icon;
9241            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9242            return res;
9243        }
9244
9245        @Override
9246        protected void sortResults(List<ResolveInfo> results) {
9247            Collections.sort(results, mResolvePrioritySorter);
9248        }
9249
9250        @Override
9251        protected void dumpFilter(PrintWriter out, String prefix,
9252                PackageParser.ServiceIntentInfo filter) {
9253            out.print(prefix); out.print(
9254                    Integer.toHexString(System.identityHashCode(filter.service)));
9255                    out.print(' ');
9256                    filter.service.printComponentShortName(out);
9257                    out.print(" filter ");
9258                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9259        }
9260
9261        @Override
9262        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9263            return filter.service;
9264        }
9265
9266        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9267            PackageParser.Service service = (PackageParser.Service)label;
9268            out.print(prefix); out.print(
9269                    Integer.toHexString(System.identityHashCode(service)));
9270                    out.print(' ');
9271                    service.printComponentShortName(out);
9272            if (count > 1) {
9273                out.print(" ("); out.print(count); out.print(" filters)");
9274            }
9275            out.println();
9276        }
9277
9278//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9279//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9280//            final List<ResolveInfo> retList = Lists.newArrayList();
9281//            while (i.hasNext()) {
9282//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9283//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9284//                    retList.add(resolveInfo);
9285//                }
9286//            }
9287//            return retList;
9288//        }
9289
9290        // Keys are String (activity class name), values are Activity.
9291        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9292                = new ArrayMap<ComponentName, PackageParser.Service>();
9293        private int mFlags;
9294    };
9295
9296    private final class ProviderIntentResolver
9297            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9298        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9299                boolean defaultOnly, int userId) {
9300            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9301            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9302        }
9303
9304        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9305                int userId) {
9306            if (!sUserManager.exists(userId))
9307                return null;
9308            mFlags = flags;
9309            return super.queryIntent(intent, resolvedType,
9310                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9311        }
9312
9313        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9314                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9315            if (!sUserManager.exists(userId))
9316                return null;
9317            if (packageProviders == null) {
9318                return null;
9319            }
9320            mFlags = flags;
9321            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9322            final int N = packageProviders.size();
9323            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9324                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9325
9326            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9327            for (int i = 0; i < N; ++i) {
9328                intentFilters = packageProviders.get(i).intents;
9329                if (intentFilters != null && intentFilters.size() > 0) {
9330                    PackageParser.ProviderIntentInfo[] array =
9331                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9332                    intentFilters.toArray(array);
9333                    listCut.add(array);
9334                }
9335            }
9336            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9337        }
9338
9339        public final void addProvider(PackageParser.Provider p) {
9340            if (mProviders.containsKey(p.getComponentName())) {
9341                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9342                return;
9343            }
9344
9345            mProviders.put(p.getComponentName(), p);
9346            if (DEBUG_SHOW_INFO) {
9347                Log.v(TAG, "  "
9348                        + (p.info.nonLocalizedLabel != null
9349                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9350                Log.v(TAG, "    Class=" + p.info.name);
9351            }
9352            final int NI = p.intents.size();
9353            int j;
9354            for (j = 0; j < NI; j++) {
9355                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9356                if (DEBUG_SHOW_INFO) {
9357                    Log.v(TAG, "    IntentFilter:");
9358                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9359                }
9360                if (!intent.debugCheck()) {
9361                    Log.w(TAG, "==> For Provider " + p.info.name);
9362                }
9363                addFilter(intent);
9364            }
9365        }
9366
9367        public final void removeProvider(PackageParser.Provider p) {
9368            mProviders.remove(p.getComponentName());
9369            if (DEBUG_SHOW_INFO) {
9370                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9371                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9372                Log.v(TAG, "    Class=" + p.info.name);
9373            }
9374            final int NI = p.intents.size();
9375            int j;
9376            for (j = 0; j < NI; j++) {
9377                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9378                if (DEBUG_SHOW_INFO) {
9379                    Log.v(TAG, "    IntentFilter:");
9380                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9381                }
9382                removeFilter(intent);
9383            }
9384        }
9385
9386        @Override
9387        protected boolean allowFilterResult(
9388                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9389            ProviderInfo filterPi = filter.provider.info;
9390            for (int i = dest.size() - 1; i >= 0; i--) {
9391                ProviderInfo destPi = dest.get(i).providerInfo;
9392                if (destPi.name == filterPi.name
9393                        && destPi.packageName == filterPi.packageName) {
9394                    return false;
9395                }
9396            }
9397            return true;
9398        }
9399
9400        @Override
9401        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9402            return new PackageParser.ProviderIntentInfo[size];
9403        }
9404
9405        @Override
9406        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9407            if (!sUserManager.exists(userId))
9408                return true;
9409            PackageParser.Package p = filter.provider.owner;
9410            if (p != null) {
9411                PackageSetting ps = (PackageSetting) p.mExtras;
9412                if (ps != null) {
9413                    // System apps are never considered stopped for purposes of
9414                    // filtering, because there may be no way for the user to
9415                    // actually re-launch them.
9416                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9417                            && ps.getStopped(userId);
9418                }
9419            }
9420            return false;
9421        }
9422
9423        @Override
9424        protected boolean isPackageForFilter(String packageName,
9425                PackageParser.ProviderIntentInfo info) {
9426            return packageName.equals(info.provider.owner.packageName);
9427        }
9428
9429        @Override
9430        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9431                int match, int userId) {
9432            if (!sUserManager.exists(userId))
9433                return null;
9434            final PackageParser.ProviderIntentInfo info = filter;
9435            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9436                return null;
9437            }
9438            final PackageParser.Provider provider = info.provider;
9439            if (mSafeMode && (provider.info.applicationInfo.flags
9440                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9441                return null;
9442            }
9443            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9444            if (ps == null) {
9445                return null;
9446            }
9447            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9448                    ps.readUserState(userId), userId);
9449            if (pi == null) {
9450                return null;
9451            }
9452            final ResolveInfo res = new ResolveInfo();
9453            res.providerInfo = pi;
9454            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9455                res.filter = filter;
9456            }
9457            res.priority = info.getPriority();
9458            res.preferredOrder = provider.owner.mPreferredOrder;
9459            res.match = match;
9460            res.isDefault = info.hasDefault;
9461            res.labelRes = info.labelRes;
9462            res.nonLocalizedLabel = info.nonLocalizedLabel;
9463            res.icon = info.icon;
9464            res.system = res.providerInfo.applicationInfo.isSystemApp();
9465            return res;
9466        }
9467
9468        @Override
9469        protected void sortResults(List<ResolveInfo> results) {
9470            Collections.sort(results, mResolvePrioritySorter);
9471        }
9472
9473        @Override
9474        protected void dumpFilter(PrintWriter out, String prefix,
9475                PackageParser.ProviderIntentInfo filter) {
9476            out.print(prefix);
9477            out.print(
9478                    Integer.toHexString(System.identityHashCode(filter.provider)));
9479            out.print(' ');
9480            filter.provider.printComponentShortName(out);
9481            out.print(" filter ");
9482            out.println(Integer.toHexString(System.identityHashCode(filter)));
9483        }
9484
9485        @Override
9486        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9487            return filter.provider;
9488        }
9489
9490        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9491            PackageParser.Provider provider = (PackageParser.Provider)label;
9492            out.print(prefix); out.print(
9493                    Integer.toHexString(System.identityHashCode(provider)));
9494                    out.print(' ');
9495                    provider.printComponentShortName(out);
9496            if (count > 1) {
9497                out.print(" ("); out.print(count); out.print(" filters)");
9498            }
9499            out.println();
9500        }
9501
9502        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9503                = new ArrayMap<ComponentName, PackageParser.Provider>();
9504        private int mFlags;
9505    };
9506
9507    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9508            new Comparator<ResolveInfo>() {
9509        public int compare(ResolveInfo r1, ResolveInfo r2) {
9510            int v1 = r1.priority;
9511            int v2 = r2.priority;
9512            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9513            if (v1 != v2) {
9514                return (v1 > v2) ? -1 : 1;
9515            }
9516            v1 = r1.preferredOrder;
9517            v2 = r2.preferredOrder;
9518            if (v1 != v2) {
9519                return (v1 > v2) ? -1 : 1;
9520            }
9521            if (r1.isDefault != r2.isDefault) {
9522                return r1.isDefault ? -1 : 1;
9523            }
9524            v1 = r1.match;
9525            v2 = r2.match;
9526            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9527            if (v1 != v2) {
9528                return (v1 > v2) ? -1 : 1;
9529            }
9530            if (r1.system != r2.system) {
9531                return r1.system ? -1 : 1;
9532            }
9533            return 0;
9534        }
9535    };
9536
9537    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9538            new Comparator<ProviderInfo>() {
9539        public int compare(ProviderInfo p1, ProviderInfo p2) {
9540            final int v1 = p1.initOrder;
9541            final int v2 = p2.initOrder;
9542            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9543        }
9544    };
9545
9546    final void sendPackageBroadcast(final String action, final String pkg,
9547            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9548            final int[] userIds) {
9549        mHandler.post(new Runnable() {
9550            @Override
9551            public void run() {
9552                try {
9553                    final IActivityManager am = ActivityManagerNative.getDefault();
9554                    if (am == null) return;
9555                    final int[] resolvedUserIds;
9556                    if (userIds == null) {
9557                        resolvedUserIds = am.getRunningUserIds();
9558                    } else {
9559                        resolvedUserIds = userIds;
9560                    }
9561                    for (int id : resolvedUserIds) {
9562                        final Intent intent = new Intent(action,
9563                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9564                        if (extras != null) {
9565                            intent.putExtras(extras);
9566                        }
9567                        if (targetPkg != null) {
9568                            intent.setPackage(targetPkg);
9569                        }
9570                        // Modify the UID when posting to other users
9571                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9572                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9573                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9574                            intent.putExtra(Intent.EXTRA_UID, uid);
9575                        }
9576                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9577                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9578                        if (DEBUG_BROADCASTS) {
9579                            RuntimeException here = new RuntimeException("here");
9580                            here.fillInStackTrace();
9581                            Slog.d(TAG, "Sending to user " + id + ": "
9582                                    + intent.toShortString(false, true, false, false)
9583                                    + " " + intent.getExtras(), here);
9584                        }
9585                        am.broadcastIntent(null, intent, null, finishedReceiver,
9586                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9587                                null, finishedReceiver != null, false, id);
9588                    }
9589                } catch (RemoteException ex) {
9590                }
9591            }
9592        });
9593    }
9594
9595    /**
9596     * Check if the external storage media is available. This is true if there
9597     * is a mounted external storage medium or if the external storage is
9598     * emulated.
9599     */
9600    private boolean isExternalMediaAvailable() {
9601        return mMediaMounted || Environment.isExternalStorageEmulated();
9602    }
9603
9604    @Override
9605    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9606        // writer
9607        synchronized (mPackages) {
9608            if (!isExternalMediaAvailable()) {
9609                // If the external storage is no longer mounted at this point,
9610                // the caller may not have been able to delete all of this
9611                // packages files and can not delete any more.  Bail.
9612                return null;
9613            }
9614            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9615            if (lastPackage != null) {
9616                pkgs.remove(lastPackage);
9617            }
9618            if (pkgs.size() > 0) {
9619                return pkgs.get(0);
9620            }
9621        }
9622        return null;
9623    }
9624
9625    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9626        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9627                userId, andCode ? 1 : 0, packageName);
9628        if (mSystemReady) {
9629            msg.sendToTarget();
9630        } else {
9631            if (mPostSystemReadyMessages == null) {
9632                mPostSystemReadyMessages = new ArrayList<>();
9633            }
9634            mPostSystemReadyMessages.add(msg);
9635        }
9636    }
9637
9638    void startCleaningPackages() {
9639        // reader
9640        synchronized (mPackages) {
9641            if (!isExternalMediaAvailable()) {
9642                return;
9643            }
9644            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9645                return;
9646            }
9647        }
9648        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9649        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9650        IActivityManager am = ActivityManagerNative.getDefault();
9651        if (am != null) {
9652            try {
9653                am.startService(null, intent, null, mContext.getOpPackageName(),
9654                        UserHandle.USER_SYSTEM);
9655            } catch (RemoteException e) {
9656            }
9657        }
9658    }
9659
9660    @Override
9661    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9662            int installFlags, String installerPackageName, VerificationParams verificationParams,
9663            String packageAbiOverride) {
9664        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9665                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9666    }
9667
9668    @Override
9669    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9670            int installFlags, String installerPackageName, VerificationParams verificationParams,
9671            String packageAbiOverride, int userId) {
9672        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9673
9674        final int callingUid = Binder.getCallingUid();
9675        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9676
9677        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9678            try {
9679                if (observer != null) {
9680                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9681                }
9682            } catch (RemoteException re) {
9683            }
9684            return;
9685        }
9686
9687        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9688            installFlags |= PackageManager.INSTALL_FROM_ADB;
9689
9690        } else {
9691            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9692            // about installerPackageName.
9693
9694            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9695            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9696        }
9697
9698        UserHandle user;
9699        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9700            user = UserHandle.ALL;
9701        } else {
9702            user = new UserHandle(userId);
9703        }
9704
9705        // Only system components can circumvent runtime permissions when installing.
9706        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9707                && mContext.checkCallingOrSelfPermission(Manifest.permission
9708                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9709            throw new SecurityException("You need the "
9710                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9711                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9712        }
9713
9714        verificationParams.setInstallerUid(callingUid);
9715
9716        final File originFile = new File(originPath);
9717        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9718
9719        final Message msg = mHandler.obtainMessage(INIT_COPY);
9720        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9721                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9722        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
9723        msg.obj = params;
9724
9725        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
9726                System.identityHashCode(msg.obj));
9727        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9728                System.identityHashCode(msg.obj));
9729
9730        mHandler.sendMessage(msg);
9731    }
9732
9733    void installStage(String packageName, File stagedDir, String stagedCid,
9734            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
9735            String installerPackageName, int installerUid, UserHandle user) {
9736        final VerificationParams verifParams = new VerificationParams(
9737                null, sessionParams.originatingUri, sessionParams.referrerUri,
9738                sessionParams.originatingUid, null);
9739        verifParams.setInstallerUid(installerUid);
9740
9741        final OriginInfo origin;
9742        if (stagedDir != null) {
9743            origin = OriginInfo.fromStagedFile(stagedDir);
9744        } else {
9745            origin = OriginInfo.fromStagedContainer(stagedCid);
9746        }
9747
9748        final Message msg = mHandler.obtainMessage(INIT_COPY);
9749        final InstallParams params = new InstallParams(origin, null, observer,
9750                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
9751                verifParams, user, sessionParams.abiOverride,
9752                sessionParams.grantedRuntimePermissions);
9753        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
9754        msg.obj = params;
9755
9756        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
9757                System.identityHashCode(msg.obj));
9758        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9759                System.identityHashCode(msg.obj));
9760
9761        mHandler.sendMessage(msg);
9762    }
9763
9764    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9765        Bundle extras = new Bundle(1);
9766        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9767
9768        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9769                packageName, extras, null, null, new int[] {userId});
9770        try {
9771            IActivityManager am = ActivityManagerNative.getDefault();
9772            final boolean isSystem =
9773                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9774            if (isSystem && am.isUserRunning(userId, false)) {
9775                // The just-installed/enabled app is bundled on the system, so presumed
9776                // to be able to run automatically without needing an explicit launch.
9777                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9778                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9779                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9780                        .setPackage(packageName);
9781                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9782                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9783            }
9784        } catch (RemoteException e) {
9785            // shouldn't happen
9786            Slog.w(TAG, "Unable to bootstrap installed package", e);
9787        }
9788    }
9789
9790    @Override
9791    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9792            int userId) {
9793        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9794        PackageSetting pkgSetting;
9795        final int uid = Binder.getCallingUid();
9796        enforceCrossUserPermission(uid, userId, true, true,
9797                "setApplicationHiddenSetting for user " + userId);
9798
9799        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9800            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9801            return false;
9802        }
9803
9804        long callingId = Binder.clearCallingIdentity();
9805        try {
9806            boolean sendAdded = false;
9807            boolean sendRemoved = false;
9808            // writer
9809            synchronized (mPackages) {
9810                pkgSetting = mSettings.mPackages.get(packageName);
9811                if (pkgSetting == null) {
9812                    return false;
9813                }
9814                if (pkgSetting.getHidden(userId) != hidden) {
9815                    pkgSetting.setHidden(hidden, userId);
9816                    mSettings.writePackageRestrictionsLPr(userId);
9817                    if (hidden) {
9818                        sendRemoved = true;
9819                    } else {
9820                        sendAdded = true;
9821                    }
9822                }
9823            }
9824            if (sendAdded) {
9825                sendPackageAddedForUser(packageName, pkgSetting, userId);
9826                return true;
9827            }
9828            if (sendRemoved) {
9829                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9830                        "hiding pkg");
9831                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9832                return true;
9833            }
9834        } finally {
9835            Binder.restoreCallingIdentity(callingId);
9836        }
9837        return false;
9838    }
9839
9840    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9841            int userId) {
9842        final PackageRemovedInfo info = new PackageRemovedInfo();
9843        info.removedPackage = packageName;
9844        info.removedUsers = new int[] {userId};
9845        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9846        info.sendBroadcast(false, false, false);
9847    }
9848
9849    /**
9850     * Returns true if application is not found or there was an error. Otherwise it returns
9851     * the hidden state of the package for the given user.
9852     */
9853    @Override
9854    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9855        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9856        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9857                false, "getApplicationHidden for user " + userId);
9858        PackageSetting pkgSetting;
9859        long callingId = Binder.clearCallingIdentity();
9860        try {
9861            // writer
9862            synchronized (mPackages) {
9863                pkgSetting = mSettings.mPackages.get(packageName);
9864                if (pkgSetting == null) {
9865                    return true;
9866                }
9867                return pkgSetting.getHidden(userId);
9868            }
9869        } finally {
9870            Binder.restoreCallingIdentity(callingId);
9871        }
9872    }
9873
9874    /**
9875     * @hide
9876     */
9877    @Override
9878    public int installExistingPackageAsUser(String packageName, int userId) {
9879        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9880                null);
9881        PackageSetting pkgSetting;
9882        final int uid = Binder.getCallingUid();
9883        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9884                + userId);
9885        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9886            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9887        }
9888
9889        long callingId = Binder.clearCallingIdentity();
9890        try {
9891            boolean sendAdded = false;
9892
9893            // writer
9894            synchronized (mPackages) {
9895                pkgSetting = mSettings.mPackages.get(packageName);
9896                if (pkgSetting == null) {
9897                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9898                }
9899                if (!pkgSetting.getInstalled(userId)) {
9900                    pkgSetting.setInstalled(true, userId);
9901                    pkgSetting.setHidden(false, userId);
9902                    mSettings.writePackageRestrictionsLPr(userId);
9903                    sendAdded = true;
9904                }
9905            }
9906
9907            if (sendAdded) {
9908                sendPackageAddedForUser(packageName, pkgSetting, userId);
9909            }
9910        } finally {
9911            Binder.restoreCallingIdentity(callingId);
9912        }
9913
9914        return PackageManager.INSTALL_SUCCEEDED;
9915    }
9916
9917    boolean isUserRestricted(int userId, String restrictionKey) {
9918        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9919        if (restrictions.getBoolean(restrictionKey, false)) {
9920            Log.w(TAG, "User is restricted: " + restrictionKey);
9921            return true;
9922        }
9923        return false;
9924    }
9925
9926    @Override
9927    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9928        mContext.enforceCallingOrSelfPermission(
9929                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9930                "Only package verification agents can verify applications");
9931
9932        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9933        final PackageVerificationResponse response = new PackageVerificationResponse(
9934                verificationCode, Binder.getCallingUid());
9935        msg.arg1 = id;
9936        msg.obj = response;
9937        mHandler.sendMessage(msg);
9938    }
9939
9940    @Override
9941    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9942            long millisecondsToDelay) {
9943        mContext.enforceCallingOrSelfPermission(
9944                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9945                "Only package verification agents can extend verification timeouts");
9946
9947        final PackageVerificationState state = mPendingVerification.get(id);
9948        final PackageVerificationResponse response = new PackageVerificationResponse(
9949                verificationCodeAtTimeout, Binder.getCallingUid());
9950
9951        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9952            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9953        }
9954        if (millisecondsToDelay < 0) {
9955            millisecondsToDelay = 0;
9956        }
9957        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9958                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9959            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9960        }
9961
9962        if ((state != null) && !state.timeoutExtended()) {
9963            state.extendTimeout();
9964
9965            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9966            msg.arg1 = id;
9967            msg.obj = response;
9968            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9969        }
9970    }
9971
9972    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9973            int verificationCode, UserHandle user) {
9974        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9975        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9976        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9977        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9978        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9979
9980        mContext.sendBroadcastAsUser(intent, user,
9981                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9982    }
9983
9984    private ComponentName matchComponentForVerifier(String packageName,
9985            List<ResolveInfo> receivers) {
9986        ActivityInfo targetReceiver = null;
9987
9988        final int NR = receivers.size();
9989        for (int i = 0; i < NR; i++) {
9990            final ResolveInfo info = receivers.get(i);
9991            if (info.activityInfo == null) {
9992                continue;
9993            }
9994
9995            if (packageName.equals(info.activityInfo.packageName)) {
9996                targetReceiver = info.activityInfo;
9997                break;
9998            }
9999        }
10000
10001        if (targetReceiver == null) {
10002            return null;
10003        }
10004
10005        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10006    }
10007
10008    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10009            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10010        if (pkgInfo.verifiers.length == 0) {
10011            return null;
10012        }
10013
10014        final int N = pkgInfo.verifiers.length;
10015        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10016        for (int i = 0; i < N; i++) {
10017            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10018
10019            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10020                    receivers);
10021            if (comp == null) {
10022                continue;
10023            }
10024
10025            final int verifierUid = getUidForVerifier(verifierInfo);
10026            if (verifierUid == -1) {
10027                continue;
10028            }
10029
10030            if (DEBUG_VERIFY) {
10031                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10032                        + " with the correct signature");
10033            }
10034            sufficientVerifiers.add(comp);
10035            verificationState.addSufficientVerifier(verifierUid);
10036        }
10037
10038        return sufficientVerifiers;
10039    }
10040
10041    private int getUidForVerifier(VerifierInfo verifierInfo) {
10042        synchronized (mPackages) {
10043            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10044            if (pkg == null) {
10045                return -1;
10046            } else if (pkg.mSignatures.length != 1) {
10047                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10048                        + " has more than one signature; ignoring");
10049                return -1;
10050            }
10051
10052            /*
10053             * If the public key of the package's signature does not match
10054             * our expected public key, then this is a different package and
10055             * we should skip.
10056             */
10057
10058            final byte[] expectedPublicKey;
10059            try {
10060                final Signature verifierSig = pkg.mSignatures[0];
10061                final PublicKey publicKey = verifierSig.getPublicKey();
10062                expectedPublicKey = publicKey.getEncoded();
10063            } catch (CertificateException e) {
10064                return -1;
10065            }
10066
10067            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10068
10069            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10070                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10071                        + " does not have the expected public key; ignoring");
10072                return -1;
10073            }
10074
10075            return pkg.applicationInfo.uid;
10076        }
10077    }
10078
10079    @Override
10080    public void finishPackageInstall(int token) {
10081        enforceSystemOrRoot("Only the system is allowed to finish installs");
10082
10083        if (DEBUG_INSTALL) {
10084            Slog.v(TAG, "BM finishing package install for " + token);
10085        }
10086        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10087
10088        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10089        mHandler.sendMessage(msg);
10090    }
10091
10092    /**
10093     * Get the verification agent timeout.
10094     *
10095     * @return verification timeout in milliseconds
10096     */
10097    private long getVerificationTimeout() {
10098        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10099                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10100                DEFAULT_VERIFICATION_TIMEOUT);
10101    }
10102
10103    /**
10104     * Get the default verification agent response code.
10105     *
10106     * @return default verification response code
10107     */
10108    private int getDefaultVerificationResponse() {
10109        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10110                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10111                DEFAULT_VERIFICATION_RESPONSE);
10112    }
10113
10114    /**
10115     * Check whether or not package verification has been enabled.
10116     *
10117     * @return true if verification should be performed
10118     */
10119    private boolean isVerificationEnabled(int userId, int installFlags) {
10120        if (!DEFAULT_VERIFY_ENABLE) {
10121            return false;
10122        }
10123        // TODO: fix b/25118622; don't bypass verification
10124        if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) {
10125            return false;
10126        }
10127
10128        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10129
10130        // Check if installing from ADB
10131        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10132            // Do not run verification in a test harness environment
10133            if (ActivityManager.isRunningInTestHarness()) {
10134                return false;
10135            }
10136            if (ensureVerifyAppsEnabled) {
10137                return true;
10138            }
10139            // Check if the developer does not want package verification for ADB installs
10140            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10141                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10142                return false;
10143            }
10144        }
10145
10146        if (ensureVerifyAppsEnabled) {
10147            return true;
10148        }
10149
10150        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10151                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10152    }
10153
10154    @Override
10155    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10156            throws RemoteException {
10157        mContext.enforceCallingOrSelfPermission(
10158                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10159                "Only intentfilter verification agents can verify applications");
10160
10161        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10162        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10163                Binder.getCallingUid(), verificationCode, failedDomains);
10164        msg.arg1 = id;
10165        msg.obj = response;
10166        mHandler.sendMessage(msg);
10167    }
10168
10169    @Override
10170    public int getIntentVerificationStatus(String packageName, int userId) {
10171        synchronized (mPackages) {
10172            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10173        }
10174    }
10175
10176    @Override
10177    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10178        mContext.enforceCallingOrSelfPermission(
10179                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10180
10181        boolean result = false;
10182        synchronized (mPackages) {
10183            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10184        }
10185        if (result) {
10186            scheduleWritePackageRestrictionsLocked(userId);
10187        }
10188        return result;
10189    }
10190
10191    @Override
10192    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10193        synchronized (mPackages) {
10194            return mSettings.getIntentFilterVerificationsLPr(packageName);
10195        }
10196    }
10197
10198    @Override
10199    public List<IntentFilter> getAllIntentFilters(String packageName) {
10200        if (TextUtils.isEmpty(packageName)) {
10201            return Collections.<IntentFilter>emptyList();
10202        }
10203        synchronized (mPackages) {
10204            PackageParser.Package pkg = mPackages.get(packageName);
10205            if (pkg == null || pkg.activities == null) {
10206                return Collections.<IntentFilter>emptyList();
10207            }
10208            final int count = pkg.activities.size();
10209            ArrayList<IntentFilter> result = new ArrayList<>();
10210            for (int n=0; n<count; n++) {
10211                PackageParser.Activity activity = pkg.activities.get(n);
10212                if (activity.intents != null || activity.intents.size() > 0) {
10213                    result.addAll(activity.intents);
10214                }
10215            }
10216            return result;
10217        }
10218    }
10219
10220    @Override
10221    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10222        mContext.enforceCallingOrSelfPermission(
10223                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10224
10225        synchronized (mPackages) {
10226            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10227            if (packageName != null) {
10228                result |= updateIntentVerificationStatus(packageName,
10229                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10230                        userId);
10231                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10232                        packageName, userId);
10233            }
10234            return result;
10235        }
10236    }
10237
10238    @Override
10239    public String getDefaultBrowserPackageName(int userId) {
10240        synchronized (mPackages) {
10241            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10242        }
10243    }
10244
10245    /**
10246     * Get the "allow unknown sources" setting.
10247     *
10248     * @return the current "allow unknown sources" setting
10249     */
10250    private int getUnknownSourcesSettings() {
10251        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10252                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10253                -1);
10254    }
10255
10256    @Override
10257    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10258        final int uid = Binder.getCallingUid();
10259        // writer
10260        synchronized (mPackages) {
10261            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10262            if (targetPackageSetting == null) {
10263                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10264            }
10265
10266            PackageSetting installerPackageSetting;
10267            if (installerPackageName != null) {
10268                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10269                if (installerPackageSetting == null) {
10270                    throw new IllegalArgumentException("Unknown installer package: "
10271                            + installerPackageName);
10272                }
10273            } else {
10274                installerPackageSetting = null;
10275            }
10276
10277            Signature[] callerSignature;
10278            Object obj = mSettings.getUserIdLPr(uid);
10279            if (obj != null) {
10280                if (obj instanceof SharedUserSetting) {
10281                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10282                } else if (obj instanceof PackageSetting) {
10283                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10284                } else {
10285                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10286                }
10287            } else {
10288                throw new SecurityException("Unknown calling uid " + uid);
10289            }
10290
10291            // Verify: can't set installerPackageName to a package that is
10292            // not signed with the same cert as the caller.
10293            if (installerPackageSetting != null) {
10294                if (compareSignatures(callerSignature,
10295                        installerPackageSetting.signatures.mSignatures)
10296                        != PackageManager.SIGNATURE_MATCH) {
10297                    throw new SecurityException(
10298                            "Caller does not have same cert as new installer package "
10299                            + installerPackageName);
10300                }
10301            }
10302
10303            // Verify: if target already has an installer package, it must
10304            // be signed with the same cert as the caller.
10305            if (targetPackageSetting.installerPackageName != null) {
10306                PackageSetting setting = mSettings.mPackages.get(
10307                        targetPackageSetting.installerPackageName);
10308                // If the currently set package isn't valid, then it's always
10309                // okay to change it.
10310                if (setting != null) {
10311                    if (compareSignatures(callerSignature,
10312                            setting.signatures.mSignatures)
10313                            != PackageManager.SIGNATURE_MATCH) {
10314                        throw new SecurityException(
10315                                "Caller does not have same cert as old installer package "
10316                                + targetPackageSetting.installerPackageName);
10317                    }
10318                }
10319            }
10320
10321            // Okay!
10322            targetPackageSetting.installerPackageName = installerPackageName;
10323            scheduleWriteSettingsLocked();
10324        }
10325    }
10326
10327    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10328        // Queue up an async operation since the package installation may take a little while.
10329        mHandler.post(new Runnable() {
10330            public void run() {
10331                mHandler.removeCallbacks(this);
10332                 // Result object to be returned
10333                PackageInstalledInfo res = new PackageInstalledInfo();
10334                res.returnCode = currentStatus;
10335                res.uid = -1;
10336                res.pkg = null;
10337                res.removedInfo = new PackageRemovedInfo();
10338                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10339                    args.doPreInstall(res.returnCode);
10340                    synchronized (mInstallLock) {
10341                        installPackageTracedLI(args, res);
10342                    }
10343                    args.doPostInstall(res.returnCode, res.uid);
10344                }
10345
10346                // A restore should be performed at this point if (a) the install
10347                // succeeded, (b) the operation is not an update, and (c) the new
10348                // package has not opted out of backup participation.
10349                final boolean update = res.removedInfo.removedPackage != null;
10350                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10351                boolean doRestore = !update
10352                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10353
10354                // Set up the post-install work request bookkeeping.  This will be used
10355                // and cleaned up by the post-install event handling regardless of whether
10356                // there's a restore pass performed.  Token values are >= 1.
10357                int token;
10358                if (mNextInstallToken < 0) mNextInstallToken = 1;
10359                token = mNextInstallToken++;
10360
10361                PostInstallData data = new PostInstallData(args, res);
10362                mRunningInstalls.put(token, data);
10363                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10364
10365                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10366                    // Pass responsibility to the Backup Manager.  It will perform a
10367                    // restore if appropriate, then pass responsibility back to the
10368                    // Package Manager to run the post-install observer callbacks
10369                    // and broadcasts.
10370                    IBackupManager bm = IBackupManager.Stub.asInterface(
10371                            ServiceManager.getService(Context.BACKUP_SERVICE));
10372                    if (bm != null) {
10373                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10374                                + " to BM for possible restore");
10375                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10376                        try {
10377                            // TODO: http://b/22388012
10378                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10379                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10380                            } else {
10381                                doRestore = false;
10382                            }
10383                        } catch (RemoteException e) {
10384                            // can't happen; the backup manager is local
10385                        } catch (Exception e) {
10386                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10387                            doRestore = false;
10388                        }
10389                    } else {
10390                        Slog.e(TAG, "Backup Manager not found!");
10391                        doRestore = false;
10392                    }
10393                }
10394
10395                if (!doRestore) {
10396                    // No restore possible, or the Backup Manager was mysteriously not
10397                    // available -- just fire the post-install work request directly.
10398                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10399
10400                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10401
10402                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10403                    mHandler.sendMessage(msg);
10404                }
10405            }
10406        });
10407    }
10408
10409    private abstract class HandlerParams {
10410        private static final int MAX_RETRIES = 4;
10411
10412        /**
10413         * Number of times startCopy() has been attempted and had a non-fatal
10414         * error.
10415         */
10416        private int mRetries = 0;
10417
10418        /** User handle for the user requesting the information or installation. */
10419        private final UserHandle mUser;
10420        String traceMethod;
10421        int traceCookie;
10422
10423        HandlerParams(UserHandle user) {
10424            mUser = user;
10425        }
10426
10427        UserHandle getUser() {
10428            return mUser;
10429        }
10430
10431        HandlerParams setTraceMethod(String traceMethod) {
10432            this.traceMethod = traceMethod;
10433            return this;
10434        }
10435
10436        HandlerParams setTraceCookie(int traceCookie) {
10437            this.traceCookie = traceCookie;
10438            return this;
10439        }
10440
10441        final boolean startCopy() {
10442            boolean res;
10443            try {
10444                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10445
10446                if (++mRetries > MAX_RETRIES) {
10447                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10448                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10449                    handleServiceError();
10450                    return false;
10451                } else {
10452                    handleStartCopy();
10453                    res = true;
10454                }
10455            } catch (RemoteException e) {
10456                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10457                mHandler.sendEmptyMessage(MCS_RECONNECT);
10458                res = false;
10459            }
10460            handleReturnCode();
10461            return res;
10462        }
10463
10464        final void serviceError() {
10465            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10466            handleServiceError();
10467            handleReturnCode();
10468        }
10469
10470        abstract void handleStartCopy() throws RemoteException;
10471        abstract void handleServiceError();
10472        abstract void handleReturnCode();
10473    }
10474
10475    class MeasureParams extends HandlerParams {
10476        private final PackageStats mStats;
10477        private boolean mSuccess;
10478
10479        private final IPackageStatsObserver mObserver;
10480
10481        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10482            super(new UserHandle(stats.userHandle));
10483            mObserver = observer;
10484            mStats = stats;
10485        }
10486
10487        @Override
10488        public String toString() {
10489            return "MeasureParams{"
10490                + Integer.toHexString(System.identityHashCode(this))
10491                + " " + mStats.packageName + "}";
10492        }
10493
10494        @Override
10495        void handleStartCopy() throws RemoteException {
10496            synchronized (mInstallLock) {
10497                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10498            }
10499
10500            if (mSuccess) {
10501                final boolean mounted;
10502                if (Environment.isExternalStorageEmulated()) {
10503                    mounted = true;
10504                } else {
10505                    final String status = Environment.getExternalStorageState();
10506                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10507                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10508                }
10509
10510                if (mounted) {
10511                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10512
10513                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10514                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10515
10516                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10517                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10518
10519                    // Always subtract cache size, since it's a subdirectory
10520                    mStats.externalDataSize -= mStats.externalCacheSize;
10521
10522                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10523                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10524
10525                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10526                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10527                }
10528            }
10529        }
10530
10531        @Override
10532        void handleReturnCode() {
10533            if (mObserver != null) {
10534                try {
10535                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10536                } catch (RemoteException e) {
10537                    Slog.i(TAG, "Observer no longer exists.");
10538                }
10539            }
10540        }
10541
10542        @Override
10543        void handleServiceError() {
10544            Slog.e(TAG, "Could not measure application " + mStats.packageName
10545                            + " external storage");
10546        }
10547    }
10548
10549    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10550            throws RemoteException {
10551        long result = 0;
10552        for (File path : paths) {
10553            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10554        }
10555        return result;
10556    }
10557
10558    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10559        for (File path : paths) {
10560            try {
10561                mcs.clearDirectory(path.getAbsolutePath());
10562            } catch (RemoteException e) {
10563            }
10564        }
10565    }
10566
10567    static class OriginInfo {
10568        /**
10569         * Location where install is coming from, before it has been
10570         * copied/renamed into place. This could be a single monolithic APK
10571         * file, or a cluster directory. This location may be untrusted.
10572         */
10573        final File file;
10574        final String cid;
10575
10576        /**
10577         * Flag indicating that {@link #file} or {@link #cid} has already been
10578         * staged, meaning downstream users don't need to defensively copy the
10579         * contents.
10580         */
10581        final boolean staged;
10582
10583        /**
10584         * Flag indicating that {@link #file} or {@link #cid} is an already
10585         * installed app that is being moved.
10586         */
10587        final boolean existing;
10588
10589        final String resolvedPath;
10590        final File resolvedFile;
10591
10592        static OriginInfo fromNothing() {
10593            return new OriginInfo(null, null, false, false);
10594        }
10595
10596        static OriginInfo fromUntrustedFile(File file) {
10597            return new OriginInfo(file, null, false, false);
10598        }
10599
10600        static OriginInfo fromExistingFile(File file) {
10601            return new OriginInfo(file, null, false, true);
10602        }
10603
10604        static OriginInfo fromStagedFile(File file) {
10605            return new OriginInfo(file, null, true, false);
10606        }
10607
10608        static OriginInfo fromStagedContainer(String cid) {
10609            return new OriginInfo(null, cid, true, false);
10610        }
10611
10612        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10613            this.file = file;
10614            this.cid = cid;
10615            this.staged = staged;
10616            this.existing = existing;
10617
10618            if (cid != null) {
10619                resolvedPath = PackageHelper.getSdDir(cid);
10620                resolvedFile = new File(resolvedPath);
10621            } else if (file != null) {
10622                resolvedPath = file.getAbsolutePath();
10623                resolvedFile = file;
10624            } else {
10625                resolvedPath = null;
10626                resolvedFile = null;
10627            }
10628        }
10629    }
10630
10631    class MoveInfo {
10632        final int moveId;
10633        final String fromUuid;
10634        final String toUuid;
10635        final String packageName;
10636        final String dataAppName;
10637        final int appId;
10638        final String seinfo;
10639
10640        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10641                String dataAppName, int appId, String seinfo) {
10642            this.moveId = moveId;
10643            this.fromUuid = fromUuid;
10644            this.toUuid = toUuid;
10645            this.packageName = packageName;
10646            this.dataAppName = dataAppName;
10647            this.appId = appId;
10648            this.seinfo = seinfo;
10649        }
10650    }
10651
10652    class InstallParams extends HandlerParams {
10653        final OriginInfo origin;
10654        final MoveInfo move;
10655        final IPackageInstallObserver2 observer;
10656        int installFlags;
10657        final String installerPackageName;
10658        final String volumeUuid;
10659        final VerificationParams verificationParams;
10660        private InstallArgs mArgs;
10661        private int mRet;
10662        final String packageAbiOverride;
10663        final String[] grantedRuntimePermissions;
10664
10665        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10666                int installFlags, String installerPackageName, String volumeUuid,
10667                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10668                String[] grantedPermissions) {
10669            super(user);
10670            this.origin = origin;
10671            this.move = move;
10672            this.observer = observer;
10673            this.installFlags = installFlags;
10674            this.installerPackageName = installerPackageName;
10675            this.volumeUuid = volumeUuid;
10676            this.verificationParams = verificationParams;
10677            this.packageAbiOverride = packageAbiOverride;
10678            this.grantedRuntimePermissions = grantedPermissions;
10679        }
10680
10681        @Override
10682        public String toString() {
10683            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10684                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10685        }
10686
10687        public ManifestDigest getManifestDigest() {
10688            if (verificationParams == null) {
10689                return null;
10690            }
10691            return verificationParams.getManifestDigest();
10692        }
10693
10694        private int installLocationPolicy(PackageInfoLite pkgLite) {
10695            String packageName = pkgLite.packageName;
10696            int installLocation = pkgLite.installLocation;
10697            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10698            // reader
10699            synchronized (mPackages) {
10700                PackageParser.Package pkg = mPackages.get(packageName);
10701                if (pkg != null) {
10702                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10703                        // Check for downgrading.
10704                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10705                            try {
10706                                checkDowngrade(pkg, pkgLite);
10707                            } catch (PackageManagerException e) {
10708                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10709                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10710                            }
10711                        }
10712                        // Check for updated system application.
10713                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10714                            if (onSd) {
10715                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10716                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10717                            }
10718                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10719                        } else {
10720                            if (onSd) {
10721                                // Install flag overrides everything.
10722                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10723                            }
10724                            // If current upgrade specifies particular preference
10725                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10726                                // Application explicitly specified internal.
10727                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10728                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10729                                // App explictly prefers external. Let policy decide
10730                            } else {
10731                                // Prefer previous location
10732                                if (isExternal(pkg)) {
10733                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10734                                }
10735                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10736                            }
10737                        }
10738                    } else {
10739                        // Invalid install. Return error code
10740                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10741                    }
10742                }
10743            }
10744            // All the special cases have been taken care of.
10745            // Return result based on recommended install location.
10746            if (onSd) {
10747                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10748            }
10749            return pkgLite.recommendedInstallLocation;
10750        }
10751
10752        /*
10753         * Invoke remote method to get package information and install
10754         * location values. Override install location based on default
10755         * policy if needed and then create install arguments based
10756         * on the install location.
10757         */
10758        public void handleStartCopy() throws RemoteException {
10759            int ret = PackageManager.INSTALL_SUCCEEDED;
10760
10761            // If we're already staged, we've firmly committed to an install location
10762            if (origin.staged) {
10763                if (origin.file != null) {
10764                    installFlags |= PackageManager.INSTALL_INTERNAL;
10765                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10766                } else if (origin.cid != null) {
10767                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10768                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10769                } else {
10770                    throw new IllegalStateException("Invalid stage location");
10771                }
10772            }
10773
10774            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10775            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10776            PackageInfoLite pkgLite = null;
10777
10778            if (onInt && onSd) {
10779                // Check if both bits are set.
10780                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10781                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10782            } else {
10783                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10784                        packageAbiOverride);
10785
10786                /*
10787                 * If we have too little free space, try to free cache
10788                 * before giving up.
10789                 */
10790                if (!origin.staged && pkgLite.recommendedInstallLocation
10791                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10792                    // TODO: focus freeing disk space on the target device
10793                    final StorageManager storage = StorageManager.from(mContext);
10794                    final long lowThreshold = storage.getStorageLowBytes(
10795                            Environment.getDataDirectory());
10796
10797                    final long sizeBytes = mContainerService.calculateInstalledSize(
10798                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10799
10800                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10801                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10802                                installFlags, packageAbiOverride);
10803                    }
10804
10805                    /*
10806                     * The cache free must have deleted the file we
10807                     * downloaded to install.
10808                     *
10809                     * TODO: fix the "freeCache" call to not delete
10810                     *       the file we care about.
10811                     */
10812                    if (pkgLite.recommendedInstallLocation
10813                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10814                        pkgLite.recommendedInstallLocation
10815                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10816                    }
10817                }
10818            }
10819
10820            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10821                int loc = pkgLite.recommendedInstallLocation;
10822                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10823                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10824                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10825                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10826                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10827                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10828                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10829                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10830                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10831                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10832                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10833                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10834                } else {
10835                    // Override with defaults if needed.
10836                    loc = installLocationPolicy(pkgLite);
10837                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10838                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10839                    } else if (!onSd && !onInt) {
10840                        // Override install location with flags
10841                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10842                            // Set the flag to install on external media.
10843                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10844                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10845                        } else {
10846                            // Make sure the flag for installing on external
10847                            // media is unset
10848                            installFlags |= PackageManager.INSTALL_INTERNAL;
10849                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10850                        }
10851                    }
10852                }
10853            }
10854
10855            final InstallArgs args = createInstallArgs(this);
10856            mArgs = args;
10857
10858            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10859                // TODO: http://b/22976637
10860                // Apps installed for "all" users use the device owner to verify the app
10861                UserHandle verifierUser = getUser();
10862                if (verifierUser == UserHandle.ALL) {
10863                    verifierUser = UserHandle.SYSTEM;
10864                }
10865
10866                /*
10867                 * Determine if we have any installed package verifiers. If we
10868                 * do, then we'll defer to them to verify the packages.
10869                 */
10870                final int requiredUid = mRequiredVerifierPackage == null ? -1
10871                        : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier());
10872                if (!origin.existing && requiredUid != -1
10873                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
10874                    final Intent verification = new Intent(
10875                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10876                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10877                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10878                            PACKAGE_MIME_TYPE);
10879                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10880
10881                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10882                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10883                            verifierUser.getIdentifier());
10884
10885                    if (DEBUG_VERIFY) {
10886                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10887                                + verification.toString() + " with " + pkgLite.verifiers.length
10888                                + " optional verifiers");
10889                    }
10890
10891                    final int verificationId = mPendingVerificationToken++;
10892
10893                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10894
10895                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10896                            installerPackageName);
10897
10898                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10899                            installFlags);
10900
10901                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10902                            pkgLite.packageName);
10903
10904                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10905                            pkgLite.versionCode);
10906
10907                    if (verificationParams != null) {
10908                        if (verificationParams.getVerificationURI() != null) {
10909                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10910                                 verificationParams.getVerificationURI());
10911                        }
10912                        if (verificationParams.getOriginatingURI() != null) {
10913                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10914                                  verificationParams.getOriginatingURI());
10915                        }
10916                        if (verificationParams.getReferrer() != null) {
10917                            verification.putExtra(Intent.EXTRA_REFERRER,
10918                                  verificationParams.getReferrer());
10919                        }
10920                        if (verificationParams.getOriginatingUid() >= 0) {
10921                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10922                                  verificationParams.getOriginatingUid());
10923                        }
10924                        if (verificationParams.getInstallerUid() >= 0) {
10925                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10926                                  verificationParams.getInstallerUid());
10927                        }
10928                    }
10929
10930                    final PackageVerificationState verificationState = new PackageVerificationState(
10931                            requiredUid, args);
10932
10933                    mPendingVerification.append(verificationId, verificationState);
10934
10935                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10936                            receivers, verificationState);
10937
10938                    /*
10939                     * If any sufficient verifiers were listed in the package
10940                     * manifest, attempt to ask them.
10941                     */
10942                    if (sufficientVerifiers != null) {
10943                        final int N = sufficientVerifiers.size();
10944                        if (N == 0) {
10945                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10946                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10947                        } else {
10948                            for (int i = 0; i < N; i++) {
10949                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10950
10951                                final Intent sufficientIntent = new Intent(verification);
10952                                sufficientIntent.setComponent(verifierComponent);
10953                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10954                            }
10955                        }
10956                    }
10957
10958                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10959                            mRequiredVerifierPackage, receivers);
10960                    if (ret == PackageManager.INSTALL_SUCCEEDED
10961                            && mRequiredVerifierPackage != null) {
10962                        Trace.asyncTraceBegin(
10963                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
10964                        /*
10965                         * Send the intent to the required verification agent,
10966                         * but only start the verification timeout after the
10967                         * target BroadcastReceivers have run.
10968                         */
10969                        verification.setComponent(requiredVerifierComponent);
10970                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10971                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10972                                new BroadcastReceiver() {
10973                                    @Override
10974                                    public void onReceive(Context context, Intent intent) {
10975                                        final Message msg = mHandler
10976                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10977                                        msg.arg1 = verificationId;
10978                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10979                                    }
10980                                }, null, 0, null, null);
10981
10982                        /*
10983                         * We don't want the copy to proceed until verification
10984                         * succeeds, so null out this field.
10985                         */
10986                        mArgs = null;
10987                    }
10988                } else {
10989                    /*
10990                     * No package verification is enabled, so immediately start
10991                     * the remote call to initiate copy using temporary file.
10992                     */
10993                    ret = args.copyApk(mContainerService, true);
10994                }
10995            }
10996
10997            mRet = ret;
10998        }
10999
11000        @Override
11001        void handleReturnCode() {
11002            // If mArgs is null, then MCS couldn't be reached. When it
11003            // reconnects, it will try again to install. At that point, this
11004            // will succeed.
11005            if (mArgs != null) {
11006                processPendingInstall(mArgs, mRet);
11007            }
11008        }
11009
11010        @Override
11011        void handleServiceError() {
11012            mArgs = createInstallArgs(this);
11013            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11014        }
11015
11016        public boolean isForwardLocked() {
11017            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11018        }
11019    }
11020
11021    /**
11022     * Used during creation of InstallArgs
11023     *
11024     * @param installFlags package installation flags
11025     * @return true if should be installed on external storage
11026     */
11027    private static boolean installOnExternalAsec(int installFlags) {
11028        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11029            return false;
11030        }
11031        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11032            return true;
11033        }
11034        return false;
11035    }
11036
11037    /**
11038     * Used during creation of InstallArgs
11039     *
11040     * @param installFlags package installation flags
11041     * @return true if should be installed as forward locked
11042     */
11043    private static boolean installForwardLocked(int installFlags) {
11044        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11045    }
11046
11047    private InstallArgs createInstallArgs(InstallParams params) {
11048        if (params.move != null) {
11049            return new MoveInstallArgs(params);
11050        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11051            return new AsecInstallArgs(params);
11052        } else {
11053            return new FileInstallArgs(params);
11054        }
11055    }
11056
11057    /**
11058     * Create args that describe an existing installed package. Typically used
11059     * when cleaning up old installs, or used as a move source.
11060     */
11061    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11062            String resourcePath, String[] instructionSets) {
11063        final boolean isInAsec;
11064        if (installOnExternalAsec(installFlags)) {
11065            /* Apps on SD card are always in ASEC containers. */
11066            isInAsec = true;
11067        } else if (installForwardLocked(installFlags)
11068                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11069            /*
11070             * Forward-locked apps are only in ASEC containers if they're the
11071             * new style
11072             */
11073            isInAsec = true;
11074        } else {
11075            isInAsec = false;
11076        }
11077
11078        if (isInAsec) {
11079            return new AsecInstallArgs(codePath, instructionSets,
11080                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11081        } else {
11082            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11083        }
11084    }
11085
11086    static abstract class InstallArgs {
11087        /** @see InstallParams#origin */
11088        final OriginInfo origin;
11089        /** @see InstallParams#move */
11090        final MoveInfo move;
11091
11092        final IPackageInstallObserver2 observer;
11093        // Always refers to PackageManager flags only
11094        final int installFlags;
11095        final String installerPackageName;
11096        final String volumeUuid;
11097        final ManifestDigest manifestDigest;
11098        final UserHandle user;
11099        final String abiOverride;
11100        final String[] installGrantPermissions;
11101        /** If non-null, drop an async trace when the install completes */
11102        final String traceMethod;
11103        final int traceCookie;
11104
11105        // The list of instruction sets supported by this app. This is currently
11106        // only used during the rmdex() phase to clean up resources. We can get rid of this
11107        // if we move dex files under the common app path.
11108        /* nullable */ String[] instructionSets;
11109
11110        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11111                int installFlags, String installerPackageName, String volumeUuid,
11112                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11113                String abiOverride, String[] installGrantPermissions,
11114                String traceMethod, int traceCookie) {
11115            this.origin = origin;
11116            this.move = move;
11117            this.installFlags = installFlags;
11118            this.observer = observer;
11119            this.installerPackageName = installerPackageName;
11120            this.volumeUuid = volumeUuid;
11121            this.manifestDigest = manifestDigest;
11122            this.user = user;
11123            this.instructionSets = instructionSets;
11124            this.abiOverride = abiOverride;
11125            this.installGrantPermissions = installGrantPermissions;
11126            this.traceMethod = traceMethod;
11127            this.traceCookie = traceCookie;
11128        }
11129
11130        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11131        abstract int doPreInstall(int status);
11132
11133        /**
11134         * Rename package into final resting place. All paths on the given
11135         * scanned package should be updated to reflect the rename.
11136         */
11137        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11138        abstract int doPostInstall(int status, int uid);
11139
11140        /** @see PackageSettingBase#codePathString */
11141        abstract String getCodePath();
11142        /** @see PackageSettingBase#resourcePathString */
11143        abstract String getResourcePath();
11144
11145        // Need installer lock especially for dex file removal.
11146        abstract void cleanUpResourcesLI();
11147        abstract boolean doPostDeleteLI(boolean delete);
11148
11149        /**
11150         * Called before the source arguments are copied. This is used mostly
11151         * for MoveParams when it needs to read the source file to put it in the
11152         * destination.
11153         */
11154        int doPreCopy() {
11155            return PackageManager.INSTALL_SUCCEEDED;
11156        }
11157
11158        /**
11159         * Called after the source arguments are copied. This is used mostly for
11160         * MoveParams when it needs to read the source file to put it in the
11161         * destination.
11162         *
11163         * @return
11164         */
11165        int doPostCopy(int uid) {
11166            return PackageManager.INSTALL_SUCCEEDED;
11167        }
11168
11169        protected boolean isFwdLocked() {
11170            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11171        }
11172
11173        protected boolean isExternalAsec() {
11174            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11175        }
11176
11177        UserHandle getUser() {
11178            return user;
11179        }
11180    }
11181
11182    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11183        if (!allCodePaths.isEmpty()) {
11184            if (instructionSets == null) {
11185                throw new IllegalStateException("instructionSet == null");
11186            }
11187            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11188            for (String codePath : allCodePaths) {
11189                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11190                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11191                    if (retCode < 0) {
11192                        Slog.w(TAG, "Couldn't remove dex file for package: "
11193                                + " at location " + codePath + ", retcode=" + retCode);
11194                        // we don't consider this to be a failure of the core package deletion
11195                    }
11196                }
11197            }
11198        }
11199    }
11200
11201    /**
11202     * Logic to handle installation of non-ASEC applications, including copying
11203     * and renaming logic.
11204     */
11205    class FileInstallArgs extends InstallArgs {
11206        private File codeFile;
11207        private File resourceFile;
11208
11209        // Example topology:
11210        // /data/app/com.example/base.apk
11211        // /data/app/com.example/split_foo.apk
11212        // /data/app/com.example/lib/arm/libfoo.so
11213        // /data/app/com.example/lib/arm64/libfoo.so
11214        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11215
11216        /** New install */
11217        FileInstallArgs(InstallParams params) {
11218            super(params.origin, params.move, params.observer, params.installFlags,
11219                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11220                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11221                    params.grantedRuntimePermissions,
11222                    params.traceMethod, params.traceCookie);
11223            if (isFwdLocked()) {
11224                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11225            }
11226        }
11227
11228        /** Existing install */
11229        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11230            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11231                    null, null, null, 0);
11232            this.codeFile = (codePath != null) ? new File(codePath) : null;
11233            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11234        }
11235
11236        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11237            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11238            try {
11239                return doCopyApk(imcs, temp);
11240            } finally {
11241                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11242            }
11243        }
11244
11245        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11246            if (origin.staged) {
11247                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11248                codeFile = origin.file;
11249                resourceFile = origin.file;
11250                return PackageManager.INSTALL_SUCCEEDED;
11251            }
11252
11253            try {
11254                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11255                codeFile = tempDir;
11256                resourceFile = tempDir;
11257            } catch (IOException e) {
11258                Slog.w(TAG, "Failed to create copy file: " + e);
11259                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11260            }
11261
11262            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11263                @Override
11264                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11265                    if (!FileUtils.isValidExtFilename(name)) {
11266                        throw new IllegalArgumentException("Invalid filename: " + name);
11267                    }
11268                    try {
11269                        final File file = new File(codeFile, name);
11270                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11271                                O_RDWR | O_CREAT, 0644);
11272                        Os.chmod(file.getAbsolutePath(), 0644);
11273                        return new ParcelFileDescriptor(fd);
11274                    } catch (ErrnoException e) {
11275                        throw new RemoteException("Failed to open: " + e.getMessage());
11276                    }
11277                }
11278            };
11279
11280            int ret = PackageManager.INSTALL_SUCCEEDED;
11281            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11282            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11283                Slog.e(TAG, "Failed to copy package");
11284                return ret;
11285            }
11286
11287            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11288            NativeLibraryHelper.Handle handle = null;
11289            try {
11290                handle = NativeLibraryHelper.Handle.create(codeFile);
11291                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11292                        abiOverride);
11293            } catch (IOException e) {
11294                Slog.e(TAG, "Copying native libraries failed", e);
11295                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11296            } finally {
11297                IoUtils.closeQuietly(handle);
11298            }
11299
11300            return ret;
11301        }
11302
11303        int doPreInstall(int status) {
11304            if (status != PackageManager.INSTALL_SUCCEEDED) {
11305                cleanUp();
11306            }
11307            return status;
11308        }
11309
11310        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11311            if (status != PackageManager.INSTALL_SUCCEEDED) {
11312                cleanUp();
11313                return false;
11314            }
11315
11316            final File targetDir = codeFile.getParentFile();
11317            final File beforeCodeFile = codeFile;
11318            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11319
11320            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11321            try {
11322                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11323            } catch (ErrnoException e) {
11324                Slog.w(TAG, "Failed to rename", e);
11325                return false;
11326            }
11327
11328            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11329                Slog.w(TAG, "Failed to restorecon");
11330                return false;
11331            }
11332
11333            // Reflect the rename internally
11334            codeFile = afterCodeFile;
11335            resourceFile = afterCodeFile;
11336
11337            // Reflect the rename in scanned details
11338            pkg.codePath = afterCodeFile.getAbsolutePath();
11339            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11340                    pkg.baseCodePath);
11341            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11342                    pkg.splitCodePaths);
11343
11344            // Reflect the rename in app info
11345            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11346            pkg.applicationInfo.setCodePath(pkg.codePath);
11347            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11348            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11349            pkg.applicationInfo.setResourcePath(pkg.codePath);
11350            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11351            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11352
11353            return true;
11354        }
11355
11356        int doPostInstall(int status, int uid) {
11357            if (status != PackageManager.INSTALL_SUCCEEDED) {
11358                cleanUp();
11359            }
11360            return status;
11361        }
11362
11363        @Override
11364        String getCodePath() {
11365            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11366        }
11367
11368        @Override
11369        String getResourcePath() {
11370            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11371        }
11372
11373        private boolean cleanUp() {
11374            if (codeFile == null || !codeFile.exists()) {
11375                return false;
11376            }
11377
11378            if (codeFile.isDirectory()) {
11379                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11380            } else {
11381                codeFile.delete();
11382            }
11383
11384            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11385                resourceFile.delete();
11386            }
11387
11388            return true;
11389        }
11390
11391        void cleanUpResourcesLI() {
11392            // Try enumerating all code paths before deleting
11393            List<String> allCodePaths = Collections.EMPTY_LIST;
11394            if (codeFile != null && codeFile.exists()) {
11395                try {
11396                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11397                    allCodePaths = pkg.getAllCodePaths();
11398                } catch (PackageParserException e) {
11399                    // Ignored; we tried our best
11400                }
11401            }
11402
11403            cleanUp();
11404            removeDexFiles(allCodePaths, instructionSets);
11405        }
11406
11407        boolean doPostDeleteLI(boolean delete) {
11408            // XXX err, shouldn't we respect the delete flag?
11409            cleanUpResourcesLI();
11410            return true;
11411        }
11412    }
11413
11414    private boolean isAsecExternal(String cid) {
11415        final String asecPath = PackageHelper.getSdFilesystem(cid);
11416        return !asecPath.startsWith(mAsecInternalPath);
11417    }
11418
11419    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11420            PackageManagerException {
11421        if (copyRet < 0) {
11422            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11423                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11424                throw new PackageManagerException(copyRet, message);
11425            }
11426        }
11427    }
11428
11429    /**
11430     * Extract the MountService "container ID" from the full code path of an
11431     * .apk.
11432     */
11433    static String cidFromCodePath(String fullCodePath) {
11434        int eidx = fullCodePath.lastIndexOf("/");
11435        String subStr1 = fullCodePath.substring(0, eidx);
11436        int sidx = subStr1.lastIndexOf("/");
11437        return subStr1.substring(sidx+1, eidx);
11438    }
11439
11440    /**
11441     * Logic to handle installation of ASEC applications, including copying and
11442     * renaming logic.
11443     */
11444    class AsecInstallArgs extends InstallArgs {
11445        static final String RES_FILE_NAME = "pkg.apk";
11446        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11447
11448        String cid;
11449        String packagePath;
11450        String resourcePath;
11451
11452        /** New install */
11453        AsecInstallArgs(InstallParams params) {
11454            super(params.origin, params.move, params.observer, params.installFlags,
11455                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11456                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11457                    params.grantedRuntimePermissions,
11458                    params.traceMethod, params.traceCookie);
11459        }
11460
11461        /** Existing install */
11462        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11463                        boolean isExternal, boolean isForwardLocked) {
11464            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11465                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11466                    instructionSets, null, null, null, 0);
11467            // Hackily pretend we're still looking at a full code path
11468            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11469                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11470            }
11471
11472            // Extract cid from fullCodePath
11473            int eidx = fullCodePath.lastIndexOf("/");
11474            String subStr1 = fullCodePath.substring(0, eidx);
11475            int sidx = subStr1.lastIndexOf("/");
11476            cid = subStr1.substring(sidx+1, eidx);
11477            setMountPath(subStr1);
11478        }
11479
11480        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11481            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11482                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11483                    instructionSets, null, null, null, 0);
11484            this.cid = cid;
11485            setMountPath(PackageHelper.getSdDir(cid));
11486        }
11487
11488        void createCopyFile() {
11489            cid = mInstallerService.allocateExternalStageCidLegacy();
11490        }
11491
11492        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11493            if (origin.staged) {
11494                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11495                cid = origin.cid;
11496                setMountPath(PackageHelper.getSdDir(cid));
11497                return PackageManager.INSTALL_SUCCEEDED;
11498            }
11499
11500            if (temp) {
11501                createCopyFile();
11502            } else {
11503                /*
11504                 * Pre-emptively destroy the container since it's destroyed if
11505                 * copying fails due to it existing anyway.
11506                 */
11507                PackageHelper.destroySdDir(cid);
11508            }
11509
11510            final String newMountPath = imcs.copyPackageToContainer(
11511                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11512                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11513
11514            if (newMountPath != null) {
11515                setMountPath(newMountPath);
11516                return PackageManager.INSTALL_SUCCEEDED;
11517            } else {
11518                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11519            }
11520        }
11521
11522        @Override
11523        String getCodePath() {
11524            return packagePath;
11525        }
11526
11527        @Override
11528        String getResourcePath() {
11529            return resourcePath;
11530        }
11531
11532        int doPreInstall(int status) {
11533            if (status != PackageManager.INSTALL_SUCCEEDED) {
11534                // Destroy container
11535                PackageHelper.destroySdDir(cid);
11536            } else {
11537                boolean mounted = PackageHelper.isContainerMounted(cid);
11538                if (!mounted) {
11539                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11540                            Process.SYSTEM_UID);
11541                    if (newMountPath != null) {
11542                        setMountPath(newMountPath);
11543                    } else {
11544                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11545                    }
11546                }
11547            }
11548            return status;
11549        }
11550
11551        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11552            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11553            String newMountPath = null;
11554            if (PackageHelper.isContainerMounted(cid)) {
11555                // Unmount the container
11556                if (!PackageHelper.unMountSdDir(cid)) {
11557                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11558                    return false;
11559                }
11560            }
11561            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11562                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11563                        " which might be stale. Will try to clean up.");
11564                // Clean up the stale container and proceed to recreate.
11565                if (!PackageHelper.destroySdDir(newCacheId)) {
11566                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11567                    return false;
11568                }
11569                // Successfully cleaned up stale container. Try to rename again.
11570                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11571                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11572                            + " inspite of cleaning it up.");
11573                    return false;
11574                }
11575            }
11576            if (!PackageHelper.isContainerMounted(newCacheId)) {
11577                Slog.w(TAG, "Mounting container " + newCacheId);
11578                newMountPath = PackageHelper.mountSdDir(newCacheId,
11579                        getEncryptKey(), Process.SYSTEM_UID);
11580            } else {
11581                newMountPath = PackageHelper.getSdDir(newCacheId);
11582            }
11583            if (newMountPath == null) {
11584                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11585                return false;
11586            }
11587            Log.i(TAG, "Succesfully renamed " + cid +
11588                    " to " + newCacheId +
11589                    " at new path: " + newMountPath);
11590            cid = newCacheId;
11591
11592            final File beforeCodeFile = new File(packagePath);
11593            setMountPath(newMountPath);
11594            final File afterCodeFile = new File(packagePath);
11595
11596            // Reflect the rename in scanned details
11597            pkg.codePath = afterCodeFile.getAbsolutePath();
11598            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11599                    pkg.baseCodePath);
11600            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11601                    pkg.splitCodePaths);
11602
11603            // Reflect the rename in app info
11604            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11605            pkg.applicationInfo.setCodePath(pkg.codePath);
11606            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11607            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11608            pkg.applicationInfo.setResourcePath(pkg.codePath);
11609            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11610            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11611
11612            return true;
11613        }
11614
11615        private void setMountPath(String mountPath) {
11616            final File mountFile = new File(mountPath);
11617
11618            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11619            if (monolithicFile.exists()) {
11620                packagePath = monolithicFile.getAbsolutePath();
11621                if (isFwdLocked()) {
11622                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11623                } else {
11624                    resourcePath = packagePath;
11625                }
11626            } else {
11627                packagePath = mountFile.getAbsolutePath();
11628                resourcePath = packagePath;
11629            }
11630        }
11631
11632        int doPostInstall(int status, int uid) {
11633            if (status != PackageManager.INSTALL_SUCCEEDED) {
11634                cleanUp();
11635            } else {
11636                final int groupOwner;
11637                final String protectedFile;
11638                if (isFwdLocked()) {
11639                    groupOwner = UserHandle.getSharedAppGid(uid);
11640                    protectedFile = RES_FILE_NAME;
11641                } else {
11642                    groupOwner = -1;
11643                    protectedFile = null;
11644                }
11645
11646                if (uid < Process.FIRST_APPLICATION_UID
11647                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11648                    Slog.e(TAG, "Failed to finalize " + cid);
11649                    PackageHelper.destroySdDir(cid);
11650                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11651                }
11652
11653                boolean mounted = PackageHelper.isContainerMounted(cid);
11654                if (!mounted) {
11655                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11656                }
11657            }
11658            return status;
11659        }
11660
11661        private void cleanUp() {
11662            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11663
11664            // Destroy secure container
11665            PackageHelper.destroySdDir(cid);
11666        }
11667
11668        private List<String> getAllCodePaths() {
11669            final File codeFile = new File(getCodePath());
11670            if (codeFile != null && codeFile.exists()) {
11671                try {
11672                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11673                    return pkg.getAllCodePaths();
11674                } catch (PackageParserException e) {
11675                    // Ignored; we tried our best
11676                }
11677            }
11678            return Collections.EMPTY_LIST;
11679        }
11680
11681        void cleanUpResourcesLI() {
11682            // Enumerate all code paths before deleting
11683            cleanUpResourcesLI(getAllCodePaths());
11684        }
11685
11686        private void cleanUpResourcesLI(List<String> allCodePaths) {
11687            cleanUp();
11688            removeDexFiles(allCodePaths, instructionSets);
11689        }
11690
11691        String getPackageName() {
11692            return getAsecPackageName(cid);
11693        }
11694
11695        boolean doPostDeleteLI(boolean delete) {
11696            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11697            final List<String> allCodePaths = getAllCodePaths();
11698            boolean mounted = PackageHelper.isContainerMounted(cid);
11699            if (mounted) {
11700                // Unmount first
11701                if (PackageHelper.unMountSdDir(cid)) {
11702                    mounted = false;
11703                }
11704            }
11705            if (!mounted && delete) {
11706                cleanUpResourcesLI(allCodePaths);
11707            }
11708            return !mounted;
11709        }
11710
11711        @Override
11712        int doPreCopy() {
11713            if (isFwdLocked()) {
11714                if (!PackageHelper.fixSdPermissions(cid,
11715                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11716                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11717                }
11718            }
11719
11720            return PackageManager.INSTALL_SUCCEEDED;
11721        }
11722
11723        @Override
11724        int doPostCopy(int uid) {
11725            if (isFwdLocked()) {
11726                if (uid < Process.FIRST_APPLICATION_UID
11727                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11728                                RES_FILE_NAME)) {
11729                    Slog.e(TAG, "Failed to finalize " + cid);
11730                    PackageHelper.destroySdDir(cid);
11731                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11732                }
11733            }
11734
11735            return PackageManager.INSTALL_SUCCEEDED;
11736        }
11737    }
11738
11739    /**
11740     * Logic to handle movement of existing installed applications.
11741     */
11742    class MoveInstallArgs extends InstallArgs {
11743        private File codeFile;
11744        private File resourceFile;
11745
11746        /** New install */
11747        MoveInstallArgs(InstallParams params) {
11748            super(params.origin, params.move, params.observer, params.installFlags,
11749                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11750                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11751                    params.grantedRuntimePermissions,
11752                    params.traceMethod, params.traceCookie);
11753        }
11754
11755        int copyApk(IMediaContainerService imcs, boolean temp) {
11756            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11757                    + move.fromUuid + " to " + move.toUuid);
11758            synchronized (mInstaller) {
11759                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11760                        move.dataAppName, move.appId, move.seinfo) != 0) {
11761                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11762                }
11763            }
11764
11765            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11766            resourceFile = codeFile;
11767            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11768
11769            return PackageManager.INSTALL_SUCCEEDED;
11770        }
11771
11772        int doPreInstall(int status) {
11773            if (status != PackageManager.INSTALL_SUCCEEDED) {
11774                cleanUp(move.toUuid);
11775            }
11776            return status;
11777        }
11778
11779        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11780            if (status != PackageManager.INSTALL_SUCCEEDED) {
11781                cleanUp(move.toUuid);
11782                return false;
11783            }
11784
11785            // Reflect the move in app info
11786            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11787            pkg.applicationInfo.setCodePath(pkg.codePath);
11788            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11789            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11790            pkg.applicationInfo.setResourcePath(pkg.codePath);
11791            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11792            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11793
11794            return true;
11795        }
11796
11797        int doPostInstall(int status, int uid) {
11798            if (status == PackageManager.INSTALL_SUCCEEDED) {
11799                cleanUp(move.fromUuid);
11800            } else {
11801                cleanUp(move.toUuid);
11802            }
11803            return status;
11804        }
11805
11806        @Override
11807        String getCodePath() {
11808            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11809        }
11810
11811        @Override
11812        String getResourcePath() {
11813            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11814        }
11815
11816        private boolean cleanUp(String volumeUuid) {
11817            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11818                    move.dataAppName);
11819            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11820            synchronized (mInstallLock) {
11821                // Clean up both app data and code
11822                removeDataDirsLI(volumeUuid, move.packageName);
11823                if (codeFile.isDirectory()) {
11824                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11825                } else {
11826                    codeFile.delete();
11827                }
11828            }
11829            return true;
11830        }
11831
11832        void cleanUpResourcesLI() {
11833            throw new UnsupportedOperationException();
11834        }
11835
11836        boolean doPostDeleteLI(boolean delete) {
11837            throw new UnsupportedOperationException();
11838        }
11839    }
11840
11841    static String getAsecPackageName(String packageCid) {
11842        int idx = packageCid.lastIndexOf("-");
11843        if (idx == -1) {
11844            return packageCid;
11845        }
11846        return packageCid.substring(0, idx);
11847    }
11848
11849    // Utility method used to create code paths based on package name and available index.
11850    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11851        String idxStr = "";
11852        int idx = 1;
11853        // Fall back to default value of idx=1 if prefix is not
11854        // part of oldCodePath
11855        if (oldCodePath != null) {
11856            String subStr = oldCodePath;
11857            // Drop the suffix right away
11858            if (suffix != null && subStr.endsWith(suffix)) {
11859                subStr = subStr.substring(0, subStr.length() - suffix.length());
11860            }
11861            // If oldCodePath already contains prefix find out the
11862            // ending index to either increment or decrement.
11863            int sidx = subStr.lastIndexOf(prefix);
11864            if (sidx != -1) {
11865                subStr = subStr.substring(sidx + prefix.length());
11866                if (subStr != null) {
11867                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11868                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11869                    }
11870                    try {
11871                        idx = Integer.parseInt(subStr);
11872                        if (idx <= 1) {
11873                            idx++;
11874                        } else {
11875                            idx--;
11876                        }
11877                    } catch(NumberFormatException e) {
11878                    }
11879                }
11880            }
11881        }
11882        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11883        return prefix + idxStr;
11884    }
11885
11886    private File getNextCodePath(File targetDir, String packageName) {
11887        int suffix = 1;
11888        File result;
11889        do {
11890            result = new File(targetDir, packageName + "-" + suffix);
11891            suffix++;
11892        } while (result.exists());
11893        return result;
11894    }
11895
11896    // Utility method that returns the relative package path with respect
11897    // to the installation directory. Like say for /data/data/com.test-1.apk
11898    // string com.test-1 is returned.
11899    static String deriveCodePathName(String codePath) {
11900        if (codePath == null) {
11901            return null;
11902        }
11903        final File codeFile = new File(codePath);
11904        final String name = codeFile.getName();
11905        if (codeFile.isDirectory()) {
11906            return name;
11907        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11908            final int lastDot = name.lastIndexOf('.');
11909            return name.substring(0, lastDot);
11910        } else {
11911            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11912            return null;
11913        }
11914    }
11915
11916    class PackageInstalledInfo {
11917        String name;
11918        int uid;
11919        // The set of users that originally had this package installed.
11920        int[] origUsers;
11921        // The set of users that now have this package installed.
11922        int[] newUsers;
11923        PackageParser.Package pkg;
11924        int returnCode;
11925        String returnMsg;
11926        PackageRemovedInfo removedInfo;
11927
11928        public void setError(int code, String msg) {
11929            returnCode = code;
11930            returnMsg = msg;
11931            Slog.w(TAG, msg);
11932        }
11933
11934        public void setError(String msg, PackageParserException e) {
11935            returnCode = e.error;
11936            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11937            Slog.w(TAG, msg, e);
11938        }
11939
11940        public void setError(String msg, PackageManagerException e) {
11941            returnCode = e.error;
11942            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11943            Slog.w(TAG, msg, e);
11944        }
11945
11946        // In some error cases we want to convey more info back to the observer
11947        String origPackage;
11948        String origPermission;
11949    }
11950
11951    /*
11952     * Install a non-existing package.
11953     */
11954    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11955            UserHandle user, String installerPackageName, String volumeUuid,
11956            PackageInstalledInfo res) {
11957        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
11958
11959        // Remember this for later, in case we need to rollback this install
11960        String pkgName = pkg.packageName;
11961
11962        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11963        // TODO: b/23350563
11964        final boolean dataDirExists = Environment
11965                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
11966
11967        synchronized(mPackages) {
11968            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11969                // A package with the same name is already installed, though
11970                // it has been renamed to an older name.  The package we
11971                // are trying to install should be installed as an update to
11972                // the existing one, but that has not been requested, so bail.
11973                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11974                        + " without first uninstalling package running as "
11975                        + mSettings.mRenamedPackages.get(pkgName));
11976                return;
11977            }
11978            if (mPackages.containsKey(pkgName)) {
11979                // Don't allow installation over an existing package with the same name.
11980                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11981                        + " without first uninstalling.");
11982                return;
11983            }
11984        }
11985
11986        try {
11987            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
11988                    System.currentTimeMillis(), user);
11989
11990            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11991            // delete the partially installed application. the data directory will have to be
11992            // restored if it was already existing
11993            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11994                // remove package from internal structures.  Note that we want deletePackageX to
11995                // delete the package data and cache directories that it created in
11996                // scanPackageLocked, unless those directories existed before we even tried to
11997                // install.
11998                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11999                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12000                                res.removedInfo, true);
12001            }
12002
12003        } catch (PackageManagerException e) {
12004            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12005        }
12006
12007        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12008    }
12009
12010    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12011        // Can't rotate keys during boot or if sharedUser.
12012        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12013                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12014            return false;
12015        }
12016        // app is using upgradeKeySets; make sure all are valid
12017        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12018        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12019        for (int i = 0; i < upgradeKeySets.length; i++) {
12020            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12021                Slog.wtf(TAG, "Package "
12022                         + (oldPs.name != null ? oldPs.name : "<null>")
12023                         + " contains upgrade-key-set reference to unknown key-set: "
12024                         + upgradeKeySets[i]
12025                         + " reverting to signatures check.");
12026                return false;
12027            }
12028        }
12029        return true;
12030    }
12031
12032    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12033        // Upgrade keysets are being used.  Determine if new package has a superset of the
12034        // required keys.
12035        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12036        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12037        for (int i = 0; i < upgradeKeySets.length; i++) {
12038            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12039            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12040                return true;
12041            }
12042        }
12043        return false;
12044    }
12045
12046    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12047            UserHandle user, String installerPackageName, String volumeUuid,
12048            PackageInstalledInfo res) {
12049        final PackageParser.Package oldPackage;
12050        final String pkgName = pkg.packageName;
12051        final int[] allUsers;
12052        final boolean[] perUserInstalled;
12053
12054        // First find the old package info and check signatures
12055        synchronized(mPackages) {
12056            oldPackage = mPackages.get(pkgName);
12057            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12058            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12059            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12060                if(!checkUpgradeKeySetLP(ps, pkg)) {
12061                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12062                            "New package not signed by keys specified by upgrade-keysets: "
12063                            + pkgName);
12064                    return;
12065                }
12066            } else {
12067                // default to original signature matching
12068                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12069                    != PackageManager.SIGNATURE_MATCH) {
12070                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12071                            "New package has a different signature: " + pkgName);
12072                    return;
12073                }
12074            }
12075
12076            // In case of rollback, remember per-user/profile install state
12077            allUsers = sUserManager.getUserIds();
12078            perUserInstalled = new boolean[allUsers.length];
12079            for (int i = 0; i < allUsers.length; i++) {
12080                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12081            }
12082        }
12083
12084        boolean sysPkg = (isSystemApp(oldPackage));
12085        if (sysPkg) {
12086            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12087                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12088        } else {
12089            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12090                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12091        }
12092    }
12093
12094    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12095            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12096            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12097            String volumeUuid, PackageInstalledInfo res) {
12098        String pkgName = deletedPackage.packageName;
12099        boolean deletedPkg = true;
12100        boolean updatedSettings = false;
12101
12102        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12103                + deletedPackage);
12104        long origUpdateTime;
12105        if (pkg.mExtras != null) {
12106            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12107        } else {
12108            origUpdateTime = 0;
12109        }
12110
12111        // First delete the existing package while retaining the data directory
12112        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12113                res.removedInfo, true)) {
12114            // If the existing package wasn't successfully deleted
12115            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12116            deletedPkg = false;
12117        } else {
12118            // Successfully deleted the old package; proceed with replace.
12119
12120            // If deleted package lived in a container, give users a chance to
12121            // relinquish resources before killing.
12122            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12123                if (DEBUG_INSTALL) {
12124                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12125                }
12126                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12127                final ArrayList<String> pkgList = new ArrayList<String>(1);
12128                pkgList.add(deletedPackage.applicationInfo.packageName);
12129                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12130            }
12131
12132            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12133            try {
12134                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12135                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12136                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12137                        perUserInstalled, res, user);
12138                updatedSettings = true;
12139            } catch (PackageManagerException e) {
12140                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12141            }
12142        }
12143
12144        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12145            // remove package from internal structures.  Note that we want deletePackageX to
12146            // delete the package data and cache directories that it created in
12147            // scanPackageLocked, unless those directories existed before we even tried to
12148            // install.
12149            if(updatedSettings) {
12150                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12151                deletePackageLI(
12152                        pkgName, null, true, allUsers, perUserInstalled,
12153                        PackageManager.DELETE_KEEP_DATA,
12154                                res.removedInfo, true);
12155            }
12156            // Since we failed to install the new package we need to restore the old
12157            // package that we deleted.
12158            if (deletedPkg) {
12159                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12160                File restoreFile = new File(deletedPackage.codePath);
12161                // Parse old package
12162                boolean oldExternal = isExternal(deletedPackage);
12163                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12164                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12165                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12166                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12167                try {
12168                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12169                            null);
12170                } catch (PackageManagerException e) {
12171                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12172                            + e.getMessage());
12173                    return;
12174                }
12175                // Restore of old package succeeded. Update permissions.
12176                // writer
12177                synchronized (mPackages) {
12178                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12179                            UPDATE_PERMISSIONS_ALL);
12180                    // can downgrade to reader
12181                    mSettings.writeLPr();
12182                }
12183                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12184            }
12185        }
12186    }
12187
12188    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12189            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12190            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12191            String volumeUuid, PackageInstalledInfo res) {
12192        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12193                + ", old=" + deletedPackage);
12194        boolean disabledSystem = false;
12195        boolean updatedSettings = false;
12196        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12197        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12198                != 0) {
12199            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12200        }
12201        String packageName = deletedPackage.packageName;
12202        if (packageName == null) {
12203            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12204                    "Attempt to delete null packageName.");
12205            return;
12206        }
12207        PackageParser.Package oldPkg;
12208        PackageSetting oldPkgSetting;
12209        // reader
12210        synchronized (mPackages) {
12211            oldPkg = mPackages.get(packageName);
12212            oldPkgSetting = mSettings.mPackages.get(packageName);
12213            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12214                    (oldPkgSetting == null)) {
12215                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12216                        "Couldn't find package:" + packageName + " information");
12217                return;
12218            }
12219        }
12220
12221        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12222
12223        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12224        res.removedInfo.removedPackage = packageName;
12225        // Remove existing system package
12226        removePackageLI(oldPkgSetting, true);
12227        // writer
12228        synchronized (mPackages) {
12229            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12230            if (!disabledSystem && deletedPackage != null) {
12231                // We didn't need to disable the .apk as a current system package,
12232                // which means we are replacing another update that is already
12233                // installed.  We need to make sure to delete the older one's .apk.
12234                res.removedInfo.args = createInstallArgsForExisting(0,
12235                        deletedPackage.applicationInfo.getCodePath(),
12236                        deletedPackage.applicationInfo.getResourcePath(),
12237                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12238            } else {
12239                res.removedInfo.args = null;
12240            }
12241        }
12242
12243        // Successfully disabled the old package. Now proceed with re-installation
12244        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12245
12246        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12247        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12248
12249        PackageParser.Package newPackage = null;
12250        try {
12251            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12252            if (newPackage.mExtras != null) {
12253                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12254                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12255                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12256
12257                // is the update attempting to change shared user? that isn't going to work...
12258                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12259                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12260                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12261                            + " to " + newPkgSetting.sharedUser);
12262                    updatedSettings = true;
12263                }
12264            }
12265
12266            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12267                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12268                        perUserInstalled, res, user);
12269                updatedSettings = true;
12270            }
12271
12272        } catch (PackageManagerException e) {
12273            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12274        }
12275
12276        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12277            // Re installation failed. Restore old information
12278            // Remove new pkg information
12279            if (newPackage != null) {
12280                removeInstalledPackageLI(newPackage, true);
12281            }
12282            // Add back the old system package
12283            try {
12284                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12285            } catch (PackageManagerException e) {
12286                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12287            }
12288            // Restore the old system information in Settings
12289            synchronized (mPackages) {
12290                if (disabledSystem) {
12291                    mSettings.enableSystemPackageLPw(packageName);
12292                }
12293                if (updatedSettings) {
12294                    mSettings.setInstallerPackageName(packageName,
12295                            oldPkgSetting.installerPackageName);
12296                }
12297                mSettings.writeLPr();
12298            }
12299        }
12300    }
12301
12302    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12303        // Collect all used permissions in the UID
12304        ArraySet<String> usedPermissions = new ArraySet<>();
12305        final int packageCount = su.packages.size();
12306        for (int i = 0; i < packageCount; i++) {
12307            PackageSetting ps = su.packages.valueAt(i);
12308            if (ps.pkg == null) {
12309                continue;
12310            }
12311            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12312            for (int j = 0; j < requestedPermCount; j++) {
12313                String permission = ps.pkg.requestedPermissions.get(j);
12314                BasePermission bp = mSettings.mPermissions.get(permission);
12315                if (bp != null) {
12316                    usedPermissions.add(permission);
12317                }
12318            }
12319        }
12320
12321        PermissionsState permissionsState = su.getPermissionsState();
12322        // Prune install permissions
12323        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12324        final int installPermCount = installPermStates.size();
12325        for (int i = installPermCount - 1; i >= 0;  i--) {
12326            PermissionState permissionState = installPermStates.get(i);
12327            if (!usedPermissions.contains(permissionState.getName())) {
12328                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12329                if (bp != null) {
12330                    permissionsState.revokeInstallPermission(bp);
12331                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12332                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12333                }
12334            }
12335        }
12336
12337        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12338
12339        // Prune runtime permissions
12340        for (int userId : allUserIds) {
12341            List<PermissionState> runtimePermStates = permissionsState
12342                    .getRuntimePermissionStates(userId);
12343            final int runtimePermCount = runtimePermStates.size();
12344            for (int i = runtimePermCount - 1; i >= 0; i--) {
12345                PermissionState permissionState = runtimePermStates.get(i);
12346                if (!usedPermissions.contains(permissionState.getName())) {
12347                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12348                    if (bp != null) {
12349                        permissionsState.revokeRuntimePermission(bp, userId);
12350                        permissionsState.updatePermissionFlags(bp, userId,
12351                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12352                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12353                                runtimePermissionChangedUserIds, userId);
12354                    }
12355                }
12356            }
12357        }
12358
12359        return runtimePermissionChangedUserIds;
12360    }
12361
12362    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12363            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12364            UserHandle user) {
12365        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12366
12367        String pkgName = newPackage.packageName;
12368        synchronized (mPackages) {
12369            //write settings. the installStatus will be incomplete at this stage.
12370            //note that the new package setting would have already been
12371            //added to mPackages. It hasn't been persisted yet.
12372            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12373            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12374            mSettings.writeLPr();
12375            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12376        }
12377
12378        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12379        synchronized (mPackages) {
12380            updatePermissionsLPw(newPackage.packageName, newPackage,
12381                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12382                            ? UPDATE_PERMISSIONS_ALL : 0));
12383            // For system-bundled packages, we assume that installing an upgraded version
12384            // of the package implies that the user actually wants to run that new code,
12385            // so we enable the package.
12386            PackageSetting ps = mSettings.mPackages.get(pkgName);
12387            if (ps != null) {
12388                if (isSystemApp(newPackage)) {
12389                    // NB: implicit assumption that system package upgrades apply to all users
12390                    if (DEBUG_INSTALL) {
12391                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12392                    }
12393                    if (res.origUsers != null) {
12394                        for (int userHandle : res.origUsers) {
12395                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12396                                    userHandle, installerPackageName);
12397                        }
12398                    }
12399                    // Also convey the prior install/uninstall state
12400                    if (allUsers != null && perUserInstalled != null) {
12401                        for (int i = 0; i < allUsers.length; i++) {
12402                            if (DEBUG_INSTALL) {
12403                                Slog.d(TAG, "    user " + allUsers[i]
12404                                        + " => " + perUserInstalled[i]);
12405                            }
12406                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12407                        }
12408                        // these install state changes will be persisted in the
12409                        // upcoming call to mSettings.writeLPr().
12410                    }
12411                }
12412                // It's implied that when a user requests installation, they want the app to be
12413                // installed and enabled.
12414                int userId = user.getIdentifier();
12415                if (userId != UserHandle.USER_ALL) {
12416                    ps.setInstalled(true, userId);
12417                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12418                }
12419            }
12420            res.name = pkgName;
12421            res.uid = newPackage.applicationInfo.uid;
12422            res.pkg = newPackage;
12423            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12424            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12425            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12426            //to update install status
12427            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12428            mSettings.writeLPr();
12429            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12430        }
12431
12432        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12433    }
12434
12435    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12436        try {
12437            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12438            installPackageLI(args, res);
12439        } finally {
12440            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12441        }
12442    }
12443
12444    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12445        final int installFlags = args.installFlags;
12446        final String installerPackageName = args.installerPackageName;
12447        final String volumeUuid = args.volumeUuid;
12448        final File tmpPackageFile = new File(args.getCodePath());
12449        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12450        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12451                || (args.volumeUuid != null));
12452        final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0);
12453        boolean replace = false;
12454        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12455        if (args.move != null) {
12456            // moving a complete application; perfom an initial scan on the new install location
12457            scanFlags |= SCAN_INITIAL;
12458        }
12459        // Result object to be returned
12460        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12461
12462        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12463
12464        // Retrieve PackageSettings and parse package
12465        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12466                | PackageParser.PARSE_ENFORCE_CODE
12467                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12468                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12469                | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0);
12470        PackageParser pp = new PackageParser();
12471        pp.setSeparateProcesses(mSeparateProcesses);
12472        pp.setDisplayMetrics(mMetrics);
12473
12474        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12475        final PackageParser.Package pkg;
12476        try {
12477            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12478        } catch (PackageParserException e) {
12479            res.setError("Failed parse during installPackageLI", e);
12480            return;
12481        } finally {
12482            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12483        }
12484
12485        // Mark that we have an install time CPU ABI override.
12486        pkg.cpuAbiOverride = args.abiOverride;
12487
12488        String pkgName = res.name = pkg.packageName;
12489        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12490            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12491                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12492                return;
12493            }
12494        }
12495
12496        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12497        try {
12498            pp.collectCertificates(pkg, parseFlags);
12499        } catch (PackageParserException e) {
12500            res.setError("Failed collect during installPackageLI", e);
12501            return;
12502        } finally {
12503            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12504        }
12505
12506        /* If the installer passed in a manifest digest, compare it now. */
12507        if (args.manifestDigest != null) {
12508            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest");
12509            try {
12510                pp.collectManifestDigest(pkg);
12511            } catch (PackageParserException e) {
12512                res.setError("Failed collect during installPackageLI", e);
12513                return;
12514            } finally {
12515                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12516            }
12517
12518            if (DEBUG_INSTALL) {
12519                final String parsedManifest = pkg.manifestDigest == null ? "null"
12520                        : pkg.manifestDigest.toString();
12521                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12522                        + parsedManifest);
12523            }
12524
12525            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12526                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12527                return;
12528            }
12529        } else if (DEBUG_INSTALL) {
12530            final String parsedManifest = pkg.manifestDigest == null
12531                    ? "null" : pkg.manifestDigest.toString();
12532            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12533        }
12534
12535        // Get rid of all references to package scan path via parser.
12536        pp = null;
12537        String oldCodePath = null;
12538        boolean systemApp = false;
12539        synchronized (mPackages) {
12540            // Check if installing already existing package
12541            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12542                String oldName = mSettings.mRenamedPackages.get(pkgName);
12543                if (pkg.mOriginalPackages != null
12544                        && pkg.mOriginalPackages.contains(oldName)
12545                        && mPackages.containsKey(oldName)) {
12546                    // This package is derived from an original package,
12547                    // and this device has been updating from that original
12548                    // name.  We must continue using the original name, so
12549                    // rename the new package here.
12550                    pkg.setPackageName(oldName);
12551                    pkgName = pkg.packageName;
12552                    replace = true;
12553                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12554                            + oldName + " pkgName=" + pkgName);
12555                } else if (mPackages.containsKey(pkgName)) {
12556                    // This package, under its official name, already exists
12557                    // on the device; we should replace it.
12558                    replace = true;
12559                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12560                }
12561
12562                // Prevent apps opting out from runtime permissions
12563                if (replace) {
12564                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12565                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12566                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12567                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12568                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12569                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12570                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12571                                        + " doesn't support runtime permissions but the old"
12572                                        + " target SDK " + oldTargetSdk + " does.");
12573                        return;
12574                    }
12575                }
12576            }
12577
12578            PackageSetting ps = mSettings.mPackages.get(pkgName);
12579            if (ps != null) {
12580                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12581
12582                // Quick sanity check that we're signed correctly if updating;
12583                // we'll check this again later when scanning, but we want to
12584                // bail early here before tripping over redefined permissions.
12585                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12586                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12587                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12588                                + pkg.packageName + " upgrade keys do not match the "
12589                                + "previously installed version");
12590                        return;
12591                    }
12592                } else {
12593                    try {
12594                        verifySignaturesLP(ps, pkg);
12595                    } catch (PackageManagerException e) {
12596                        res.setError(e.error, e.getMessage());
12597                        return;
12598                    }
12599                }
12600
12601                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12602                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12603                    systemApp = (ps.pkg.applicationInfo.flags &
12604                            ApplicationInfo.FLAG_SYSTEM) != 0;
12605                }
12606                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12607            }
12608
12609            // Check whether the newly-scanned package wants to define an already-defined perm
12610            int N = pkg.permissions.size();
12611            for (int i = N-1; i >= 0; i--) {
12612                PackageParser.Permission perm = pkg.permissions.get(i);
12613                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12614                if (bp != null) {
12615                    // If the defining package is signed with our cert, it's okay.  This
12616                    // also includes the "updating the same package" case, of course.
12617                    // "updating same package" could also involve key-rotation.
12618                    final boolean sigsOk;
12619                    if (bp.sourcePackage.equals(pkg.packageName)
12620                            && (bp.packageSetting instanceof PackageSetting)
12621                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12622                                    scanFlags))) {
12623                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12624                    } else {
12625                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12626                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12627                    }
12628                    if (!sigsOk) {
12629                        // If the owning package is the system itself, we log but allow
12630                        // install to proceed; we fail the install on all other permission
12631                        // redefinitions.
12632                        if (!bp.sourcePackage.equals("android")) {
12633                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12634                                    + pkg.packageName + " attempting to redeclare permission "
12635                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12636                            res.origPermission = perm.info.name;
12637                            res.origPackage = bp.sourcePackage;
12638                            return;
12639                        } else {
12640                            Slog.w(TAG, "Package " + pkg.packageName
12641                                    + " attempting to redeclare system permission "
12642                                    + perm.info.name + "; ignoring new declaration");
12643                            pkg.permissions.remove(i);
12644                        }
12645                    }
12646                }
12647            }
12648
12649        }
12650
12651        if (systemApp && onExternal) {
12652            // Disable updates to system apps on sdcard
12653            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12654                    "Cannot install updates to system apps on sdcard");
12655            return;
12656        }
12657
12658        if (args.move != null) {
12659            // We did an in-place move, so dex is ready to roll
12660            scanFlags |= SCAN_NO_DEX;
12661            scanFlags |= SCAN_MOVE;
12662
12663            synchronized (mPackages) {
12664                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12665                if (ps == null) {
12666                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12667                            "Missing settings for moved package " + pkgName);
12668                }
12669
12670                // We moved the entire application as-is, so bring over the
12671                // previously derived ABI information.
12672                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12673                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12674            }
12675
12676        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12677            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12678            scanFlags |= SCAN_NO_DEX;
12679
12680            try {
12681                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12682                        true /* extract libs */);
12683            } catch (PackageManagerException pme) {
12684                Slog.e(TAG, "Error deriving application ABI", pme);
12685                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12686                return;
12687            }
12688
12689            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12690            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
12691
12692            int result = mPackageDexOptimizer
12693                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12694                            false /* defer */, false /* inclDependencies */,
12695                            true /*bootComplete*/, quickInstall /*useJit*/);
12696            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12697            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12698                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12699                return;
12700            }
12701        }
12702
12703        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12704            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12705            return;
12706        }
12707
12708        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12709
12710        if (replace) {
12711            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12712                    installerPackageName, volumeUuid, res);
12713        } else {
12714            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12715                    args.user, installerPackageName, volumeUuid, res);
12716        }
12717        synchronized (mPackages) {
12718            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12719            if (ps != null) {
12720                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12721            }
12722        }
12723    }
12724
12725    private void startIntentFilterVerifications(int userId, boolean replacing,
12726            PackageParser.Package pkg) {
12727        if (mIntentFilterVerifierComponent == null) {
12728            Slog.w(TAG, "No IntentFilter verification will not be done as "
12729                    + "there is no IntentFilterVerifier available!");
12730            return;
12731        }
12732
12733        final int verifierUid = getPackageUid(
12734                mIntentFilterVerifierComponent.getPackageName(),
12735                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
12736
12737        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12738        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12739        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12740        mHandler.sendMessage(msg);
12741    }
12742
12743    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12744            PackageParser.Package pkg) {
12745        int size = pkg.activities.size();
12746        if (size == 0) {
12747            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12748                    "No activity, so no need to verify any IntentFilter!");
12749            return;
12750        }
12751
12752        final boolean hasDomainURLs = hasDomainURLs(pkg);
12753        if (!hasDomainURLs) {
12754            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12755                    "No domain URLs, so no need to verify any IntentFilter!");
12756            return;
12757        }
12758
12759        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12760                + " if any IntentFilter from the " + size
12761                + " Activities needs verification ...");
12762
12763        int count = 0;
12764        final String packageName = pkg.packageName;
12765
12766        synchronized (mPackages) {
12767            // If this is a new install and we see that we've already run verification for this
12768            // package, we have nothing to do: it means the state was restored from backup.
12769            if (!replacing) {
12770                IntentFilterVerificationInfo ivi =
12771                        mSettings.getIntentFilterVerificationLPr(packageName);
12772                if (ivi != null) {
12773                    if (DEBUG_DOMAIN_VERIFICATION) {
12774                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12775                                + ivi.getStatusString());
12776                    }
12777                    return;
12778                }
12779            }
12780
12781            // If any filters need to be verified, then all need to be.
12782            boolean needToVerify = false;
12783            for (PackageParser.Activity a : pkg.activities) {
12784                for (ActivityIntentInfo filter : a.intents) {
12785                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12786                        if (DEBUG_DOMAIN_VERIFICATION) {
12787                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12788                        }
12789                        needToVerify = true;
12790                        break;
12791                    }
12792                }
12793            }
12794
12795            if (needToVerify) {
12796                final int verificationId = mIntentFilterVerificationToken++;
12797                for (PackageParser.Activity a : pkg.activities) {
12798                    for (ActivityIntentInfo filter : a.intents) {
12799                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12800                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12801                                    "Verification needed for IntentFilter:" + filter.toString());
12802                            mIntentFilterVerifier.addOneIntentFilterVerification(
12803                                    verifierUid, userId, verificationId, filter, packageName);
12804                            count++;
12805                        }
12806                    }
12807                }
12808            }
12809        }
12810
12811        if (count > 0) {
12812            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12813                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12814                    +  " for userId:" + userId);
12815            mIntentFilterVerifier.startVerifications(userId);
12816        } else {
12817            if (DEBUG_DOMAIN_VERIFICATION) {
12818                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12819            }
12820        }
12821    }
12822
12823    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12824        final ComponentName cn  = filter.activity.getComponentName();
12825        final String packageName = cn.getPackageName();
12826
12827        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12828                packageName);
12829        if (ivi == null) {
12830            return true;
12831        }
12832        int status = ivi.getStatus();
12833        switch (status) {
12834            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12835            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12836                return true;
12837
12838            default:
12839                // Nothing to do
12840                return false;
12841        }
12842    }
12843
12844    private static boolean isMultiArch(PackageSetting ps) {
12845        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12846    }
12847
12848    private static boolean isMultiArch(ApplicationInfo info) {
12849        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12850    }
12851
12852    private static boolean isExternal(PackageParser.Package pkg) {
12853        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12854    }
12855
12856    private static boolean isExternal(PackageSetting ps) {
12857        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12858    }
12859
12860    private static boolean isExternal(ApplicationInfo info) {
12861        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12862    }
12863
12864    private static boolean isSystemApp(PackageParser.Package pkg) {
12865        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12866    }
12867
12868    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12869        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12870    }
12871
12872    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12873        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12874    }
12875
12876    private static boolean isSystemApp(PackageSetting ps) {
12877        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12878    }
12879
12880    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12881        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12882    }
12883
12884    private int packageFlagsToInstallFlags(PackageSetting ps) {
12885        int installFlags = 0;
12886        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12887            // This existing package was an external ASEC install when we have
12888            // the external flag without a UUID
12889            installFlags |= PackageManager.INSTALL_EXTERNAL;
12890        }
12891        if (ps.isForwardLocked()) {
12892            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12893        }
12894        return installFlags;
12895    }
12896
12897    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
12898        if (isExternal(pkg)) {
12899            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12900                return StorageManager.UUID_PRIMARY_PHYSICAL;
12901            } else {
12902                return pkg.volumeUuid;
12903            }
12904        } else {
12905            return StorageManager.UUID_PRIVATE_INTERNAL;
12906        }
12907    }
12908
12909    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12910        if (isExternal(pkg)) {
12911            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12912                return mSettings.getExternalVersion();
12913            } else {
12914                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12915            }
12916        } else {
12917            return mSettings.getInternalVersion();
12918        }
12919    }
12920
12921    private void deleteTempPackageFiles() {
12922        final FilenameFilter filter = new FilenameFilter() {
12923            public boolean accept(File dir, String name) {
12924                return name.startsWith("vmdl") && name.endsWith(".tmp");
12925            }
12926        };
12927        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12928            file.delete();
12929        }
12930    }
12931
12932    @Override
12933    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12934            int flags) {
12935        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12936                flags);
12937    }
12938
12939    @Override
12940    public void deletePackage(final String packageName,
12941            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12942        mContext.enforceCallingOrSelfPermission(
12943                android.Manifest.permission.DELETE_PACKAGES, null);
12944        Preconditions.checkNotNull(packageName);
12945        Preconditions.checkNotNull(observer);
12946        final int uid = Binder.getCallingUid();
12947        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
12948        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
12949        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
12950            mContext.enforceCallingPermission(
12951                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12952                    "deletePackage for user " + userId);
12953        }
12954
12955        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12956            try {
12957                observer.onPackageDeleted(packageName,
12958                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12959            } catch (RemoteException re) {
12960            }
12961            return;
12962        }
12963
12964        for (int currentUserId : users) {
12965            if (getBlockUninstallForUser(packageName, currentUserId)) {
12966                try {
12967                    observer.onPackageDeleted(packageName,
12968                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
12969                } catch (RemoteException re) {
12970                }
12971                return;
12972            }
12973        }
12974
12975        if (DEBUG_REMOVE) {
12976            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12977        }
12978        // Queue up an async operation since the package deletion may take a little while.
12979        mHandler.post(new Runnable() {
12980            public void run() {
12981                mHandler.removeCallbacks(this);
12982                final int returnCode = deletePackageX(packageName, userId, flags);
12983                try {
12984                    observer.onPackageDeleted(packageName, returnCode, null);
12985                } catch (RemoteException e) {
12986                    Log.i(TAG, "Observer no longer exists.");
12987                } //end catch
12988            } //end run
12989        });
12990    }
12991
12992    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12993        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12994                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12995        try {
12996            if (dpm != null) {
12997                // Does the package contains the device owner?
12998                if (dpm.isDeviceOwnerPackage(packageName)) {
12999                    return true;
13000                }
13001                // Does it contain a device admin for any user?
13002                int[] users;
13003                if (userId == UserHandle.USER_ALL) {
13004                    users = sUserManager.getUserIds();
13005                } else {
13006                    users = new int[]{userId};
13007                }
13008                for (int i = 0; i < users.length; ++i) {
13009                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13010                        return true;
13011                    }
13012                }
13013            }
13014        } catch (RemoteException e) {
13015        }
13016        return false;
13017    }
13018
13019    /**
13020     *  This method is an internal method that could be get invoked either
13021     *  to delete an installed package or to clean up a failed installation.
13022     *  After deleting an installed package, a broadcast is sent to notify any
13023     *  listeners that the package has been installed. For cleaning up a failed
13024     *  installation, the broadcast is not necessary since the package's
13025     *  installation wouldn't have sent the initial broadcast either
13026     *  The key steps in deleting a package are
13027     *  deleting the package information in internal structures like mPackages,
13028     *  deleting the packages base directories through installd
13029     *  updating mSettings to reflect current status
13030     *  persisting settings for later use
13031     *  sending a broadcast if necessary
13032     */
13033    private int deletePackageX(String packageName, int userId, int flags) {
13034        final PackageRemovedInfo info = new PackageRemovedInfo();
13035        final boolean res;
13036
13037        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13038                ? UserHandle.ALL : new UserHandle(userId);
13039
13040        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13041            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13042            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13043        }
13044
13045        boolean removedForAllUsers = false;
13046        boolean systemUpdate = false;
13047
13048        // for the uninstall-updates case and restricted profiles, remember the per-
13049        // userhandle installed state
13050        int[] allUsers;
13051        boolean[] perUserInstalled;
13052        synchronized (mPackages) {
13053            PackageSetting ps = mSettings.mPackages.get(packageName);
13054            allUsers = sUserManager.getUserIds();
13055            perUserInstalled = new boolean[allUsers.length];
13056            for (int i = 0; i < allUsers.length; i++) {
13057                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13058            }
13059        }
13060
13061        synchronized (mInstallLock) {
13062            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13063            res = deletePackageLI(packageName, removeForUser,
13064                    true, allUsers, perUserInstalled,
13065                    flags | REMOVE_CHATTY, info, true);
13066            systemUpdate = info.isRemovedPackageSystemUpdate;
13067            if (res && !systemUpdate && mPackages.get(packageName) == null) {
13068                removedForAllUsers = true;
13069            }
13070            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13071                    + " removedForAllUsers=" + removedForAllUsers);
13072        }
13073
13074        if (res) {
13075            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13076
13077            // If the removed package was a system update, the old system package
13078            // was re-enabled; we need to broadcast this information
13079            if (systemUpdate) {
13080                Bundle extras = new Bundle(1);
13081                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13082                        ? info.removedAppId : info.uid);
13083                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13084
13085                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13086                        extras, null, null, null);
13087                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13088                        extras, null, null, null);
13089                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13090                        null, packageName, null, null);
13091            }
13092        }
13093        // Force a gc here.
13094        Runtime.getRuntime().gc();
13095        // Delete the resources here after sending the broadcast to let
13096        // other processes clean up before deleting resources.
13097        if (info.args != null) {
13098            synchronized (mInstallLock) {
13099                info.args.doPostDeleteLI(true);
13100            }
13101        }
13102
13103        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13104    }
13105
13106    class PackageRemovedInfo {
13107        String removedPackage;
13108        int uid = -1;
13109        int removedAppId = -1;
13110        int[] removedUsers = null;
13111        boolean isRemovedPackageSystemUpdate = false;
13112        // Clean up resources deleted packages.
13113        InstallArgs args = null;
13114
13115        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13116            Bundle extras = new Bundle(1);
13117            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13118            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13119            if (replacing) {
13120                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13121            }
13122            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13123            if (removedPackage != null) {
13124                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13125                        extras, null, null, removedUsers);
13126                if (fullRemove && !replacing) {
13127                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13128                            extras, null, null, removedUsers);
13129                }
13130            }
13131            if (removedAppId >= 0) {
13132                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
13133                        removedUsers);
13134            }
13135        }
13136    }
13137
13138    /*
13139     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13140     * flag is not set, the data directory is removed as well.
13141     * make sure this flag is set for partially installed apps. If not its meaningless to
13142     * delete a partially installed application.
13143     */
13144    private void removePackageDataLI(PackageSetting ps,
13145            int[] allUserHandles, boolean[] perUserInstalled,
13146            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13147        String packageName = ps.name;
13148        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13149        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13150        // Retrieve object to delete permissions for shared user later on
13151        final PackageSetting deletedPs;
13152        // reader
13153        synchronized (mPackages) {
13154            deletedPs = mSettings.mPackages.get(packageName);
13155            if (outInfo != null) {
13156                outInfo.removedPackage = packageName;
13157                outInfo.removedUsers = deletedPs != null
13158                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13159                        : null;
13160            }
13161        }
13162        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13163            removeDataDirsLI(ps.volumeUuid, packageName);
13164            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13165        }
13166        // writer
13167        synchronized (mPackages) {
13168            if (deletedPs != null) {
13169                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13170                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13171                    clearDefaultBrowserIfNeeded(packageName);
13172                    if (outInfo != null) {
13173                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13174                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13175                    }
13176                    updatePermissionsLPw(deletedPs.name, null, 0);
13177                    if (deletedPs.sharedUser != null) {
13178                        // Remove permissions associated with package. Since runtime
13179                        // permissions are per user we have to kill the removed package
13180                        // or packages running under the shared user of the removed
13181                        // package if revoking the permissions requested only by the removed
13182                        // package is successful and this causes a change in gids.
13183                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13184                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13185                                    userId);
13186                            if (userIdToKill == UserHandle.USER_ALL
13187                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13188                                // If gids changed for this user, kill all affected packages.
13189                                mHandler.post(new Runnable() {
13190                                    @Override
13191                                    public void run() {
13192                                        // This has to happen with no lock held.
13193                                        killApplication(deletedPs.name, deletedPs.appId,
13194                                                KILL_APP_REASON_GIDS_CHANGED);
13195                                    }
13196                                });
13197                                break;
13198                            }
13199                        }
13200                    }
13201                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13202                }
13203                // make sure to preserve per-user disabled state if this removal was just
13204                // a downgrade of a system app to the factory package
13205                if (allUserHandles != null && perUserInstalled != null) {
13206                    if (DEBUG_REMOVE) {
13207                        Slog.d(TAG, "Propagating install state across downgrade");
13208                    }
13209                    for (int i = 0; i < allUserHandles.length; i++) {
13210                        if (DEBUG_REMOVE) {
13211                            Slog.d(TAG, "    user " + allUserHandles[i]
13212                                    + " => " + perUserInstalled[i]);
13213                        }
13214                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13215                    }
13216                }
13217            }
13218            // can downgrade to reader
13219            if (writeSettings) {
13220                // Save settings now
13221                mSettings.writeLPr();
13222            }
13223        }
13224        if (outInfo != null) {
13225            // A user ID was deleted here. Go through all users and remove it
13226            // from KeyStore.
13227            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13228        }
13229    }
13230
13231    static boolean locationIsPrivileged(File path) {
13232        try {
13233            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13234                    .getCanonicalPath();
13235            return path.getCanonicalPath().startsWith(privilegedAppDir);
13236        } catch (IOException e) {
13237            Slog.e(TAG, "Unable to access code path " + path);
13238        }
13239        return false;
13240    }
13241
13242    /*
13243     * Tries to delete system package.
13244     */
13245    private boolean deleteSystemPackageLI(PackageSetting newPs,
13246            int[] allUserHandles, boolean[] perUserInstalled,
13247            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13248        final boolean applyUserRestrictions
13249                = (allUserHandles != null) && (perUserInstalled != null);
13250        PackageSetting disabledPs = null;
13251        // Confirm if the system package has been updated
13252        // An updated system app can be deleted. This will also have to restore
13253        // the system pkg from system partition
13254        // reader
13255        synchronized (mPackages) {
13256            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13257        }
13258        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13259                + " disabledPs=" + disabledPs);
13260        if (disabledPs == null) {
13261            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13262            return false;
13263        } else if (DEBUG_REMOVE) {
13264            Slog.d(TAG, "Deleting system pkg from data partition");
13265        }
13266        if (DEBUG_REMOVE) {
13267            if (applyUserRestrictions) {
13268                Slog.d(TAG, "Remembering install states:");
13269                for (int i = 0; i < allUserHandles.length; i++) {
13270                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13271                }
13272            }
13273        }
13274        // Delete the updated package
13275        outInfo.isRemovedPackageSystemUpdate = true;
13276        if (disabledPs.versionCode < newPs.versionCode) {
13277            // Delete data for downgrades
13278            flags &= ~PackageManager.DELETE_KEEP_DATA;
13279        } else {
13280            // Preserve data by setting flag
13281            flags |= PackageManager.DELETE_KEEP_DATA;
13282        }
13283        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13284                allUserHandles, perUserInstalled, outInfo, writeSettings);
13285        if (!ret) {
13286            return false;
13287        }
13288        // writer
13289        synchronized (mPackages) {
13290            // Reinstate the old system package
13291            mSettings.enableSystemPackageLPw(newPs.name);
13292            // Remove any native libraries from the upgraded package.
13293            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13294        }
13295        // Install the system package
13296        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13297        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13298        if (locationIsPrivileged(disabledPs.codePath)) {
13299            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13300        }
13301
13302        final PackageParser.Package newPkg;
13303        try {
13304            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13305        } catch (PackageManagerException e) {
13306            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13307            return false;
13308        }
13309
13310        // writer
13311        synchronized (mPackages) {
13312            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13313
13314            // Propagate the permissions state as we do not want to drop on the floor
13315            // runtime permissions. The update permissions method below will take
13316            // care of removing obsolete permissions and grant install permissions.
13317            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13318            updatePermissionsLPw(newPkg.packageName, newPkg,
13319                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13320
13321            if (applyUserRestrictions) {
13322                if (DEBUG_REMOVE) {
13323                    Slog.d(TAG, "Propagating install state across reinstall");
13324                }
13325                for (int i = 0; i < allUserHandles.length; i++) {
13326                    if (DEBUG_REMOVE) {
13327                        Slog.d(TAG, "    user " + allUserHandles[i]
13328                                + " => " + perUserInstalled[i]);
13329                    }
13330                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13331
13332                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13333                }
13334                // Regardless of writeSettings we need to ensure that this restriction
13335                // state propagation is persisted
13336                mSettings.writeAllUsersPackageRestrictionsLPr();
13337            }
13338            // can downgrade to reader here
13339            if (writeSettings) {
13340                mSettings.writeLPr();
13341            }
13342        }
13343        return true;
13344    }
13345
13346    private boolean deleteInstalledPackageLI(PackageSetting ps,
13347            boolean deleteCodeAndResources, int flags,
13348            int[] allUserHandles, boolean[] perUserInstalled,
13349            PackageRemovedInfo outInfo, boolean writeSettings) {
13350        if (outInfo != null) {
13351            outInfo.uid = ps.appId;
13352        }
13353
13354        // Delete package data from internal structures and also remove data if flag is set
13355        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13356
13357        // Delete application code and resources
13358        if (deleteCodeAndResources && (outInfo != null)) {
13359            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13360                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13361            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13362        }
13363        return true;
13364    }
13365
13366    @Override
13367    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13368            int userId) {
13369        mContext.enforceCallingOrSelfPermission(
13370                android.Manifest.permission.DELETE_PACKAGES, null);
13371        synchronized (mPackages) {
13372            PackageSetting ps = mSettings.mPackages.get(packageName);
13373            if (ps == null) {
13374                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13375                return false;
13376            }
13377            if (!ps.getInstalled(userId)) {
13378                // Can't block uninstall for an app that is not installed or enabled.
13379                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13380                return false;
13381            }
13382            ps.setBlockUninstall(blockUninstall, userId);
13383            mSettings.writePackageRestrictionsLPr(userId);
13384        }
13385        return true;
13386    }
13387
13388    @Override
13389    public boolean getBlockUninstallForUser(String packageName, int userId) {
13390        synchronized (mPackages) {
13391            PackageSetting ps = mSettings.mPackages.get(packageName);
13392            if (ps == null) {
13393                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13394                return false;
13395            }
13396            return ps.getBlockUninstall(userId);
13397        }
13398    }
13399
13400    /*
13401     * This method handles package deletion in general
13402     */
13403    private boolean deletePackageLI(String packageName, UserHandle user,
13404            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13405            int flags, PackageRemovedInfo outInfo,
13406            boolean writeSettings) {
13407        if (packageName == null) {
13408            Slog.w(TAG, "Attempt to delete null packageName.");
13409            return false;
13410        }
13411        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13412        PackageSetting ps;
13413        boolean dataOnly = false;
13414        int removeUser = -1;
13415        int appId = -1;
13416        synchronized (mPackages) {
13417            ps = mSettings.mPackages.get(packageName);
13418            if (ps == null) {
13419                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13420                return false;
13421            }
13422            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13423                    && user.getIdentifier() != UserHandle.USER_ALL) {
13424                // The caller is asking that the package only be deleted for a single
13425                // user.  To do this, we just mark its uninstalled state and delete
13426                // its data.  If this is a system app, we only allow this to happen if
13427                // they have set the special DELETE_SYSTEM_APP which requests different
13428                // semantics than normal for uninstalling system apps.
13429                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13430                final int userId = user.getIdentifier();
13431                ps.setUserState(userId,
13432                        COMPONENT_ENABLED_STATE_DEFAULT,
13433                        false, //installed
13434                        true,  //stopped
13435                        true,  //notLaunched
13436                        false, //hidden
13437                        null, null, null,
13438                        false, // blockUninstall
13439                        ps.readUserState(userId).domainVerificationStatus, 0);
13440                if (!isSystemApp(ps)) {
13441                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13442                        // Other user still have this package installed, so all
13443                        // we need to do is clear this user's data and save that
13444                        // it is uninstalled.
13445                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13446                        removeUser = user.getIdentifier();
13447                        appId = ps.appId;
13448                        scheduleWritePackageRestrictionsLocked(removeUser);
13449                    } else {
13450                        // We need to set it back to 'installed' so the uninstall
13451                        // broadcasts will be sent correctly.
13452                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13453                        ps.setInstalled(true, user.getIdentifier());
13454                    }
13455                } else {
13456                    // This is a system app, so we assume that the
13457                    // other users still have this package installed, so all
13458                    // we need to do is clear this user's data and save that
13459                    // it is uninstalled.
13460                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13461                    removeUser = user.getIdentifier();
13462                    appId = ps.appId;
13463                    scheduleWritePackageRestrictionsLocked(removeUser);
13464                }
13465            }
13466        }
13467
13468        if (removeUser >= 0) {
13469            // From above, we determined that we are deleting this only
13470            // for a single user.  Continue the work here.
13471            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13472            if (outInfo != null) {
13473                outInfo.removedPackage = packageName;
13474                outInfo.removedAppId = appId;
13475                outInfo.removedUsers = new int[] {removeUser};
13476            }
13477            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13478            removeKeystoreDataIfNeeded(removeUser, appId);
13479            schedulePackageCleaning(packageName, removeUser, false);
13480            synchronized (mPackages) {
13481                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13482                    scheduleWritePackageRestrictionsLocked(removeUser);
13483                }
13484                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13485            }
13486            return true;
13487        }
13488
13489        if (dataOnly) {
13490            // Delete application data first
13491            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13492            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13493            return true;
13494        }
13495
13496        boolean ret = false;
13497        if (isSystemApp(ps)) {
13498            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13499            // When an updated system application is deleted we delete the existing resources as well and
13500            // fall back to existing code in system partition
13501            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13502                    flags, outInfo, writeSettings);
13503        } else {
13504            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13505            // Kill application pre-emptively especially for apps on sd.
13506            killApplication(packageName, ps.appId, "uninstall pkg");
13507            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13508                    allUserHandles, perUserInstalled,
13509                    outInfo, writeSettings);
13510        }
13511
13512        return ret;
13513    }
13514
13515    private final class ClearStorageConnection implements ServiceConnection {
13516        IMediaContainerService mContainerService;
13517
13518        @Override
13519        public void onServiceConnected(ComponentName name, IBinder service) {
13520            synchronized (this) {
13521                mContainerService = IMediaContainerService.Stub.asInterface(service);
13522                notifyAll();
13523            }
13524        }
13525
13526        @Override
13527        public void onServiceDisconnected(ComponentName name) {
13528        }
13529    }
13530
13531    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13532        final boolean mounted;
13533        if (Environment.isExternalStorageEmulated()) {
13534            mounted = true;
13535        } else {
13536            final String status = Environment.getExternalStorageState();
13537
13538            mounted = status.equals(Environment.MEDIA_MOUNTED)
13539                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13540        }
13541
13542        if (!mounted) {
13543            return;
13544        }
13545
13546        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13547        int[] users;
13548        if (userId == UserHandle.USER_ALL) {
13549            users = sUserManager.getUserIds();
13550        } else {
13551            users = new int[] { userId };
13552        }
13553        final ClearStorageConnection conn = new ClearStorageConnection();
13554        if (mContext.bindServiceAsUser(
13555                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13556            try {
13557                for (int curUser : users) {
13558                    long timeout = SystemClock.uptimeMillis() + 5000;
13559                    synchronized (conn) {
13560                        long now = SystemClock.uptimeMillis();
13561                        while (conn.mContainerService == null && now < timeout) {
13562                            try {
13563                                conn.wait(timeout - now);
13564                            } catch (InterruptedException e) {
13565                            }
13566                        }
13567                    }
13568                    if (conn.mContainerService == null) {
13569                        return;
13570                    }
13571
13572                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13573                    clearDirectory(conn.mContainerService,
13574                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13575                    if (allData) {
13576                        clearDirectory(conn.mContainerService,
13577                                userEnv.buildExternalStorageAppDataDirs(packageName));
13578                        clearDirectory(conn.mContainerService,
13579                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13580                    }
13581                }
13582            } finally {
13583                mContext.unbindService(conn);
13584            }
13585        }
13586    }
13587
13588    @Override
13589    public void clearApplicationUserData(final String packageName,
13590            final IPackageDataObserver observer, final int userId) {
13591        mContext.enforceCallingOrSelfPermission(
13592                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13593        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13594        // Queue up an async operation since the package deletion may take a little while.
13595        mHandler.post(new Runnable() {
13596            public void run() {
13597                mHandler.removeCallbacks(this);
13598                final boolean succeeded;
13599                synchronized (mInstallLock) {
13600                    succeeded = clearApplicationUserDataLI(packageName, userId);
13601                }
13602                clearExternalStorageDataSync(packageName, userId, true);
13603                if (succeeded) {
13604                    // invoke DeviceStorageMonitor's update method to clear any notifications
13605                    DeviceStorageMonitorInternal
13606                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13607                    if (dsm != null) {
13608                        dsm.checkMemory();
13609                    }
13610                }
13611                if(observer != null) {
13612                    try {
13613                        observer.onRemoveCompleted(packageName, succeeded);
13614                    } catch (RemoteException e) {
13615                        Log.i(TAG, "Observer no longer exists.");
13616                    }
13617                } //end if observer
13618            } //end run
13619        });
13620    }
13621
13622    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13623        if (packageName == null) {
13624            Slog.w(TAG, "Attempt to delete null packageName.");
13625            return false;
13626        }
13627
13628        // Try finding details about the requested package
13629        PackageParser.Package pkg;
13630        synchronized (mPackages) {
13631            pkg = mPackages.get(packageName);
13632            if (pkg == null) {
13633                final PackageSetting ps = mSettings.mPackages.get(packageName);
13634                if (ps != null) {
13635                    pkg = ps.pkg;
13636                }
13637            }
13638
13639            if (pkg == null) {
13640                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13641                return false;
13642            }
13643
13644            PackageSetting ps = (PackageSetting) pkg.mExtras;
13645            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13646        }
13647
13648        // Always delete data directories for package, even if we found no other
13649        // record of app. This helps users recover from UID mismatches without
13650        // resorting to a full data wipe.
13651        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13652        if (retCode < 0) {
13653            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13654            return false;
13655        }
13656
13657        final int appId = pkg.applicationInfo.uid;
13658        removeKeystoreDataIfNeeded(userId, appId);
13659
13660        // Create a native library symlink only if we have native libraries
13661        // and if the native libraries are 32 bit libraries. We do not provide
13662        // this symlink for 64 bit libraries.
13663        if (pkg.applicationInfo.primaryCpuAbi != null &&
13664                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13665            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13666            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13667                    nativeLibPath, userId) < 0) {
13668                Slog.w(TAG, "Failed linking native library dir");
13669                return false;
13670            }
13671        }
13672
13673        return true;
13674    }
13675
13676    /**
13677     * Reverts user permission state changes (permissions and flags) in
13678     * all packages for a given user.
13679     *
13680     * @param userId The device user for which to do a reset.
13681     */
13682    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13683        final int packageCount = mPackages.size();
13684        for (int i = 0; i < packageCount; i++) {
13685            PackageParser.Package pkg = mPackages.valueAt(i);
13686            PackageSetting ps = (PackageSetting) pkg.mExtras;
13687            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13688        }
13689    }
13690
13691    /**
13692     * Reverts user permission state changes (permissions and flags).
13693     *
13694     * @param ps The package for which to reset.
13695     * @param userId The device user for which to do a reset.
13696     */
13697    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13698            final PackageSetting ps, final int userId) {
13699        if (ps.pkg == null) {
13700            return;
13701        }
13702
13703        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13704                | FLAG_PERMISSION_USER_FIXED
13705                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13706
13707        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13708                | FLAG_PERMISSION_POLICY_FIXED;
13709
13710        boolean writeInstallPermissions = false;
13711        boolean writeRuntimePermissions = false;
13712
13713        final int permissionCount = ps.pkg.requestedPermissions.size();
13714        for (int i = 0; i < permissionCount; i++) {
13715            String permission = ps.pkg.requestedPermissions.get(i);
13716
13717            BasePermission bp = mSettings.mPermissions.get(permission);
13718            if (bp == null) {
13719                continue;
13720            }
13721
13722            // If shared user we just reset the state to which only this app contributed.
13723            if (ps.sharedUser != null) {
13724                boolean used = false;
13725                final int packageCount = ps.sharedUser.packages.size();
13726                for (int j = 0; j < packageCount; j++) {
13727                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13728                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13729                            && pkg.pkg.requestedPermissions.contains(permission)) {
13730                        used = true;
13731                        break;
13732                    }
13733                }
13734                if (used) {
13735                    continue;
13736                }
13737            }
13738
13739            PermissionsState permissionsState = ps.getPermissionsState();
13740
13741            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13742
13743            // Always clear the user settable flags.
13744            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13745                    bp.name) != null;
13746            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13747                if (hasInstallState) {
13748                    writeInstallPermissions = true;
13749                } else {
13750                    writeRuntimePermissions = true;
13751                }
13752            }
13753
13754            // Below is only runtime permission handling.
13755            if (!bp.isRuntime()) {
13756                continue;
13757            }
13758
13759            // Never clobber system or policy.
13760            if ((oldFlags & policyOrSystemFlags) != 0) {
13761                continue;
13762            }
13763
13764            // If this permission was granted by default, make sure it is.
13765            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13766                if (permissionsState.grantRuntimePermission(bp, userId)
13767                        != PERMISSION_OPERATION_FAILURE) {
13768                    writeRuntimePermissions = true;
13769                }
13770            } else {
13771                // Otherwise, reset the permission.
13772                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13773                switch (revokeResult) {
13774                    case PERMISSION_OPERATION_SUCCESS: {
13775                        writeRuntimePermissions = true;
13776                    } break;
13777
13778                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13779                        writeRuntimePermissions = true;
13780                        final int appId = ps.appId;
13781                        mHandler.post(new Runnable() {
13782                            @Override
13783                            public void run() {
13784                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13785                            }
13786                        });
13787                    } break;
13788                }
13789            }
13790        }
13791
13792        // Synchronously write as we are taking permissions away.
13793        if (writeRuntimePermissions) {
13794            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13795        }
13796
13797        // Synchronously write as we are taking permissions away.
13798        if (writeInstallPermissions) {
13799            mSettings.writeLPr();
13800        }
13801    }
13802
13803    /**
13804     * Remove entries from the keystore daemon. Will only remove it if the
13805     * {@code appId} is valid.
13806     */
13807    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13808        if (appId < 0) {
13809            return;
13810        }
13811
13812        final KeyStore keyStore = KeyStore.getInstance();
13813        if (keyStore != null) {
13814            if (userId == UserHandle.USER_ALL) {
13815                for (final int individual : sUserManager.getUserIds()) {
13816                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13817                }
13818            } else {
13819                keyStore.clearUid(UserHandle.getUid(userId, appId));
13820            }
13821        } else {
13822            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13823        }
13824    }
13825
13826    @Override
13827    public void deleteApplicationCacheFiles(final String packageName,
13828            final IPackageDataObserver observer) {
13829        mContext.enforceCallingOrSelfPermission(
13830                android.Manifest.permission.DELETE_CACHE_FILES, null);
13831        // Queue up an async operation since the package deletion may take a little while.
13832        final int userId = UserHandle.getCallingUserId();
13833        mHandler.post(new Runnable() {
13834            public void run() {
13835                mHandler.removeCallbacks(this);
13836                final boolean succeded;
13837                synchronized (mInstallLock) {
13838                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13839                }
13840                clearExternalStorageDataSync(packageName, userId, false);
13841                if (observer != null) {
13842                    try {
13843                        observer.onRemoveCompleted(packageName, succeded);
13844                    } catch (RemoteException e) {
13845                        Log.i(TAG, "Observer no longer exists.");
13846                    }
13847                } //end if observer
13848            } //end run
13849        });
13850    }
13851
13852    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13853        if (packageName == null) {
13854            Slog.w(TAG, "Attempt to delete null packageName.");
13855            return false;
13856        }
13857        PackageParser.Package p;
13858        synchronized (mPackages) {
13859            p = mPackages.get(packageName);
13860        }
13861        if (p == null) {
13862            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13863            return false;
13864        }
13865        final ApplicationInfo applicationInfo = p.applicationInfo;
13866        if (applicationInfo == null) {
13867            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13868            return false;
13869        }
13870        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13871        if (retCode < 0) {
13872            Slog.w(TAG, "Couldn't remove cache files for package: "
13873                       + packageName + " u" + userId);
13874            return false;
13875        }
13876        return true;
13877    }
13878
13879    @Override
13880    public void getPackageSizeInfo(final String packageName, int userHandle,
13881            final IPackageStatsObserver observer) {
13882        mContext.enforceCallingOrSelfPermission(
13883                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13884        if (packageName == null) {
13885            throw new IllegalArgumentException("Attempt to get size of null packageName");
13886        }
13887
13888        PackageStats stats = new PackageStats(packageName, userHandle);
13889
13890        /*
13891         * Queue up an async operation since the package measurement may take a
13892         * little while.
13893         */
13894        Message msg = mHandler.obtainMessage(INIT_COPY);
13895        msg.obj = new MeasureParams(stats, observer);
13896        mHandler.sendMessage(msg);
13897    }
13898
13899    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13900            PackageStats pStats) {
13901        if (packageName == null) {
13902            Slog.w(TAG, "Attempt to get size of null packageName.");
13903            return false;
13904        }
13905        PackageParser.Package p;
13906        boolean dataOnly = false;
13907        String libDirRoot = null;
13908        String asecPath = null;
13909        PackageSetting ps = null;
13910        synchronized (mPackages) {
13911            p = mPackages.get(packageName);
13912            ps = mSettings.mPackages.get(packageName);
13913            if(p == null) {
13914                dataOnly = true;
13915                if((ps == null) || (ps.pkg == null)) {
13916                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13917                    return false;
13918                }
13919                p = ps.pkg;
13920            }
13921            if (ps != null) {
13922                libDirRoot = ps.legacyNativeLibraryPathString;
13923            }
13924            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
13925                final long token = Binder.clearCallingIdentity();
13926                try {
13927                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13928                    if (secureContainerId != null) {
13929                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13930                    }
13931                } finally {
13932                    Binder.restoreCallingIdentity(token);
13933                }
13934            }
13935        }
13936        String publicSrcDir = null;
13937        if(!dataOnly) {
13938            final ApplicationInfo applicationInfo = p.applicationInfo;
13939            if (applicationInfo == null) {
13940                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13941                return false;
13942            }
13943            if (p.isForwardLocked()) {
13944                publicSrcDir = applicationInfo.getBaseResourcePath();
13945            }
13946        }
13947        // TODO: extend to measure size of split APKs
13948        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13949        // not just the first level.
13950        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13951        // just the primary.
13952        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13953
13954        String apkPath;
13955        File packageDir = new File(p.codePath);
13956
13957        if (packageDir.isDirectory() && p.canHaveOatDir()) {
13958            apkPath = packageDir.getAbsolutePath();
13959            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
13960            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
13961                libDirRoot = null;
13962            }
13963        } else {
13964            apkPath = p.baseCodePath;
13965        }
13966
13967        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
13968                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13969        if (res < 0) {
13970            return false;
13971        }
13972
13973        // Fix-up for forward-locked applications in ASEC containers.
13974        if (!isExternal(p)) {
13975            pStats.codeSize += pStats.externalCodeSize;
13976            pStats.externalCodeSize = 0L;
13977        }
13978
13979        return true;
13980    }
13981
13982
13983    @Override
13984    public void addPackageToPreferred(String packageName) {
13985        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13986    }
13987
13988    @Override
13989    public void removePackageFromPreferred(String packageName) {
13990        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13991    }
13992
13993    @Override
13994    public List<PackageInfo> getPreferredPackages(int flags) {
13995        return new ArrayList<PackageInfo>();
13996    }
13997
13998    private int getUidTargetSdkVersionLockedLPr(int uid) {
13999        Object obj = mSettings.getUserIdLPr(uid);
14000        if (obj instanceof SharedUserSetting) {
14001            final SharedUserSetting sus = (SharedUserSetting) obj;
14002            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14003            final Iterator<PackageSetting> it = sus.packages.iterator();
14004            while (it.hasNext()) {
14005                final PackageSetting ps = it.next();
14006                if (ps.pkg != null) {
14007                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14008                    if (v < vers) vers = v;
14009                }
14010            }
14011            return vers;
14012        } else if (obj instanceof PackageSetting) {
14013            final PackageSetting ps = (PackageSetting) obj;
14014            if (ps.pkg != null) {
14015                return ps.pkg.applicationInfo.targetSdkVersion;
14016            }
14017        }
14018        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14019    }
14020
14021    @Override
14022    public void addPreferredActivity(IntentFilter filter, int match,
14023            ComponentName[] set, ComponentName activity, int userId) {
14024        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14025                "Adding preferred");
14026    }
14027
14028    private void addPreferredActivityInternal(IntentFilter filter, int match,
14029            ComponentName[] set, ComponentName activity, boolean always, int userId,
14030            String opname) {
14031        // writer
14032        int callingUid = Binder.getCallingUid();
14033        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14034        if (filter.countActions() == 0) {
14035            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14036            return;
14037        }
14038        synchronized (mPackages) {
14039            if (mContext.checkCallingOrSelfPermission(
14040                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14041                    != PackageManager.PERMISSION_GRANTED) {
14042                if (getUidTargetSdkVersionLockedLPr(callingUid)
14043                        < Build.VERSION_CODES.FROYO) {
14044                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14045                            + callingUid);
14046                    return;
14047                }
14048                mContext.enforceCallingOrSelfPermission(
14049                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14050            }
14051
14052            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14053            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14054                    + userId + ":");
14055            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14056            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14057            scheduleWritePackageRestrictionsLocked(userId);
14058        }
14059    }
14060
14061    @Override
14062    public void replacePreferredActivity(IntentFilter filter, int match,
14063            ComponentName[] set, ComponentName activity, int userId) {
14064        if (filter.countActions() != 1) {
14065            throw new IllegalArgumentException(
14066                    "replacePreferredActivity expects filter to have only 1 action.");
14067        }
14068        if (filter.countDataAuthorities() != 0
14069                || filter.countDataPaths() != 0
14070                || filter.countDataSchemes() > 1
14071                || filter.countDataTypes() != 0) {
14072            throw new IllegalArgumentException(
14073                    "replacePreferredActivity expects filter to have no data authorities, " +
14074                    "paths, or types; and at most one scheme.");
14075        }
14076
14077        final int callingUid = Binder.getCallingUid();
14078        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14079        synchronized (mPackages) {
14080            if (mContext.checkCallingOrSelfPermission(
14081                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14082                    != PackageManager.PERMISSION_GRANTED) {
14083                if (getUidTargetSdkVersionLockedLPr(callingUid)
14084                        < Build.VERSION_CODES.FROYO) {
14085                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14086                            + Binder.getCallingUid());
14087                    return;
14088                }
14089                mContext.enforceCallingOrSelfPermission(
14090                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14091            }
14092
14093            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14094            if (pir != null) {
14095                // Get all of the existing entries that exactly match this filter.
14096                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14097                if (existing != null && existing.size() == 1) {
14098                    PreferredActivity cur = existing.get(0);
14099                    if (DEBUG_PREFERRED) {
14100                        Slog.i(TAG, "Checking replace of preferred:");
14101                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14102                        if (!cur.mPref.mAlways) {
14103                            Slog.i(TAG, "  -- CUR; not mAlways!");
14104                        } else {
14105                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14106                            Slog.i(TAG, "  -- CUR: mSet="
14107                                    + Arrays.toString(cur.mPref.mSetComponents));
14108                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14109                            Slog.i(TAG, "  -- NEW: mMatch="
14110                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14111                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14112                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14113                        }
14114                    }
14115                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14116                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14117                            && cur.mPref.sameSet(set)) {
14118                        // Setting the preferred activity to what it happens to be already
14119                        if (DEBUG_PREFERRED) {
14120                            Slog.i(TAG, "Replacing with same preferred activity "
14121                                    + cur.mPref.mShortComponent + " for user "
14122                                    + userId + ":");
14123                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14124                        }
14125                        return;
14126                    }
14127                }
14128
14129                if (existing != null) {
14130                    if (DEBUG_PREFERRED) {
14131                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14132                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14133                    }
14134                    for (int i = 0; i < existing.size(); i++) {
14135                        PreferredActivity pa = existing.get(i);
14136                        if (DEBUG_PREFERRED) {
14137                            Slog.i(TAG, "Removing existing preferred activity "
14138                                    + pa.mPref.mComponent + ":");
14139                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14140                        }
14141                        pir.removeFilter(pa);
14142                    }
14143                }
14144            }
14145            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14146                    "Replacing preferred");
14147        }
14148    }
14149
14150    @Override
14151    public void clearPackagePreferredActivities(String packageName) {
14152        final int uid = Binder.getCallingUid();
14153        // writer
14154        synchronized (mPackages) {
14155            PackageParser.Package pkg = mPackages.get(packageName);
14156            if (pkg == null || pkg.applicationInfo.uid != uid) {
14157                if (mContext.checkCallingOrSelfPermission(
14158                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14159                        != PackageManager.PERMISSION_GRANTED) {
14160                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14161                            < Build.VERSION_CODES.FROYO) {
14162                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14163                                + Binder.getCallingUid());
14164                        return;
14165                    }
14166                    mContext.enforceCallingOrSelfPermission(
14167                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14168                }
14169            }
14170
14171            int user = UserHandle.getCallingUserId();
14172            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14173                scheduleWritePackageRestrictionsLocked(user);
14174            }
14175        }
14176    }
14177
14178    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14179    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14180        ArrayList<PreferredActivity> removed = null;
14181        boolean changed = false;
14182        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14183            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14184            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14185            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14186                continue;
14187            }
14188            Iterator<PreferredActivity> it = pir.filterIterator();
14189            while (it.hasNext()) {
14190                PreferredActivity pa = it.next();
14191                // Mark entry for removal only if it matches the package name
14192                // and the entry is of type "always".
14193                if (packageName == null ||
14194                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14195                                && pa.mPref.mAlways)) {
14196                    if (removed == null) {
14197                        removed = new ArrayList<PreferredActivity>();
14198                    }
14199                    removed.add(pa);
14200                }
14201            }
14202            if (removed != null) {
14203                for (int j=0; j<removed.size(); j++) {
14204                    PreferredActivity pa = removed.get(j);
14205                    pir.removeFilter(pa);
14206                }
14207                changed = true;
14208            }
14209        }
14210        return changed;
14211    }
14212
14213    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14214    private void clearIntentFilterVerificationsLPw(int userId) {
14215        final int packageCount = mPackages.size();
14216        for (int i = 0; i < packageCount; i++) {
14217            PackageParser.Package pkg = mPackages.valueAt(i);
14218            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14219        }
14220    }
14221
14222    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14223    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14224        if (userId == UserHandle.USER_ALL) {
14225            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14226                    sUserManager.getUserIds())) {
14227                for (int oneUserId : sUserManager.getUserIds()) {
14228                    scheduleWritePackageRestrictionsLocked(oneUserId);
14229                }
14230            }
14231        } else {
14232            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14233                scheduleWritePackageRestrictionsLocked(userId);
14234            }
14235        }
14236    }
14237
14238    void clearDefaultBrowserIfNeeded(String packageName) {
14239        for (int oneUserId : sUserManager.getUserIds()) {
14240            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14241            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14242            if (packageName.equals(defaultBrowserPackageName)) {
14243                setDefaultBrowserPackageName(null, oneUserId);
14244            }
14245        }
14246    }
14247
14248    @Override
14249    public void resetApplicationPreferences(int userId) {
14250        mContext.enforceCallingOrSelfPermission(
14251                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14252        // writer
14253        synchronized (mPackages) {
14254            final long identity = Binder.clearCallingIdentity();
14255            try {
14256                clearPackagePreferredActivitiesLPw(null, userId);
14257                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14258                // TODO: We have to reset the default SMS and Phone. This requires
14259                // significant refactoring to keep all default apps in the package
14260                // manager (cleaner but more work) or have the services provide
14261                // callbacks to the package manager to request a default app reset.
14262                applyFactoryDefaultBrowserLPw(userId);
14263                clearIntentFilterVerificationsLPw(userId);
14264                primeDomainVerificationsLPw(userId);
14265                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14266                scheduleWritePackageRestrictionsLocked(userId);
14267            } finally {
14268                Binder.restoreCallingIdentity(identity);
14269            }
14270        }
14271    }
14272
14273    @Override
14274    public int getPreferredActivities(List<IntentFilter> outFilters,
14275            List<ComponentName> outActivities, String packageName) {
14276
14277        int num = 0;
14278        final int userId = UserHandle.getCallingUserId();
14279        // reader
14280        synchronized (mPackages) {
14281            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14282            if (pir != null) {
14283                final Iterator<PreferredActivity> it = pir.filterIterator();
14284                while (it.hasNext()) {
14285                    final PreferredActivity pa = it.next();
14286                    if (packageName == null
14287                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14288                                    && pa.mPref.mAlways)) {
14289                        if (outFilters != null) {
14290                            outFilters.add(new IntentFilter(pa));
14291                        }
14292                        if (outActivities != null) {
14293                            outActivities.add(pa.mPref.mComponent);
14294                        }
14295                    }
14296                }
14297            }
14298        }
14299
14300        return num;
14301    }
14302
14303    @Override
14304    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14305            int userId) {
14306        int callingUid = Binder.getCallingUid();
14307        if (callingUid != Process.SYSTEM_UID) {
14308            throw new SecurityException(
14309                    "addPersistentPreferredActivity can only be run by the system");
14310        }
14311        if (filter.countActions() == 0) {
14312            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14313            return;
14314        }
14315        synchronized (mPackages) {
14316            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14317                    " :");
14318            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14319            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14320                    new PersistentPreferredActivity(filter, activity));
14321            scheduleWritePackageRestrictionsLocked(userId);
14322        }
14323    }
14324
14325    @Override
14326    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14327        int callingUid = Binder.getCallingUid();
14328        if (callingUid != Process.SYSTEM_UID) {
14329            throw new SecurityException(
14330                    "clearPackagePersistentPreferredActivities can only be run by the system");
14331        }
14332        ArrayList<PersistentPreferredActivity> removed = null;
14333        boolean changed = false;
14334        synchronized (mPackages) {
14335            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14336                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14337                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14338                        .valueAt(i);
14339                if (userId != thisUserId) {
14340                    continue;
14341                }
14342                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14343                while (it.hasNext()) {
14344                    PersistentPreferredActivity ppa = it.next();
14345                    // Mark entry for removal only if it matches the package name.
14346                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14347                        if (removed == null) {
14348                            removed = new ArrayList<PersistentPreferredActivity>();
14349                        }
14350                        removed.add(ppa);
14351                    }
14352                }
14353                if (removed != null) {
14354                    for (int j=0; j<removed.size(); j++) {
14355                        PersistentPreferredActivity ppa = removed.get(j);
14356                        ppir.removeFilter(ppa);
14357                    }
14358                    changed = true;
14359                }
14360            }
14361
14362            if (changed) {
14363                scheduleWritePackageRestrictionsLocked(userId);
14364            }
14365        }
14366    }
14367
14368    /**
14369     * Common machinery for picking apart a restored XML blob and passing
14370     * it to a caller-supplied functor to be applied to the running system.
14371     */
14372    private void restoreFromXml(XmlPullParser parser, int userId,
14373            String expectedStartTag, BlobXmlRestorer functor)
14374            throws IOException, XmlPullParserException {
14375        int type;
14376        while ((type = parser.next()) != XmlPullParser.START_TAG
14377                && type != XmlPullParser.END_DOCUMENT) {
14378        }
14379        if (type != XmlPullParser.START_TAG) {
14380            // oops didn't find a start tag?!
14381            if (DEBUG_BACKUP) {
14382                Slog.e(TAG, "Didn't find start tag during restore");
14383            }
14384            return;
14385        }
14386
14387        // this is supposed to be TAG_PREFERRED_BACKUP
14388        if (!expectedStartTag.equals(parser.getName())) {
14389            if (DEBUG_BACKUP) {
14390                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14391            }
14392            return;
14393        }
14394
14395        // skip interfering stuff, then we're aligned with the backing implementation
14396        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14397        functor.apply(parser, userId);
14398    }
14399
14400    private interface BlobXmlRestorer {
14401        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14402    }
14403
14404    /**
14405     * Non-Binder method, support for the backup/restore mechanism: write the
14406     * full set of preferred activities in its canonical XML format.  Returns the
14407     * XML output as a byte array, or null if there is none.
14408     */
14409    @Override
14410    public byte[] getPreferredActivityBackup(int userId) {
14411        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14412            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14413        }
14414
14415        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14416        try {
14417            final XmlSerializer serializer = new FastXmlSerializer();
14418            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14419            serializer.startDocument(null, true);
14420            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14421
14422            synchronized (mPackages) {
14423                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14424            }
14425
14426            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14427            serializer.endDocument();
14428            serializer.flush();
14429        } catch (Exception e) {
14430            if (DEBUG_BACKUP) {
14431                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14432            }
14433            return null;
14434        }
14435
14436        return dataStream.toByteArray();
14437    }
14438
14439    @Override
14440    public void restorePreferredActivities(byte[] backup, int userId) {
14441        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14442            throw new SecurityException("Only the system may call restorePreferredActivities()");
14443        }
14444
14445        try {
14446            final XmlPullParser parser = Xml.newPullParser();
14447            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14448            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14449                    new BlobXmlRestorer() {
14450                        @Override
14451                        public void apply(XmlPullParser parser, int userId)
14452                                throws XmlPullParserException, IOException {
14453                            synchronized (mPackages) {
14454                                mSettings.readPreferredActivitiesLPw(parser, userId);
14455                            }
14456                        }
14457                    } );
14458        } catch (Exception e) {
14459            if (DEBUG_BACKUP) {
14460                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14461            }
14462        }
14463    }
14464
14465    /**
14466     * Non-Binder method, support for the backup/restore mechanism: write the
14467     * default browser (etc) settings in its canonical XML format.  Returns the default
14468     * browser XML representation as a byte array, or null if there is none.
14469     */
14470    @Override
14471    public byte[] getDefaultAppsBackup(int userId) {
14472        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14473            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14474        }
14475
14476        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14477        try {
14478            final XmlSerializer serializer = new FastXmlSerializer();
14479            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14480            serializer.startDocument(null, true);
14481            serializer.startTag(null, TAG_DEFAULT_APPS);
14482
14483            synchronized (mPackages) {
14484                mSettings.writeDefaultAppsLPr(serializer, userId);
14485            }
14486
14487            serializer.endTag(null, TAG_DEFAULT_APPS);
14488            serializer.endDocument();
14489            serializer.flush();
14490        } catch (Exception e) {
14491            if (DEBUG_BACKUP) {
14492                Slog.e(TAG, "Unable to write default apps for backup", e);
14493            }
14494            return null;
14495        }
14496
14497        return dataStream.toByteArray();
14498    }
14499
14500    @Override
14501    public void restoreDefaultApps(byte[] backup, int userId) {
14502        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14503            throw new SecurityException("Only the system may call restoreDefaultApps()");
14504        }
14505
14506        try {
14507            final XmlPullParser parser = Xml.newPullParser();
14508            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14509            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14510                    new BlobXmlRestorer() {
14511                        @Override
14512                        public void apply(XmlPullParser parser, int userId)
14513                                throws XmlPullParserException, IOException {
14514                            synchronized (mPackages) {
14515                                mSettings.readDefaultAppsLPw(parser, userId);
14516                            }
14517                        }
14518                    } );
14519        } catch (Exception e) {
14520            if (DEBUG_BACKUP) {
14521                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14522            }
14523        }
14524    }
14525
14526    @Override
14527    public byte[] getIntentFilterVerificationBackup(int userId) {
14528        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14529            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14530        }
14531
14532        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14533        try {
14534            final XmlSerializer serializer = new FastXmlSerializer();
14535            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14536            serializer.startDocument(null, true);
14537            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14538
14539            synchronized (mPackages) {
14540                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14541            }
14542
14543            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14544            serializer.endDocument();
14545            serializer.flush();
14546        } catch (Exception e) {
14547            if (DEBUG_BACKUP) {
14548                Slog.e(TAG, "Unable to write default apps for backup", e);
14549            }
14550            return null;
14551        }
14552
14553        return dataStream.toByteArray();
14554    }
14555
14556    @Override
14557    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14558        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14559            throw new SecurityException("Only the system may call restorePreferredActivities()");
14560        }
14561
14562        try {
14563            final XmlPullParser parser = Xml.newPullParser();
14564            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14565            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14566                    new BlobXmlRestorer() {
14567                        @Override
14568                        public void apply(XmlPullParser parser, int userId)
14569                                throws XmlPullParserException, IOException {
14570                            synchronized (mPackages) {
14571                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14572                                mSettings.writeLPr();
14573                            }
14574                        }
14575                    } );
14576        } catch (Exception e) {
14577            if (DEBUG_BACKUP) {
14578                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14579            }
14580        }
14581    }
14582
14583    @Override
14584    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14585            int sourceUserId, int targetUserId, int flags) {
14586        mContext.enforceCallingOrSelfPermission(
14587                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14588        int callingUid = Binder.getCallingUid();
14589        enforceOwnerRights(ownerPackage, callingUid);
14590        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14591        if (intentFilter.countActions() == 0) {
14592            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14593            return;
14594        }
14595        synchronized (mPackages) {
14596            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14597                    ownerPackage, targetUserId, flags);
14598            CrossProfileIntentResolver resolver =
14599                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14600            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14601            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14602            if (existing != null) {
14603                int size = existing.size();
14604                for (int i = 0; i < size; i++) {
14605                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14606                        return;
14607                    }
14608                }
14609            }
14610            resolver.addFilter(newFilter);
14611            scheduleWritePackageRestrictionsLocked(sourceUserId);
14612        }
14613    }
14614
14615    @Override
14616    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14617        mContext.enforceCallingOrSelfPermission(
14618                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14619        int callingUid = Binder.getCallingUid();
14620        enforceOwnerRights(ownerPackage, callingUid);
14621        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14622        synchronized (mPackages) {
14623            CrossProfileIntentResolver resolver =
14624                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14625            ArraySet<CrossProfileIntentFilter> set =
14626                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14627            for (CrossProfileIntentFilter filter : set) {
14628                if (filter.getOwnerPackage().equals(ownerPackage)) {
14629                    resolver.removeFilter(filter);
14630                }
14631            }
14632            scheduleWritePackageRestrictionsLocked(sourceUserId);
14633        }
14634    }
14635
14636    // Enforcing that callingUid is owning pkg on userId
14637    private void enforceOwnerRights(String pkg, int callingUid) {
14638        // The system owns everything.
14639        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14640            return;
14641        }
14642        int callingUserId = UserHandle.getUserId(callingUid);
14643        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14644        if (pi == null) {
14645            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14646                    + callingUserId);
14647        }
14648        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14649            throw new SecurityException("Calling uid " + callingUid
14650                    + " does not own package " + pkg);
14651        }
14652    }
14653
14654    @Override
14655    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14656        Intent intent = new Intent(Intent.ACTION_MAIN);
14657        intent.addCategory(Intent.CATEGORY_HOME);
14658
14659        final int callingUserId = UserHandle.getCallingUserId();
14660        List<ResolveInfo> list = queryIntentActivities(intent, null,
14661                PackageManager.GET_META_DATA, callingUserId);
14662        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14663                true, false, false, callingUserId);
14664
14665        allHomeCandidates.clear();
14666        if (list != null) {
14667            for (ResolveInfo ri : list) {
14668                allHomeCandidates.add(ri);
14669            }
14670        }
14671        return (preferred == null || preferred.activityInfo == null)
14672                ? null
14673                : new ComponentName(preferred.activityInfo.packageName,
14674                        preferred.activityInfo.name);
14675    }
14676
14677    @Override
14678    public void setApplicationEnabledSetting(String appPackageName,
14679            int newState, int flags, int userId, String callingPackage) {
14680        if (!sUserManager.exists(userId)) return;
14681        if (callingPackage == null) {
14682            callingPackage = Integer.toString(Binder.getCallingUid());
14683        }
14684        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14685    }
14686
14687    @Override
14688    public void setComponentEnabledSetting(ComponentName componentName,
14689            int newState, int flags, int userId) {
14690        if (!sUserManager.exists(userId)) return;
14691        setEnabledSetting(componentName.getPackageName(),
14692                componentName.getClassName(), newState, flags, userId, null);
14693    }
14694
14695    private void setEnabledSetting(final String packageName, String className, int newState,
14696            final int flags, int userId, String callingPackage) {
14697        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14698              || newState == COMPONENT_ENABLED_STATE_ENABLED
14699              || newState == COMPONENT_ENABLED_STATE_DISABLED
14700              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14701              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14702            throw new IllegalArgumentException("Invalid new component state: "
14703                    + newState);
14704        }
14705        PackageSetting pkgSetting;
14706        final int uid = Binder.getCallingUid();
14707        final int permission = mContext.checkCallingOrSelfPermission(
14708                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14709        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14710        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14711        boolean sendNow = false;
14712        boolean isApp = (className == null);
14713        String componentName = isApp ? packageName : className;
14714        int packageUid = -1;
14715        ArrayList<String> components;
14716
14717        // writer
14718        synchronized (mPackages) {
14719            pkgSetting = mSettings.mPackages.get(packageName);
14720            if (pkgSetting == null) {
14721                if (className == null) {
14722                    throw new IllegalArgumentException(
14723                            "Unknown package: " + packageName);
14724                }
14725                throw new IllegalArgumentException(
14726                        "Unknown component: " + packageName
14727                        + "/" + className);
14728            }
14729            // Allow root and verify that userId is not being specified by a different user
14730            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14731                throw new SecurityException(
14732                        "Permission Denial: attempt to change component state from pid="
14733                        + Binder.getCallingPid()
14734                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14735            }
14736            if (className == null) {
14737                // We're dealing with an application/package level state change
14738                if (pkgSetting.getEnabled(userId) == newState) {
14739                    // Nothing to do
14740                    return;
14741                }
14742                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14743                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14744                    // Don't care about who enables an app.
14745                    callingPackage = null;
14746                }
14747                pkgSetting.setEnabled(newState, userId, callingPackage);
14748                // pkgSetting.pkg.mSetEnabled = newState;
14749            } else {
14750                // We're dealing with a component level state change
14751                // First, verify that this is a valid class name.
14752                PackageParser.Package pkg = pkgSetting.pkg;
14753                if (pkg == null || !pkg.hasComponentClassName(className)) {
14754                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14755                        throw new IllegalArgumentException("Component class " + className
14756                                + " does not exist in " + packageName);
14757                    } else {
14758                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14759                                + className + " does not exist in " + packageName);
14760                    }
14761                }
14762                switch (newState) {
14763                case COMPONENT_ENABLED_STATE_ENABLED:
14764                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14765                        return;
14766                    }
14767                    break;
14768                case COMPONENT_ENABLED_STATE_DISABLED:
14769                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14770                        return;
14771                    }
14772                    break;
14773                case COMPONENT_ENABLED_STATE_DEFAULT:
14774                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14775                        return;
14776                    }
14777                    break;
14778                default:
14779                    Slog.e(TAG, "Invalid new component state: " + newState);
14780                    return;
14781                }
14782            }
14783            scheduleWritePackageRestrictionsLocked(userId);
14784            components = mPendingBroadcasts.get(userId, packageName);
14785            final boolean newPackage = components == null;
14786            if (newPackage) {
14787                components = new ArrayList<String>();
14788            }
14789            if (!components.contains(componentName)) {
14790                components.add(componentName);
14791            }
14792            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14793                sendNow = true;
14794                // Purge entry from pending broadcast list if another one exists already
14795                // since we are sending one right away.
14796                mPendingBroadcasts.remove(userId, packageName);
14797            } else {
14798                if (newPackage) {
14799                    mPendingBroadcasts.put(userId, packageName, components);
14800                }
14801                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14802                    // Schedule a message
14803                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14804                }
14805            }
14806        }
14807
14808        long callingId = Binder.clearCallingIdentity();
14809        try {
14810            if (sendNow) {
14811                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14812                sendPackageChangedBroadcast(packageName,
14813                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14814            }
14815        } finally {
14816            Binder.restoreCallingIdentity(callingId);
14817        }
14818    }
14819
14820    private void sendPackageChangedBroadcast(String packageName,
14821            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14822        if (DEBUG_INSTALL)
14823            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14824                    + componentNames);
14825        Bundle extras = new Bundle(4);
14826        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14827        String nameList[] = new String[componentNames.size()];
14828        componentNames.toArray(nameList);
14829        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14830        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14831        extras.putInt(Intent.EXTRA_UID, packageUid);
14832        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14833                new int[] {UserHandle.getUserId(packageUid)});
14834    }
14835
14836    @Override
14837    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14838        if (!sUserManager.exists(userId)) return;
14839        final int uid = Binder.getCallingUid();
14840        final int permission = mContext.checkCallingOrSelfPermission(
14841                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14842        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14843        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14844        // writer
14845        synchronized (mPackages) {
14846            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14847                    allowedByPermission, uid, userId)) {
14848                scheduleWritePackageRestrictionsLocked(userId);
14849            }
14850        }
14851    }
14852
14853    @Override
14854    public String getInstallerPackageName(String packageName) {
14855        // reader
14856        synchronized (mPackages) {
14857            return mSettings.getInstallerPackageNameLPr(packageName);
14858        }
14859    }
14860
14861    @Override
14862    public int getApplicationEnabledSetting(String packageName, int userId) {
14863        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14864        int uid = Binder.getCallingUid();
14865        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14866        // reader
14867        synchronized (mPackages) {
14868            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14869        }
14870    }
14871
14872    @Override
14873    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14874        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14875        int uid = Binder.getCallingUid();
14876        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14877        // reader
14878        synchronized (mPackages) {
14879            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14880        }
14881    }
14882
14883    @Override
14884    public void enterSafeMode() {
14885        enforceSystemOrRoot("Only the system can request entering safe mode");
14886
14887        if (!mSystemReady) {
14888            mSafeMode = true;
14889        }
14890    }
14891
14892    @Override
14893    public void systemReady() {
14894        mSystemReady = true;
14895
14896        // Read the compatibilty setting when the system is ready.
14897        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14898                mContext.getContentResolver(),
14899                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14900        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14901        if (DEBUG_SETTINGS) {
14902            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14903        }
14904
14905        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14906
14907        synchronized (mPackages) {
14908            // Verify that all of the preferred activity components actually
14909            // exist.  It is possible for applications to be updated and at
14910            // that point remove a previously declared activity component that
14911            // had been set as a preferred activity.  We try to clean this up
14912            // the next time we encounter that preferred activity, but it is
14913            // possible for the user flow to never be able to return to that
14914            // situation so here we do a sanity check to make sure we haven't
14915            // left any junk around.
14916            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14917            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14918                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14919                removed.clear();
14920                for (PreferredActivity pa : pir.filterSet()) {
14921                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14922                        removed.add(pa);
14923                    }
14924                }
14925                if (removed.size() > 0) {
14926                    for (int r=0; r<removed.size(); r++) {
14927                        PreferredActivity pa = removed.get(r);
14928                        Slog.w(TAG, "Removing dangling preferred activity: "
14929                                + pa.mPref.mComponent);
14930                        pir.removeFilter(pa);
14931                    }
14932                    mSettings.writePackageRestrictionsLPr(
14933                            mSettings.mPreferredActivities.keyAt(i));
14934                }
14935            }
14936
14937            for (int userId : UserManagerService.getInstance().getUserIds()) {
14938                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14939                    grantPermissionsUserIds = ArrayUtils.appendInt(
14940                            grantPermissionsUserIds, userId);
14941                }
14942            }
14943        }
14944        sUserManager.systemReady();
14945
14946        // If we upgraded grant all default permissions before kicking off.
14947        for (int userId : grantPermissionsUserIds) {
14948            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14949        }
14950
14951        // Kick off any messages waiting for system ready
14952        if (mPostSystemReadyMessages != null) {
14953            for (Message msg : mPostSystemReadyMessages) {
14954                msg.sendToTarget();
14955            }
14956            mPostSystemReadyMessages = null;
14957        }
14958
14959        // Watch for external volumes that come and go over time
14960        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14961        storage.registerListener(mStorageListener);
14962
14963        mInstallerService.systemReady();
14964        mPackageDexOptimizer.systemReady();
14965
14966        MountServiceInternal mountServiceInternal = LocalServices.getService(
14967                MountServiceInternal.class);
14968        mountServiceInternal.addExternalStoragePolicy(
14969                new MountServiceInternal.ExternalStorageMountPolicy() {
14970            @Override
14971            public int getMountMode(int uid, String packageName) {
14972                if (Process.isIsolated(uid)) {
14973                    return Zygote.MOUNT_EXTERNAL_NONE;
14974                }
14975                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14976                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14977                }
14978                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14979                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14980                }
14981                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14982                    return Zygote.MOUNT_EXTERNAL_READ;
14983                }
14984                return Zygote.MOUNT_EXTERNAL_WRITE;
14985            }
14986
14987            @Override
14988            public boolean hasExternalStorage(int uid, String packageName) {
14989                return true;
14990            }
14991        });
14992    }
14993
14994    @Override
14995    public boolean isSafeMode() {
14996        return mSafeMode;
14997    }
14998
14999    @Override
15000    public boolean hasSystemUidErrors() {
15001        return mHasSystemUidErrors;
15002    }
15003
15004    static String arrayToString(int[] array) {
15005        StringBuffer buf = new StringBuffer(128);
15006        buf.append('[');
15007        if (array != null) {
15008            for (int i=0; i<array.length; i++) {
15009                if (i > 0) buf.append(", ");
15010                buf.append(array[i]);
15011            }
15012        }
15013        buf.append(']');
15014        return buf.toString();
15015    }
15016
15017    static class DumpState {
15018        public static final int DUMP_LIBS = 1 << 0;
15019        public static final int DUMP_FEATURES = 1 << 1;
15020        public static final int DUMP_RESOLVERS = 1 << 2;
15021        public static final int DUMP_PERMISSIONS = 1 << 3;
15022        public static final int DUMP_PACKAGES = 1 << 4;
15023        public static final int DUMP_SHARED_USERS = 1 << 5;
15024        public static final int DUMP_MESSAGES = 1 << 6;
15025        public static final int DUMP_PROVIDERS = 1 << 7;
15026        public static final int DUMP_VERIFIERS = 1 << 8;
15027        public static final int DUMP_PREFERRED = 1 << 9;
15028        public static final int DUMP_PREFERRED_XML = 1 << 10;
15029        public static final int DUMP_KEYSETS = 1 << 11;
15030        public static final int DUMP_VERSION = 1 << 12;
15031        public static final int DUMP_INSTALLS = 1 << 13;
15032        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
15033        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
15034
15035        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15036
15037        private int mTypes;
15038
15039        private int mOptions;
15040
15041        private boolean mTitlePrinted;
15042
15043        private SharedUserSetting mSharedUser;
15044
15045        public boolean isDumping(int type) {
15046            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15047                return true;
15048            }
15049
15050            return (mTypes & type) != 0;
15051        }
15052
15053        public void setDump(int type) {
15054            mTypes |= type;
15055        }
15056
15057        public boolean isOptionEnabled(int option) {
15058            return (mOptions & option) != 0;
15059        }
15060
15061        public void setOptionEnabled(int option) {
15062            mOptions |= option;
15063        }
15064
15065        public boolean onTitlePrinted() {
15066            final boolean printed = mTitlePrinted;
15067            mTitlePrinted = true;
15068            return printed;
15069        }
15070
15071        public boolean getTitlePrinted() {
15072            return mTitlePrinted;
15073        }
15074
15075        public void setTitlePrinted(boolean enabled) {
15076            mTitlePrinted = enabled;
15077        }
15078
15079        public SharedUserSetting getSharedUser() {
15080            return mSharedUser;
15081        }
15082
15083        public void setSharedUser(SharedUserSetting user) {
15084            mSharedUser = user;
15085        }
15086    }
15087
15088    @Override
15089    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15090            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15091        (new PackageManagerShellCommand(this)).exec(
15092                this, in, out, err, args, resultReceiver);
15093    }
15094
15095    @Override
15096    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15097        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15098                != PackageManager.PERMISSION_GRANTED) {
15099            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15100                    + Binder.getCallingPid()
15101                    + ", uid=" + Binder.getCallingUid()
15102                    + " without permission "
15103                    + android.Manifest.permission.DUMP);
15104            return;
15105        }
15106
15107        DumpState dumpState = new DumpState();
15108        boolean fullPreferred = false;
15109        boolean checkin = false;
15110
15111        String packageName = null;
15112        ArraySet<String> permissionNames = null;
15113
15114        int opti = 0;
15115        while (opti < args.length) {
15116            String opt = args[opti];
15117            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15118                break;
15119            }
15120            opti++;
15121
15122            if ("-a".equals(opt)) {
15123                // Right now we only know how to print all.
15124            } else if ("-h".equals(opt)) {
15125                pw.println("Package manager dump options:");
15126                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15127                pw.println("    --checkin: dump for a checkin");
15128                pw.println("    -f: print details of intent filters");
15129                pw.println("    -h: print this help");
15130                pw.println("  cmd may be one of:");
15131                pw.println("    l[ibraries]: list known shared libraries");
15132                pw.println("    f[ibraries]: list device features");
15133                pw.println("    k[eysets]: print known keysets");
15134                pw.println("    r[esolvers]: dump intent resolvers");
15135                pw.println("    perm[issions]: dump permissions");
15136                pw.println("    permission [name ...]: dump declaration and use of given permission");
15137                pw.println("    pref[erred]: print preferred package settings");
15138                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15139                pw.println("    prov[iders]: dump content providers");
15140                pw.println("    p[ackages]: dump installed packages");
15141                pw.println("    s[hared-users]: dump shared user IDs");
15142                pw.println("    m[essages]: print collected runtime messages");
15143                pw.println("    v[erifiers]: print package verifier info");
15144                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15145                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15146                pw.println("    version: print database version info");
15147                pw.println("    write: write current settings now");
15148                pw.println("    installs: details about install sessions");
15149                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15150                pw.println("    <package.name>: info about given package");
15151                return;
15152            } else if ("--checkin".equals(opt)) {
15153                checkin = true;
15154            } else if ("-f".equals(opt)) {
15155                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15156            } else {
15157                pw.println("Unknown argument: " + opt + "; use -h for help");
15158            }
15159        }
15160
15161        // Is the caller requesting to dump a particular piece of data?
15162        if (opti < args.length) {
15163            String cmd = args[opti];
15164            opti++;
15165            // Is this a package name?
15166            if ("android".equals(cmd) || cmd.contains(".")) {
15167                packageName = cmd;
15168                // When dumping a single package, we always dump all of its
15169                // filter information since the amount of data will be reasonable.
15170                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15171            } else if ("check-permission".equals(cmd)) {
15172                if (opti >= args.length) {
15173                    pw.println("Error: check-permission missing permission argument");
15174                    return;
15175                }
15176                String perm = args[opti];
15177                opti++;
15178                if (opti >= args.length) {
15179                    pw.println("Error: check-permission missing package argument");
15180                    return;
15181                }
15182                String pkg = args[opti];
15183                opti++;
15184                int user = UserHandle.getUserId(Binder.getCallingUid());
15185                if (opti < args.length) {
15186                    try {
15187                        user = Integer.parseInt(args[opti]);
15188                    } catch (NumberFormatException e) {
15189                        pw.println("Error: check-permission user argument is not a number: "
15190                                + args[opti]);
15191                        return;
15192                    }
15193                }
15194                pw.println(checkPermission(perm, pkg, user));
15195                return;
15196            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15197                dumpState.setDump(DumpState.DUMP_LIBS);
15198            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15199                dumpState.setDump(DumpState.DUMP_FEATURES);
15200            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15201                dumpState.setDump(DumpState.DUMP_RESOLVERS);
15202            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15203                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15204            } else if ("permission".equals(cmd)) {
15205                if (opti >= args.length) {
15206                    pw.println("Error: permission requires permission name");
15207                    return;
15208                }
15209                permissionNames = new ArraySet<>();
15210                while (opti < args.length) {
15211                    permissionNames.add(args[opti]);
15212                    opti++;
15213                }
15214                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15215                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15216            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15217                dumpState.setDump(DumpState.DUMP_PREFERRED);
15218            } else if ("preferred-xml".equals(cmd)) {
15219                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15220                if (opti < args.length && "--full".equals(args[opti])) {
15221                    fullPreferred = true;
15222                    opti++;
15223                }
15224            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15225                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15226            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15227                dumpState.setDump(DumpState.DUMP_PACKAGES);
15228            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15229                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15230            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15231                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15232            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15233                dumpState.setDump(DumpState.DUMP_MESSAGES);
15234            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15235                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15236            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15237                    || "intent-filter-verifiers".equals(cmd)) {
15238                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15239            } else if ("version".equals(cmd)) {
15240                dumpState.setDump(DumpState.DUMP_VERSION);
15241            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15242                dumpState.setDump(DumpState.DUMP_KEYSETS);
15243            } else if ("installs".equals(cmd)) {
15244                dumpState.setDump(DumpState.DUMP_INSTALLS);
15245            } else if ("write".equals(cmd)) {
15246                synchronized (mPackages) {
15247                    mSettings.writeLPr();
15248                    pw.println("Settings written.");
15249                    return;
15250                }
15251            }
15252        }
15253
15254        if (checkin) {
15255            pw.println("vers,1");
15256        }
15257
15258        // reader
15259        synchronized (mPackages) {
15260            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15261                if (!checkin) {
15262                    if (dumpState.onTitlePrinted())
15263                        pw.println();
15264                    pw.println("Database versions:");
15265                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15266                }
15267            }
15268
15269            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15270                if (!checkin) {
15271                    if (dumpState.onTitlePrinted())
15272                        pw.println();
15273                    pw.println("Verifiers:");
15274                    pw.print("  Required: ");
15275                    pw.print(mRequiredVerifierPackage);
15276                    pw.print(" (uid=");
15277                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15278                    pw.println(")");
15279                } else if (mRequiredVerifierPackage != null) {
15280                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15281                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15282                }
15283            }
15284
15285            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15286                    packageName == null) {
15287                if (mIntentFilterVerifierComponent != null) {
15288                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15289                    if (!checkin) {
15290                        if (dumpState.onTitlePrinted())
15291                            pw.println();
15292                        pw.println("Intent Filter Verifier:");
15293                        pw.print("  Using: ");
15294                        pw.print(verifierPackageName);
15295                        pw.print(" (uid=");
15296                        pw.print(getPackageUid(verifierPackageName, 0));
15297                        pw.println(")");
15298                    } else if (verifierPackageName != null) {
15299                        pw.print("ifv,"); pw.print(verifierPackageName);
15300                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15301                    }
15302                } else {
15303                    pw.println();
15304                    pw.println("No Intent Filter Verifier available!");
15305                }
15306            }
15307
15308            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15309                boolean printedHeader = false;
15310                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15311                while (it.hasNext()) {
15312                    String name = it.next();
15313                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15314                    if (!checkin) {
15315                        if (!printedHeader) {
15316                            if (dumpState.onTitlePrinted())
15317                                pw.println();
15318                            pw.println("Libraries:");
15319                            printedHeader = true;
15320                        }
15321                        pw.print("  ");
15322                    } else {
15323                        pw.print("lib,");
15324                    }
15325                    pw.print(name);
15326                    if (!checkin) {
15327                        pw.print(" -> ");
15328                    }
15329                    if (ent.path != null) {
15330                        if (!checkin) {
15331                            pw.print("(jar) ");
15332                            pw.print(ent.path);
15333                        } else {
15334                            pw.print(",jar,");
15335                            pw.print(ent.path);
15336                        }
15337                    } else {
15338                        if (!checkin) {
15339                            pw.print("(apk) ");
15340                            pw.print(ent.apk);
15341                        } else {
15342                            pw.print(",apk,");
15343                            pw.print(ent.apk);
15344                        }
15345                    }
15346                    pw.println();
15347                }
15348            }
15349
15350            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15351                if (dumpState.onTitlePrinted())
15352                    pw.println();
15353                if (!checkin) {
15354                    pw.println("Features:");
15355                }
15356                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15357                while (it.hasNext()) {
15358                    String name = it.next();
15359                    if (!checkin) {
15360                        pw.print("  ");
15361                    } else {
15362                        pw.print("feat,");
15363                    }
15364                    pw.println(name);
15365                }
15366            }
15367
15368            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
15369                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15370                        : "Activity Resolver Table:", "  ", packageName,
15371                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15372                    dumpState.setTitlePrinted(true);
15373                }
15374                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15375                        : "Receiver Resolver Table:", "  ", packageName,
15376                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15377                    dumpState.setTitlePrinted(true);
15378                }
15379                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15380                        : "Service Resolver Table:", "  ", packageName,
15381                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15382                    dumpState.setTitlePrinted(true);
15383                }
15384                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15385                        : "Provider Resolver Table:", "  ", packageName,
15386                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15387                    dumpState.setTitlePrinted(true);
15388                }
15389            }
15390
15391            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15392                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15393                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15394                    int user = mSettings.mPreferredActivities.keyAt(i);
15395                    if (pir.dump(pw,
15396                            dumpState.getTitlePrinted()
15397                                ? "\nPreferred Activities User " + user + ":"
15398                                : "Preferred Activities User " + user + ":", "  ",
15399                            packageName, true, false)) {
15400                        dumpState.setTitlePrinted(true);
15401                    }
15402                }
15403            }
15404
15405            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15406                pw.flush();
15407                FileOutputStream fout = new FileOutputStream(fd);
15408                BufferedOutputStream str = new BufferedOutputStream(fout);
15409                XmlSerializer serializer = new FastXmlSerializer();
15410                try {
15411                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15412                    serializer.startDocument(null, true);
15413                    serializer.setFeature(
15414                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15415                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15416                    serializer.endDocument();
15417                    serializer.flush();
15418                } catch (IllegalArgumentException e) {
15419                    pw.println("Failed writing: " + e);
15420                } catch (IllegalStateException e) {
15421                    pw.println("Failed writing: " + e);
15422                } catch (IOException e) {
15423                    pw.println("Failed writing: " + e);
15424                }
15425            }
15426
15427            if (!checkin
15428                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15429                    && packageName == null) {
15430                pw.println();
15431                int count = mSettings.mPackages.size();
15432                if (count == 0) {
15433                    pw.println("No applications!");
15434                    pw.println();
15435                } else {
15436                    final String prefix = "  ";
15437                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15438                    if (allPackageSettings.size() == 0) {
15439                        pw.println("No domain preferred apps!");
15440                        pw.println();
15441                    } else {
15442                        pw.println("App verification status:");
15443                        pw.println();
15444                        count = 0;
15445                        for (PackageSetting ps : allPackageSettings) {
15446                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15447                            if (ivi == null || ivi.getPackageName() == null) continue;
15448                            pw.println(prefix + "Package: " + ivi.getPackageName());
15449                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15450                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15451                            pw.println();
15452                            count++;
15453                        }
15454                        if (count == 0) {
15455                            pw.println(prefix + "No app verification established.");
15456                            pw.println();
15457                        }
15458                        for (int userId : sUserManager.getUserIds()) {
15459                            pw.println("App linkages for user " + userId + ":");
15460                            pw.println();
15461                            count = 0;
15462                            for (PackageSetting ps : allPackageSettings) {
15463                                final long status = ps.getDomainVerificationStatusForUser(userId);
15464                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15465                                    continue;
15466                                }
15467                                pw.println(prefix + "Package: " + ps.name);
15468                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15469                                String statusStr = IntentFilterVerificationInfo.
15470                                        getStatusStringFromValue(status);
15471                                pw.println(prefix + "Status:  " + statusStr);
15472                                pw.println();
15473                                count++;
15474                            }
15475                            if (count == 0) {
15476                                pw.println(prefix + "No configured app linkages.");
15477                                pw.println();
15478                            }
15479                        }
15480                    }
15481                }
15482            }
15483
15484            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15485                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15486                if (packageName == null && permissionNames == null) {
15487                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15488                        if (iperm == 0) {
15489                            if (dumpState.onTitlePrinted())
15490                                pw.println();
15491                            pw.println("AppOp Permissions:");
15492                        }
15493                        pw.print("  AppOp Permission ");
15494                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15495                        pw.println(":");
15496                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15497                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15498                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15499                        }
15500                    }
15501                }
15502            }
15503
15504            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15505                boolean printedSomething = false;
15506                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15507                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15508                        continue;
15509                    }
15510                    if (!printedSomething) {
15511                        if (dumpState.onTitlePrinted())
15512                            pw.println();
15513                        pw.println("Registered ContentProviders:");
15514                        printedSomething = true;
15515                    }
15516                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15517                    pw.print("    "); pw.println(p.toString());
15518                }
15519                printedSomething = false;
15520                for (Map.Entry<String, PackageParser.Provider> entry :
15521                        mProvidersByAuthority.entrySet()) {
15522                    PackageParser.Provider p = entry.getValue();
15523                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15524                        continue;
15525                    }
15526                    if (!printedSomething) {
15527                        if (dumpState.onTitlePrinted())
15528                            pw.println();
15529                        pw.println("ContentProvider Authorities:");
15530                        printedSomething = true;
15531                    }
15532                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15533                    pw.print("    "); pw.println(p.toString());
15534                    if (p.info != null && p.info.applicationInfo != null) {
15535                        final String appInfo = p.info.applicationInfo.toString();
15536                        pw.print("      applicationInfo="); pw.println(appInfo);
15537                    }
15538                }
15539            }
15540
15541            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15542                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15543            }
15544
15545            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15546                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15547            }
15548
15549            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15550                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15551            }
15552
15553            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15554                // XXX should handle packageName != null by dumping only install data that
15555                // the given package is involved with.
15556                if (dumpState.onTitlePrinted()) pw.println();
15557                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15558            }
15559
15560            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15561                if (dumpState.onTitlePrinted()) pw.println();
15562                mSettings.dumpReadMessagesLPr(pw, dumpState);
15563
15564                pw.println();
15565                pw.println("Package warning messages:");
15566                BufferedReader in = null;
15567                String line = null;
15568                try {
15569                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15570                    while ((line = in.readLine()) != null) {
15571                        if (line.contains("ignored: updated version")) continue;
15572                        pw.println(line);
15573                    }
15574                } catch (IOException ignored) {
15575                } finally {
15576                    IoUtils.closeQuietly(in);
15577                }
15578            }
15579
15580            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15581                BufferedReader in = null;
15582                String line = null;
15583                try {
15584                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15585                    while ((line = in.readLine()) != null) {
15586                        if (line.contains("ignored: updated version")) continue;
15587                        pw.print("msg,");
15588                        pw.println(line);
15589                    }
15590                } catch (IOException ignored) {
15591                } finally {
15592                    IoUtils.closeQuietly(in);
15593                }
15594            }
15595        }
15596    }
15597
15598    private String dumpDomainString(String packageName) {
15599        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15600        List<IntentFilter> filters = getAllIntentFilters(packageName);
15601
15602        ArraySet<String> result = new ArraySet<>();
15603        if (iviList.size() > 0) {
15604            for (IntentFilterVerificationInfo ivi : iviList) {
15605                for (String host : ivi.getDomains()) {
15606                    result.add(host);
15607                }
15608            }
15609        }
15610        if (filters != null && filters.size() > 0) {
15611            for (IntentFilter filter : filters) {
15612                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15613                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15614                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15615                    result.addAll(filter.getHostsList());
15616                }
15617            }
15618        }
15619
15620        StringBuilder sb = new StringBuilder(result.size() * 16);
15621        for (String domain : result) {
15622            if (sb.length() > 0) sb.append(" ");
15623            sb.append(domain);
15624        }
15625        return sb.toString();
15626    }
15627
15628    // ------- apps on sdcard specific code -------
15629    static final boolean DEBUG_SD_INSTALL = false;
15630
15631    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15632
15633    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15634
15635    private boolean mMediaMounted = false;
15636
15637    static String getEncryptKey() {
15638        try {
15639            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15640                    SD_ENCRYPTION_KEYSTORE_NAME);
15641            if (sdEncKey == null) {
15642                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15643                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15644                if (sdEncKey == null) {
15645                    Slog.e(TAG, "Failed to create encryption keys");
15646                    return null;
15647                }
15648            }
15649            return sdEncKey;
15650        } catch (NoSuchAlgorithmException nsae) {
15651            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15652            return null;
15653        } catch (IOException ioe) {
15654            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15655            return null;
15656        }
15657    }
15658
15659    /*
15660     * Update media status on PackageManager.
15661     */
15662    @Override
15663    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15664        int callingUid = Binder.getCallingUid();
15665        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15666            throw new SecurityException("Media status can only be updated by the system");
15667        }
15668        // reader; this apparently protects mMediaMounted, but should probably
15669        // be a different lock in that case.
15670        synchronized (mPackages) {
15671            Log.i(TAG, "Updating external media status from "
15672                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15673                    + (mediaStatus ? "mounted" : "unmounted"));
15674            if (DEBUG_SD_INSTALL)
15675                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15676                        + ", mMediaMounted=" + mMediaMounted);
15677            if (mediaStatus == mMediaMounted) {
15678                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15679                        : 0, -1);
15680                mHandler.sendMessage(msg);
15681                return;
15682            }
15683            mMediaMounted = mediaStatus;
15684        }
15685        // Queue up an async operation since the package installation may take a
15686        // little while.
15687        mHandler.post(new Runnable() {
15688            public void run() {
15689                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15690            }
15691        });
15692    }
15693
15694    /**
15695     * Called by MountService when the initial ASECs to scan are available.
15696     * Should block until all the ASEC containers are finished being scanned.
15697     */
15698    public void scanAvailableAsecs() {
15699        updateExternalMediaStatusInner(true, false, false);
15700        if (mShouldRestoreconData) {
15701            SELinuxMMAC.setRestoreconDone();
15702            mShouldRestoreconData = false;
15703        }
15704    }
15705
15706    /*
15707     * Collect information of applications on external media, map them against
15708     * existing containers and update information based on current mount status.
15709     * Please note that we always have to report status if reportStatus has been
15710     * set to true especially when unloading packages.
15711     */
15712    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15713            boolean externalStorage) {
15714        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15715        int[] uidArr = EmptyArray.INT;
15716
15717        final String[] list = PackageHelper.getSecureContainerList();
15718        if (ArrayUtils.isEmpty(list)) {
15719            Log.i(TAG, "No secure containers found");
15720        } else {
15721            // Process list of secure containers and categorize them
15722            // as active or stale based on their package internal state.
15723
15724            // reader
15725            synchronized (mPackages) {
15726                for (String cid : list) {
15727                    // Leave stages untouched for now; installer service owns them
15728                    if (PackageInstallerService.isStageName(cid)) continue;
15729
15730                    if (DEBUG_SD_INSTALL)
15731                        Log.i(TAG, "Processing container " + cid);
15732                    String pkgName = getAsecPackageName(cid);
15733                    if (pkgName == null) {
15734                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15735                        continue;
15736                    }
15737                    if (DEBUG_SD_INSTALL)
15738                        Log.i(TAG, "Looking for pkg : " + pkgName);
15739
15740                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15741                    if (ps == null) {
15742                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15743                        continue;
15744                    }
15745
15746                    /*
15747                     * Skip packages that are not external if we're unmounting
15748                     * external storage.
15749                     */
15750                    if (externalStorage && !isMounted && !isExternal(ps)) {
15751                        continue;
15752                    }
15753
15754                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15755                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15756                    // The package status is changed only if the code path
15757                    // matches between settings and the container id.
15758                    if (ps.codePathString != null
15759                            && ps.codePathString.startsWith(args.getCodePath())) {
15760                        if (DEBUG_SD_INSTALL) {
15761                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15762                                    + " at code path: " + ps.codePathString);
15763                        }
15764
15765                        // We do have a valid package installed on sdcard
15766                        processCids.put(args, ps.codePathString);
15767                        final int uid = ps.appId;
15768                        if (uid != -1) {
15769                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15770                        }
15771                    } else {
15772                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15773                                + ps.codePathString);
15774                    }
15775                }
15776            }
15777
15778            Arrays.sort(uidArr);
15779        }
15780
15781        // Process packages with valid entries.
15782        if (isMounted) {
15783            if (DEBUG_SD_INSTALL)
15784                Log.i(TAG, "Loading packages");
15785            loadMediaPackages(processCids, uidArr, externalStorage);
15786            startCleaningPackages();
15787            mInstallerService.onSecureContainersAvailable();
15788        } else {
15789            if (DEBUG_SD_INSTALL)
15790                Log.i(TAG, "Unloading packages");
15791            unloadMediaPackages(processCids, uidArr, reportStatus);
15792        }
15793    }
15794
15795    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15796            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15797        final int size = infos.size();
15798        final String[] packageNames = new String[size];
15799        final int[] packageUids = new int[size];
15800        for (int i = 0; i < size; i++) {
15801            final ApplicationInfo info = infos.get(i);
15802            packageNames[i] = info.packageName;
15803            packageUids[i] = info.uid;
15804        }
15805        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15806                finishedReceiver);
15807    }
15808
15809    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15810            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15811        sendResourcesChangedBroadcast(mediaStatus, replacing,
15812                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15813    }
15814
15815    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15816            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15817        int size = pkgList.length;
15818        if (size > 0) {
15819            // Send broadcasts here
15820            Bundle extras = new Bundle();
15821            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15822            if (uidArr != null) {
15823                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15824            }
15825            if (replacing) {
15826                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15827            }
15828            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15829                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15830            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15831        }
15832    }
15833
15834   /*
15835     * Look at potentially valid container ids from processCids If package
15836     * information doesn't match the one on record or package scanning fails,
15837     * the cid is added to list of removeCids. We currently don't delete stale
15838     * containers.
15839     */
15840    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
15841            boolean externalStorage) {
15842        ArrayList<String> pkgList = new ArrayList<String>();
15843        Set<AsecInstallArgs> keys = processCids.keySet();
15844
15845        for (AsecInstallArgs args : keys) {
15846            String codePath = processCids.get(args);
15847            if (DEBUG_SD_INSTALL)
15848                Log.i(TAG, "Loading container : " + args.cid);
15849            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15850            try {
15851                // Make sure there are no container errors first.
15852                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15853                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15854                            + " when installing from sdcard");
15855                    continue;
15856                }
15857                // Check code path here.
15858                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15859                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15860                            + " does not match one in settings " + codePath);
15861                    continue;
15862                }
15863                // Parse package
15864                int parseFlags = mDefParseFlags;
15865                if (args.isExternalAsec()) {
15866                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15867                }
15868                if (args.isFwdLocked()) {
15869                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15870                }
15871
15872                synchronized (mInstallLock) {
15873                    PackageParser.Package pkg = null;
15874                    try {
15875                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
15876                    } catch (PackageManagerException e) {
15877                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15878                    }
15879                    // Scan the package
15880                    if (pkg != null) {
15881                        /*
15882                         * TODO why is the lock being held? doPostInstall is
15883                         * called in other places without the lock. This needs
15884                         * to be straightened out.
15885                         */
15886                        // writer
15887                        synchronized (mPackages) {
15888                            retCode = PackageManager.INSTALL_SUCCEEDED;
15889                            pkgList.add(pkg.packageName);
15890                            // Post process args
15891                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15892                                    pkg.applicationInfo.uid);
15893                        }
15894                    } else {
15895                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15896                    }
15897                }
15898
15899            } finally {
15900                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15901                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15902                }
15903            }
15904        }
15905        // writer
15906        synchronized (mPackages) {
15907            // If the platform SDK has changed since the last time we booted,
15908            // we need to re-grant app permission to catch any new ones that
15909            // appear. This is really a hack, and means that apps can in some
15910            // cases get permissions that the user didn't initially explicitly
15911            // allow... it would be nice to have some better way to handle
15912            // this situation.
15913            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
15914                    : mSettings.getInternalVersion();
15915            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
15916                    : StorageManager.UUID_PRIVATE_INTERNAL;
15917
15918            int updateFlags = UPDATE_PERMISSIONS_ALL;
15919            if (ver.sdkVersion != mSdkVersion) {
15920                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15921                        + mSdkVersion + "; regranting permissions for external");
15922                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15923            }
15924            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
15925
15926            // Yay, everything is now upgraded
15927            ver.forceCurrent();
15928
15929            // can downgrade to reader
15930            // Persist settings
15931            mSettings.writeLPr();
15932        }
15933        // Send a broadcast to let everyone know we are done processing
15934        if (pkgList.size() > 0) {
15935            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15936        }
15937    }
15938
15939   /*
15940     * Utility method to unload a list of specified containers
15941     */
15942    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15943        // Just unmount all valid containers.
15944        for (AsecInstallArgs arg : cidArgs) {
15945            synchronized (mInstallLock) {
15946                arg.doPostDeleteLI(false);
15947           }
15948       }
15949   }
15950
15951    /*
15952     * Unload packages mounted on external media. This involves deleting package
15953     * data from internal structures, sending broadcasts about diabled packages,
15954     * gc'ing to free up references, unmounting all secure containers
15955     * corresponding to packages on external media, and posting a
15956     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15957     * that we always have to post this message if status has been requested no
15958     * matter what.
15959     */
15960    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15961            final boolean reportStatus) {
15962        if (DEBUG_SD_INSTALL)
15963            Log.i(TAG, "unloading media packages");
15964        ArrayList<String> pkgList = new ArrayList<String>();
15965        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15966        final Set<AsecInstallArgs> keys = processCids.keySet();
15967        for (AsecInstallArgs args : keys) {
15968            String pkgName = args.getPackageName();
15969            if (DEBUG_SD_INSTALL)
15970                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15971            // Delete package internally
15972            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15973            synchronized (mInstallLock) {
15974                boolean res = deletePackageLI(pkgName, null, false, null, null,
15975                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15976                if (res) {
15977                    pkgList.add(pkgName);
15978                } else {
15979                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15980                    failedList.add(args);
15981                }
15982            }
15983        }
15984
15985        // reader
15986        synchronized (mPackages) {
15987            // We didn't update the settings after removing each package;
15988            // write them now for all packages.
15989            mSettings.writeLPr();
15990        }
15991
15992        // We have to absolutely send UPDATED_MEDIA_STATUS only
15993        // after confirming that all the receivers processed the ordered
15994        // broadcast when packages get disabled, force a gc to clean things up.
15995        // and unload all the containers.
15996        if (pkgList.size() > 0) {
15997            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15998                    new IIntentReceiver.Stub() {
15999                public void performReceive(Intent intent, int resultCode, String data,
16000                        Bundle extras, boolean ordered, boolean sticky,
16001                        int sendingUser) throws RemoteException {
16002                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16003                            reportStatus ? 1 : 0, 1, keys);
16004                    mHandler.sendMessage(msg);
16005                }
16006            });
16007        } else {
16008            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16009                    keys);
16010            mHandler.sendMessage(msg);
16011        }
16012    }
16013
16014    private void loadPrivatePackages(final VolumeInfo vol) {
16015        mHandler.post(new Runnable() {
16016            @Override
16017            public void run() {
16018                loadPrivatePackagesInner(vol);
16019            }
16020        });
16021    }
16022
16023    private void loadPrivatePackagesInner(VolumeInfo vol) {
16024        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16025        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16026
16027        final VersionInfo ver;
16028        final List<PackageSetting> packages;
16029        synchronized (mPackages) {
16030            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16031            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16032        }
16033
16034        for (PackageSetting ps : packages) {
16035            synchronized (mInstallLock) {
16036                final PackageParser.Package pkg;
16037                try {
16038                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16039                    loaded.add(pkg.applicationInfo);
16040                } catch (PackageManagerException e) {
16041                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16042                }
16043
16044                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16045                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16046                }
16047            }
16048        }
16049
16050        synchronized (mPackages) {
16051            int updateFlags = UPDATE_PERMISSIONS_ALL;
16052            if (ver.sdkVersion != mSdkVersion) {
16053                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16054                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16055                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16056            }
16057            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16058
16059            // Yay, everything is now upgraded
16060            ver.forceCurrent();
16061
16062            mSettings.writeLPr();
16063        }
16064
16065        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16066        sendResourcesChangedBroadcast(true, false, loaded, null);
16067    }
16068
16069    private void unloadPrivatePackages(final VolumeInfo vol) {
16070        mHandler.post(new Runnable() {
16071            @Override
16072            public void run() {
16073                unloadPrivatePackagesInner(vol);
16074            }
16075        });
16076    }
16077
16078    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16079        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16080        synchronized (mInstallLock) {
16081        synchronized (mPackages) {
16082            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16083            for (PackageSetting ps : packages) {
16084                if (ps.pkg == null) continue;
16085
16086                final ApplicationInfo info = ps.pkg.applicationInfo;
16087                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16088                if (deletePackageLI(ps.name, null, false, null, null,
16089                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16090                    unloaded.add(info);
16091                } else {
16092                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16093                }
16094            }
16095
16096            mSettings.writeLPr();
16097        }
16098        }
16099
16100        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16101        sendResourcesChangedBroadcast(false, false, unloaded, null);
16102    }
16103
16104    /**
16105     * Examine all users present on given mounted volume, and destroy data
16106     * belonging to users that are no longer valid, or whose user ID has been
16107     * recycled.
16108     */
16109    private void reconcileUsers(String volumeUuid) {
16110        final File[] files = FileUtils
16111                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16112        for (File file : files) {
16113            if (!file.isDirectory()) continue;
16114
16115            final int userId;
16116            final UserInfo info;
16117            try {
16118                userId = Integer.parseInt(file.getName());
16119                info = sUserManager.getUserInfo(userId);
16120            } catch (NumberFormatException e) {
16121                Slog.w(TAG, "Invalid user directory " + file);
16122                continue;
16123            }
16124
16125            boolean destroyUser = false;
16126            if (info == null) {
16127                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16128                        + " because no matching user was found");
16129                destroyUser = true;
16130            } else {
16131                try {
16132                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16133                } catch (IOException e) {
16134                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16135                            + " because we failed to enforce serial number: " + e);
16136                    destroyUser = true;
16137                }
16138            }
16139
16140            if (destroyUser) {
16141                synchronized (mInstallLock) {
16142                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16143                }
16144            }
16145        }
16146
16147        final UserManager um = mContext.getSystemService(UserManager.class);
16148        for (UserInfo user : um.getUsers()) {
16149            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16150            if (userDir.exists()) continue;
16151
16152            try {
16153                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
16154                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16155            } catch (IOException e) {
16156                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16157            }
16158        }
16159    }
16160
16161    /**
16162     * Examine all apps present on given mounted volume, and destroy apps that
16163     * aren't expected, either due to uninstallation or reinstallation on
16164     * another volume.
16165     */
16166    private void reconcileApps(String volumeUuid) {
16167        final File[] files = FileUtils
16168                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16169        for (File file : files) {
16170            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16171                    && !PackageInstallerService.isStageName(file.getName());
16172            if (!isPackage) {
16173                // Ignore entries which are not packages
16174                continue;
16175            }
16176
16177            boolean destroyApp = false;
16178            String packageName = null;
16179            try {
16180                final PackageLite pkg = PackageParser.parsePackageLite(file,
16181                        PackageParser.PARSE_MUST_BE_APK);
16182                packageName = pkg.packageName;
16183
16184                synchronized (mPackages) {
16185                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16186                    if (ps == null) {
16187                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16188                                + volumeUuid + " because we found no install record");
16189                        destroyApp = true;
16190                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16191                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16192                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16193                        destroyApp = true;
16194                    }
16195                }
16196
16197            } catch (PackageParserException e) {
16198                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16199                destroyApp = true;
16200            }
16201
16202            if (destroyApp) {
16203                synchronized (mInstallLock) {
16204                    if (packageName != null) {
16205                        removeDataDirsLI(volumeUuid, packageName);
16206                    }
16207                    if (file.isDirectory()) {
16208                        mInstaller.rmPackageDir(file.getAbsolutePath());
16209                    } else {
16210                        file.delete();
16211                    }
16212                }
16213            }
16214        }
16215    }
16216
16217    private void unfreezePackage(String packageName) {
16218        synchronized (mPackages) {
16219            final PackageSetting ps = mSettings.mPackages.get(packageName);
16220            if (ps != null) {
16221                ps.frozen = false;
16222            }
16223        }
16224    }
16225
16226    @Override
16227    public int movePackage(final String packageName, final String volumeUuid) {
16228        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16229
16230        final int moveId = mNextMoveId.getAndIncrement();
16231        try {
16232            movePackageInternal(packageName, volumeUuid, moveId);
16233        } catch (PackageManagerException e) {
16234            Slog.w(TAG, "Failed to move " + packageName, e);
16235            mMoveCallbacks.notifyStatusChanged(moveId,
16236                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16237        }
16238        return moveId;
16239    }
16240
16241    private void movePackageInternal(final String packageName, final String volumeUuid,
16242            final int moveId) throws PackageManagerException {
16243        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16244        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16245        final PackageManager pm = mContext.getPackageManager();
16246
16247        final boolean currentAsec;
16248        final String currentVolumeUuid;
16249        final File codeFile;
16250        final String installerPackageName;
16251        final String packageAbiOverride;
16252        final int appId;
16253        final String seinfo;
16254        final String label;
16255
16256        // reader
16257        synchronized (mPackages) {
16258            final PackageParser.Package pkg = mPackages.get(packageName);
16259            final PackageSetting ps = mSettings.mPackages.get(packageName);
16260            if (pkg == null || ps == null) {
16261                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16262            }
16263
16264            if (pkg.applicationInfo.isSystemApp()) {
16265                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16266                        "Cannot move system application");
16267            }
16268
16269            if (pkg.applicationInfo.isExternalAsec()) {
16270                currentAsec = true;
16271                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16272            } else if (pkg.applicationInfo.isForwardLocked()) {
16273                currentAsec = true;
16274                currentVolumeUuid = "forward_locked";
16275            } else {
16276                currentAsec = false;
16277                currentVolumeUuid = ps.volumeUuid;
16278
16279                final File probe = new File(pkg.codePath);
16280                final File probeOat = new File(probe, "oat");
16281                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16282                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16283                            "Move only supported for modern cluster style installs");
16284                }
16285            }
16286
16287            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16288                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16289                        "Package already moved to " + volumeUuid);
16290            }
16291
16292            if (ps.frozen) {
16293                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16294                        "Failed to move already frozen package");
16295            }
16296            ps.frozen = true;
16297
16298            codeFile = new File(pkg.codePath);
16299            installerPackageName = ps.installerPackageName;
16300            packageAbiOverride = ps.cpuAbiOverrideString;
16301            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16302            seinfo = pkg.applicationInfo.seinfo;
16303            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16304        }
16305
16306        // Now that we're guarded by frozen state, kill app during move
16307        final long token = Binder.clearCallingIdentity();
16308        try {
16309            killApplication(packageName, appId, "move pkg");
16310        } finally {
16311            Binder.restoreCallingIdentity(token);
16312        }
16313
16314        final Bundle extras = new Bundle();
16315        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16316        extras.putString(Intent.EXTRA_TITLE, label);
16317        mMoveCallbacks.notifyCreated(moveId, extras);
16318
16319        int installFlags;
16320        final boolean moveCompleteApp;
16321        final File measurePath;
16322
16323        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16324            installFlags = INSTALL_INTERNAL;
16325            moveCompleteApp = !currentAsec;
16326            measurePath = Environment.getDataAppDirectory(volumeUuid);
16327        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16328            installFlags = INSTALL_EXTERNAL;
16329            moveCompleteApp = false;
16330            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16331        } else {
16332            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16333            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16334                    || !volume.isMountedWritable()) {
16335                unfreezePackage(packageName);
16336                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16337                        "Move location not mounted private volume");
16338            }
16339
16340            Preconditions.checkState(!currentAsec);
16341
16342            installFlags = INSTALL_INTERNAL;
16343            moveCompleteApp = true;
16344            measurePath = Environment.getDataAppDirectory(volumeUuid);
16345        }
16346
16347        final PackageStats stats = new PackageStats(null, -1);
16348        synchronized (mInstaller) {
16349            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16350                unfreezePackage(packageName);
16351                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16352                        "Failed to measure package size");
16353            }
16354        }
16355
16356        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16357                + stats.dataSize);
16358
16359        final long startFreeBytes = measurePath.getFreeSpace();
16360        final long sizeBytes;
16361        if (moveCompleteApp) {
16362            sizeBytes = stats.codeSize + stats.dataSize;
16363        } else {
16364            sizeBytes = stats.codeSize;
16365        }
16366
16367        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16368            unfreezePackage(packageName);
16369            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16370                    "Not enough free space to move");
16371        }
16372
16373        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16374
16375        final CountDownLatch installedLatch = new CountDownLatch(1);
16376        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16377            @Override
16378            public void onUserActionRequired(Intent intent) throws RemoteException {
16379                throw new IllegalStateException();
16380            }
16381
16382            @Override
16383            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16384                    Bundle extras) throws RemoteException {
16385                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16386                        + PackageManager.installStatusToString(returnCode, msg));
16387
16388                installedLatch.countDown();
16389
16390                // Regardless of success or failure of the move operation,
16391                // always unfreeze the package
16392                unfreezePackage(packageName);
16393
16394                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16395                switch (status) {
16396                    case PackageInstaller.STATUS_SUCCESS:
16397                        mMoveCallbacks.notifyStatusChanged(moveId,
16398                                PackageManager.MOVE_SUCCEEDED);
16399                        break;
16400                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16401                        mMoveCallbacks.notifyStatusChanged(moveId,
16402                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16403                        break;
16404                    default:
16405                        mMoveCallbacks.notifyStatusChanged(moveId,
16406                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16407                        break;
16408                }
16409            }
16410        };
16411
16412        final MoveInfo move;
16413        if (moveCompleteApp) {
16414            // Kick off a thread to report progress estimates
16415            new Thread() {
16416                @Override
16417                public void run() {
16418                    while (true) {
16419                        try {
16420                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16421                                break;
16422                            }
16423                        } catch (InterruptedException ignored) {
16424                        }
16425
16426                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16427                        final int progress = 10 + (int) MathUtils.constrain(
16428                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16429                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16430                    }
16431                }
16432            }.start();
16433
16434            final String dataAppName = codeFile.getName();
16435            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16436                    dataAppName, appId, seinfo);
16437        } else {
16438            move = null;
16439        }
16440
16441        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16442
16443        final Message msg = mHandler.obtainMessage(INIT_COPY);
16444        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16445        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16446                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16447        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16448        msg.obj = params;
16449
16450        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16451                System.identityHashCode(msg.obj));
16452        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16453                System.identityHashCode(msg.obj));
16454
16455        mHandler.sendMessage(msg);
16456    }
16457
16458    @Override
16459    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16460        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16461
16462        final int realMoveId = mNextMoveId.getAndIncrement();
16463        final Bundle extras = new Bundle();
16464        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16465        mMoveCallbacks.notifyCreated(realMoveId, extras);
16466
16467        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16468            @Override
16469            public void onCreated(int moveId, Bundle extras) {
16470                // Ignored
16471            }
16472
16473            @Override
16474            public void onStatusChanged(int moveId, int status, long estMillis) {
16475                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16476            }
16477        };
16478
16479        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16480        storage.setPrimaryStorageUuid(volumeUuid, callback);
16481        return realMoveId;
16482    }
16483
16484    @Override
16485    public int getMoveStatus(int moveId) {
16486        mContext.enforceCallingOrSelfPermission(
16487                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16488        return mMoveCallbacks.mLastStatus.get(moveId);
16489    }
16490
16491    @Override
16492    public void registerMoveCallback(IPackageMoveObserver callback) {
16493        mContext.enforceCallingOrSelfPermission(
16494                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16495        mMoveCallbacks.register(callback);
16496    }
16497
16498    @Override
16499    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16500        mContext.enforceCallingOrSelfPermission(
16501                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16502        mMoveCallbacks.unregister(callback);
16503    }
16504
16505    @Override
16506    public boolean setInstallLocation(int loc) {
16507        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16508                null);
16509        if (getInstallLocation() == loc) {
16510            return true;
16511        }
16512        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16513                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16514            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16515                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16516            return true;
16517        }
16518        return false;
16519   }
16520
16521    @Override
16522    public int getInstallLocation() {
16523        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16524                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16525                PackageHelper.APP_INSTALL_AUTO);
16526    }
16527
16528    /** Called by UserManagerService */
16529    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16530        mDirtyUsers.remove(userHandle);
16531        mSettings.removeUserLPw(userHandle);
16532        mPendingBroadcasts.remove(userHandle);
16533        if (mInstaller != null) {
16534            // Technically, we shouldn't be doing this with the package lock
16535            // held.  However, this is very rare, and there is already so much
16536            // other disk I/O going on, that we'll let it slide for now.
16537            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16538            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16539                final String volumeUuid = vol.getFsUuid();
16540                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16541                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16542            }
16543        }
16544        mUserNeedsBadging.delete(userHandle);
16545        removeUnusedPackagesLILPw(userManager, userHandle);
16546    }
16547
16548    /**
16549     * We're removing userHandle and would like to remove any downloaded packages
16550     * that are no longer in use by any other user.
16551     * @param userHandle the user being removed
16552     */
16553    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16554        final boolean DEBUG_CLEAN_APKS = false;
16555        int [] users = userManager.getUserIds();
16556        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16557        while (psit.hasNext()) {
16558            PackageSetting ps = psit.next();
16559            if (ps.pkg == null) {
16560                continue;
16561            }
16562            final String packageName = ps.pkg.packageName;
16563            // Skip over if system app
16564            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16565                continue;
16566            }
16567            if (DEBUG_CLEAN_APKS) {
16568                Slog.i(TAG, "Checking package " + packageName);
16569            }
16570            boolean keep = false;
16571            for (int i = 0; i < users.length; i++) {
16572                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16573                    keep = true;
16574                    if (DEBUG_CLEAN_APKS) {
16575                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16576                                + users[i]);
16577                    }
16578                    break;
16579                }
16580            }
16581            if (!keep) {
16582                if (DEBUG_CLEAN_APKS) {
16583                    Slog.i(TAG, "  Removing package " + packageName);
16584                }
16585                mHandler.post(new Runnable() {
16586                    public void run() {
16587                        deletePackageX(packageName, userHandle, 0);
16588                    } //end run
16589                });
16590            }
16591        }
16592    }
16593
16594    /** Called by UserManagerService */
16595    void createNewUserLILPw(int userHandle) {
16596        if (mInstaller != null) {
16597            mInstaller.createUserConfig(userHandle);
16598            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16599            applyFactoryDefaultBrowserLPw(userHandle);
16600            primeDomainVerificationsLPw(userHandle);
16601        }
16602    }
16603
16604    void newUserCreated(final int userHandle) {
16605        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16606    }
16607
16608    @Override
16609    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16610        mContext.enforceCallingOrSelfPermission(
16611                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16612                "Only package verification agents can read the verifier device identity");
16613
16614        synchronized (mPackages) {
16615            return mSettings.getVerifierDeviceIdentityLPw();
16616        }
16617    }
16618
16619    @Override
16620    public void setPermissionEnforced(String permission, boolean enforced) {
16621        // TODO: Now that we no longer change GID for storage, this should to away.
16622        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16623                "setPermissionEnforced");
16624        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16625            synchronized (mPackages) {
16626                if (mSettings.mReadExternalStorageEnforced == null
16627                        || mSettings.mReadExternalStorageEnforced != enforced) {
16628                    mSettings.mReadExternalStorageEnforced = enforced;
16629                    mSettings.writeLPr();
16630                }
16631            }
16632            // kill any non-foreground processes so we restart them and
16633            // grant/revoke the GID.
16634            final IActivityManager am = ActivityManagerNative.getDefault();
16635            if (am != null) {
16636                final long token = Binder.clearCallingIdentity();
16637                try {
16638                    am.killProcessesBelowForeground("setPermissionEnforcement");
16639                } catch (RemoteException e) {
16640                } finally {
16641                    Binder.restoreCallingIdentity(token);
16642                }
16643            }
16644        } else {
16645            throw new IllegalArgumentException("No selective enforcement for " + permission);
16646        }
16647    }
16648
16649    @Override
16650    @Deprecated
16651    public boolean isPermissionEnforced(String permission) {
16652        return true;
16653    }
16654
16655    @Override
16656    public boolean isStorageLow() {
16657        final long token = Binder.clearCallingIdentity();
16658        try {
16659            final DeviceStorageMonitorInternal
16660                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16661            if (dsm != null) {
16662                return dsm.isMemoryLow();
16663            } else {
16664                return false;
16665            }
16666        } finally {
16667            Binder.restoreCallingIdentity(token);
16668        }
16669    }
16670
16671    @Override
16672    public IPackageInstaller getPackageInstaller() {
16673        return mInstallerService;
16674    }
16675
16676    private boolean userNeedsBadging(int userId) {
16677        int index = mUserNeedsBadging.indexOfKey(userId);
16678        if (index < 0) {
16679            final UserInfo userInfo;
16680            final long token = Binder.clearCallingIdentity();
16681            try {
16682                userInfo = sUserManager.getUserInfo(userId);
16683            } finally {
16684                Binder.restoreCallingIdentity(token);
16685            }
16686            final boolean b;
16687            if (userInfo != null && userInfo.isManagedProfile()) {
16688                b = true;
16689            } else {
16690                b = false;
16691            }
16692            mUserNeedsBadging.put(userId, b);
16693            return b;
16694        }
16695        return mUserNeedsBadging.valueAt(index);
16696    }
16697
16698    @Override
16699    public KeySet getKeySetByAlias(String packageName, String alias) {
16700        if (packageName == null || alias == null) {
16701            return null;
16702        }
16703        synchronized(mPackages) {
16704            final PackageParser.Package pkg = mPackages.get(packageName);
16705            if (pkg == null) {
16706                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16707                throw new IllegalArgumentException("Unknown package: " + packageName);
16708            }
16709            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16710            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16711        }
16712    }
16713
16714    @Override
16715    public KeySet getSigningKeySet(String packageName) {
16716        if (packageName == null) {
16717            return null;
16718        }
16719        synchronized(mPackages) {
16720            final PackageParser.Package pkg = mPackages.get(packageName);
16721            if (pkg == null) {
16722                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16723                throw new IllegalArgumentException("Unknown package: " + packageName);
16724            }
16725            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16726                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16727                throw new SecurityException("May not access signing KeySet of other apps.");
16728            }
16729            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16730            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16731        }
16732    }
16733
16734    @Override
16735    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16736        if (packageName == null || ks == null) {
16737            return false;
16738        }
16739        synchronized(mPackages) {
16740            final PackageParser.Package pkg = mPackages.get(packageName);
16741            if (pkg == null) {
16742                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16743                throw new IllegalArgumentException("Unknown package: " + packageName);
16744            }
16745            IBinder ksh = ks.getToken();
16746            if (ksh instanceof KeySetHandle) {
16747                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16748                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16749            }
16750            return false;
16751        }
16752    }
16753
16754    @Override
16755    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16756        if (packageName == null || ks == null) {
16757            return false;
16758        }
16759        synchronized(mPackages) {
16760            final PackageParser.Package pkg = mPackages.get(packageName);
16761            if (pkg == null) {
16762                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16763                throw new IllegalArgumentException("Unknown package: " + packageName);
16764            }
16765            IBinder ksh = ks.getToken();
16766            if (ksh instanceof KeySetHandle) {
16767                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16768                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16769            }
16770            return false;
16771        }
16772    }
16773
16774    public void getUsageStatsIfNoPackageUsageInfo() {
16775        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16776            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16777            if (usm == null) {
16778                throw new IllegalStateException("UsageStatsManager must be initialized");
16779            }
16780            long now = System.currentTimeMillis();
16781            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16782            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16783                String packageName = entry.getKey();
16784                PackageParser.Package pkg = mPackages.get(packageName);
16785                if (pkg == null) {
16786                    continue;
16787                }
16788                UsageStats usage = entry.getValue();
16789                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16790                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16791            }
16792        }
16793    }
16794
16795    /**
16796     * Check and throw if the given before/after packages would be considered a
16797     * downgrade.
16798     */
16799    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16800            throws PackageManagerException {
16801        if (after.versionCode < before.mVersionCode) {
16802            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16803                    "Update version code " + after.versionCode + " is older than current "
16804                    + before.mVersionCode);
16805        } else if (after.versionCode == before.mVersionCode) {
16806            if (after.baseRevisionCode < before.baseRevisionCode) {
16807                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16808                        "Update base revision code " + after.baseRevisionCode
16809                        + " is older than current " + before.baseRevisionCode);
16810            }
16811
16812            if (!ArrayUtils.isEmpty(after.splitNames)) {
16813                for (int i = 0; i < after.splitNames.length; i++) {
16814                    final String splitName = after.splitNames[i];
16815                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16816                    if (j != -1) {
16817                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16818                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16819                                    "Update split " + splitName + " revision code "
16820                                    + after.splitRevisionCodes[i] + " is older than current "
16821                                    + before.splitRevisionCodes[j]);
16822                        }
16823                    }
16824                }
16825            }
16826        }
16827    }
16828
16829    private static class MoveCallbacks extends Handler {
16830        private static final int MSG_CREATED = 1;
16831        private static final int MSG_STATUS_CHANGED = 2;
16832
16833        private final RemoteCallbackList<IPackageMoveObserver>
16834                mCallbacks = new RemoteCallbackList<>();
16835
16836        private final SparseIntArray mLastStatus = new SparseIntArray();
16837
16838        public MoveCallbacks(Looper looper) {
16839            super(looper);
16840        }
16841
16842        public void register(IPackageMoveObserver callback) {
16843            mCallbacks.register(callback);
16844        }
16845
16846        public void unregister(IPackageMoveObserver callback) {
16847            mCallbacks.unregister(callback);
16848        }
16849
16850        @Override
16851        public void handleMessage(Message msg) {
16852            final SomeArgs args = (SomeArgs) msg.obj;
16853            final int n = mCallbacks.beginBroadcast();
16854            for (int i = 0; i < n; i++) {
16855                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16856                try {
16857                    invokeCallback(callback, msg.what, args);
16858                } catch (RemoteException ignored) {
16859                }
16860            }
16861            mCallbacks.finishBroadcast();
16862            args.recycle();
16863        }
16864
16865        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16866                throws RemoteException {
16867            switch (what) {
16868                case MSG_CREATED: {
16869                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16870                    break;
16871                }
16872                case MSG_STATUS_CHANGED: {
16873                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16874                    break;
16875                }
16876            }
16877        }
16878
16879        private void notifyCreated(int moveId, Bundle extras) {
16880            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16881
16882            final SomeArgs args = SomeArgs.obtain();
16883            args.argi1 = moveId;
16884            args.arg2 = extras;
16885            obtainMessage(MSG_CREATED, args).sendToTarget();
16886        }
16887
16888        private void notifyStatusChanged(int moveId, int status) {
16889            notifyStatusChanged(moveId, status, -1);
16890        }
16891
16892        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16893            Slog.v(TAG, "Move " + moveId + " status " + status);
16894
16895            final SomeArgs args = SomeArgs.obtain();
16896            args.argi1 = moveId;
16897            args.argi2 = status;
16898            args.arg3 = estMillis;
16899            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16900
16901            synchronized (mLastStatus) {
16902                mLastStatus.put(moveId, status);
16903            }
16904        }
16905    }
16906
16907    private final class OnPermissionChangeListeners extends Handler {
16908        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16909
16910        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16911                new RemoteCallbackList<>();
16912
16913        public OnPermissionChangeListeners(Looper looper) {
16914            super(looper);
16915        }
16916
16917        @Override
16918        public void handleMessage(Message msg) {
16919            switch (msg.what) {
16920                case MSG_ON_PERMISSIONS_CHANGED: {
16921                    final int uid = msg.arg1;
16922                    handleOnPermissionsChanged(uid);
16923                } break;
16924            }
16925        }
16926
16927        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16928            mPermissionListeners.register(listener);
16929
16930        }
16931
16932        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16933            mPermissionListeners.unregister(listener);
16934        }
16935
16936        public void onPermissionsChanged(int uid) {
16937            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16938                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16939            }
16940        }
16941
16942        private void handleOnPermissionsChanged(int uid) {
16943            final int count = mPermissionListeners.beginBroadcast();
16944            try {
16945                for (int i = 0; i < count; i++) {
16946                    IOnPermissionsChangeListener callback = mPermissionListeners
16947                            .getBroadcastItem(i);
16948                    try {
16949                        callback.onPermissionsChanged(uid);
16950                    } catch (RemoteException e) {
16951                        Log.e(TAG, "Permission listener is dead", e);
16952                    }
16953                }
16954            } finally {
16955                mPermissionListeners.finishBroadcast();
16956            }
16957        }
16958    }
16959
16960    private class PackageManagerInternalImpl extends PackageManagerInternal {
16961        @Override
16962        public void setLocationPackagesProvider(PackagesProvider provider) {
16963            synchronized (mPackages) {
16964                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16965            }
16966        }
16967
16968        @Override
16969        public void setImePackagesProvider(PackagesProvider provider) {
16970            synchronized (mPackages) {
16971                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16972            }
16973        }
16974
16975        @Override
16976        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16977            synchronized (mPackages) {
16978                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16979            }
16980        }
16981
16982        @Override
16983        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16984            synchronized (mPackages) {
16985                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16986            }
16987        }
16988
16989        @Override
16990        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16991            synchronized (mPackages) {
16992                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16993            }
16994        }
16995
16996        @Override
16997        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16998            synchronized (mPackages) {
16999                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17000            }
17001        }
17002
17003        @Override
17004        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17005            synchronized (mPackages) {
17006                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17007            }
17008        }
17009
17010        @Override
17011        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17012            synchronized (mPackages) {
17013                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17014                        packageName, userId);
17015            }
17016        }
17017
17018        @Override
17019        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17020            synchronized (mPackages) {
17021                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17022                        packageName, userId);
17023            }
17024        }
17025        @Override
17026        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17027            synchronized (mPackages) {
17028                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17029                        packageName, userId);
17030            }
17031        }
17032    }
17033
17034    @Override
17035    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17036        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17037        synchronized (mPackages) {
17038            final long identity = Binder.clearCallingIdentity();
17039            try {
17040                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17041                        packageNames, userId);
17042            } finally {
17043                Binder.restoreCallingIdentity(identity);
17044            }
17045        }
17046    }
17047
17048    private static void enforceSystemOrPhoneCaller(String tag) {
17049        int callingUid = Binder.getCallingUid();
17050        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17051            throw new SecurityException(
17052                    "Cannot call " + tag + " from UID " + callingUid);
17053        }
17054    }
17055}
17056